hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
108
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequencelengths 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
sequencelengths 1
9
| max_issues_count
int64 1
67k
⌀ | 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2bdbc50e549bfb226810973b8bf1226419c5cf0 | 14,845 | cpp | C++ | implementations/ugene/src/libs_3rdparty/QSpec/src/primitives/GTWidget.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/libs_3rdparty/QSpec/src/primitives/GTWidget.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | implementations/ugene/src/libs_3rdparty/QSpec/src/primitives/GTWidget.cpp | r-barnes/sw_comparison | 1ac2c9cc10a32badd6b8fb1e96516c97f7800176 | [
"BSD-Source-Code"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <ugene@unipro.ru>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "primitives/GTWidget.h"
#include <QApplication>
#include <QComboBox>
#include <QDesktopWidget>
#include <QGuiApplication>
#include <QLineEdit>
#include <QStyle>
#include "drivers/GTMouseDriver.h"
#include "primitives/GTMainWindow.h"
#include "utils/GTThread.h"
namespace HI {
#define GT_CLASS_NAME "GTWidget"
#define GT_METHOD_NAME "click"
void GTWidget::click(GUITestOpStatus &os, QWidget *widget, Qt::MouseButton mouseButton, QPoint p) {
GT_CHECK(widget != nullptr, "widget is NULL");
if (p.isNull()) {
p = widget->rect().center();
// TODO: this is a fast fix
if (widget->objectName().contains("ADV_single_sequence_widget")) {
p += QPoint(0, 8);
}
}
QPoint globalPoint = widget->mapToGlobal(p);
GTMouseDriver::moveTo(globalPoint);
GTMouseDriver::click(mouseButton);
GTThread::waitForMainThread();
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "setFocus"
void GTWidget::setFocus(GUITestOpStatus &os, QWidget *w) {
GT_CHECK(w != NULL, "widget is NULL");
GTWidget::click(os, w);
GTGlobals::sleep(200);
if (!qobject_cast<QComboBox *>(w)) {
GT_CHECK(w->hasFocus(), QString("Can't set focus on widget '%1'").arg(w->objectName()));
}
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "findWidget"
QWidget *GTWidget::findWidget(GUITestOpStatus &os, const QString &widgetName, QWidget const *const parentWidget, const GTGlobals::FindOptions &options) {
QWidget *widget = nullptr;
for (int time = 0; time < GT_OP_WAIT_MILLIS && widget == nullptr; time += GT_OP_CHECK_MILLIS) {
GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS : 0);
if (parentWidget == nullptr) {
QList<QWidget *> allWidgetList;
foreach (QWidget *parent, GTMainWindow::getMainWindowsAsWidget(os)) {
allWidgetList << parent->findChildren<QWidget *>(widgetName);
}
int nMatches = allWidgetList.count();
GT_CHECK_RESULT(nMatches < 2, QString("There are %1 widgets with name '%2'").arg(nMatches).arg(widgetName), nullptr);
widget = nMatches == 1 ? allWidgetList.first() : nullptr;
} else {
widget = parentWidget->findChild<QWidget *>(widgetName);
}
if (!options.failIfNotFound) {
break;
}
}
if (options.failIfNotFound) {
GT_CHECK_RESULT(widget != nullptr, QString("Widget '%1' not found").arg(widgetName), NULL);
}
return widget;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getWidgetCenter"
QPoint GTWidget::getWidgetCenter(QWidget *widget) {
return widget->mapToGlobal(widget->rect().center());
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "findButtonByText"
QAbstractButton *GTWidget::findButtonByText(GUITestOpStatus &os, const QString &text, QWidget *parentWidget, const GTGlobals::FindOptions &options) {
QList<QAbstractButton *> resultButtonList;
for (int time = 0; time < GT_OP_WAIT_MILLIS && resultButtonList.isEmpty(); time += GT_OP_CHECK_MILLIS) {
GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS : 0);
QList<QAbstractButton *> allButtonList;
if (parentWidget == nullptr) {
foreach (QWidget *mainWidget, GTMainWindow::getMainWindowsAsWidget(os)) {
allButtonList << mainWidget->findChildren<QAbstractButton *>();
}
} else {
allButtonList << parentWidget->findChildren<QAbstractButton *>();
}
foreach (QAbstractButton *button, allButtonList) {
if (button->text().contains(text, Qt::CaseInsensitive)) {
resultButtonList << button;
}
}
if (!options.failIfNotFound) {
break;
}
}
GT_CHECK_RESULT(resultButtonList.count() <= 1, QString("There are %1 buttons with text").arg(resultButtonList.count()), nullptr);
if (options.failIfNotFound) {
GT_CHECK_RESULT(resultButtonList.count() != 0, QString("Button with the text <%1> is not found").arg(text), nullptr);
}
return resultButtonList.isEmpty() ? nullptr : resultButtonList.first();
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "findLabelByText"
QList<QLabel *> GTWidget::findLabelByText(GUITestOpStatus &os,
const QString &text,
QWidget *parentWidget,
const GTGlobals::FindOptions &options) {
QList<QLabel *> resultLabelList;
for (int time = 0; time < GT_OP_WAIT_MILLIS; time += GT_OP_CHECK_MILLIS) {
GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS && resultLabelList.isEmpty() : 0);
QList<QLabel *> allLabelList;
if (parentWidget == nullptr) {
foreach (QWidget *windowWidget, GTMainWindow::getMainWindowsAsWidget(os)) {
allLabelList << windowWidget->findChildren<QLabel *>();
}
} else {
allLabelList << parentWidget->findChildren<QLabel *>();
}
foreach (QLabel *label, allLabelList) {
if (label->text().contains(text, Qt::CaseInsensitive)) {
resultLabelList << label;
}
}
}
if (options.failIfNotFound) {
GT_CHECK_RESULT(resultLabelList.count() > 0, QString("Label with this text <%1> not found").arg(text), QList<QLabel *>());
}
return resultLabelList;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "close"
void GTWidget::close(GUITestOpStatus &os, QWidget *widget) {
GT_CHECK(widget != nullptr, "Widget is NULL");
class Scenario : public CustomScenario {
public:
Scenario(QWidget *widget)
: widget(widget) {
}
void run(GUITestOpStatus &os) {
Q_UNUSED(os);
CHECK_SET_ERR(widget != nullptr, "Widget is NULL");
widget->close();
GTGlobals::sleep(100);
}
private:
QWidget *widget;
};
GTThread::runInMainThread(os, new Scenario(widget));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "showMaximized"
void GTWidget::showMaximized(GUITestOpStatus &os, QWidget *widget) {
GT_CHECK(widget != nullptr, "Widget is NULL");
class Scenario : public CustomScenario {
public:
Scenario(QWidget *widget)
: widget(widget) {
}
void run(GUITestOpStatus &os) {
Q_UNUSED(os);
CHECK_SET_ERR(widget != nullptr, "Widget is NULL");
widget->showMaximized();
GTGlobals::sleep(100);
}
private:
QWidget *widget;
};
GTThread::runInMainThread(os, new Scenario(widget));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "showNormal"
void GTWidget::showNormal(GUITestOpStatus &os, QWidget *widget) {
GT_CHECK(widget != nullptr, "Widget is NULL");
class Scenario : public CustomScenario {
public:
Scenario(QWidget *widget)
: widget(widget) {
}
void run(GUITestOpStatus &os) {
Q_UNUSED(os);
CHECK_SET_ERR(widget != nullptr, "Widget is NULL");
widget->showNormal();
GTGlobals::sleep(100);
}
private:
QWidget *widget;
};
GTThread::runInMainThread(os, new Scenario(widget));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getColor"
QColor GTWidget::getColor(GUITestOpStatus &os, QWidget *widget, const QPoint &point) {
GT_CHECK_RESULT(widget != nullptr, "Widget is NULL", QColor());
return QColor(getImage(os, widget).pixel(point));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getImage"
QImage GTWidget::getImage(GUITestOpStatus &os, QWidget *widget) {
GT_CHECK_RESULT(widget != nullptr, "Widget is NULL", QImage());
class Scenario : public CustomScenario {
public:
Scenario(QWidget *widget, QImage &image)
: widget(widget),
image(image) {
}
void run(GUITestOpStatus &os) {
CHECK_SET_ERR(widget != nullptr, "Widget to grab is NULL");
image = widget->grab(widget->rect()).toImage();
}
private:
QWidget *widget;
QImage ℑ
};
QImage image;
GTThread::runInMainThread(os, new Scenario(widget, image));
return image;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "clickLabelLink"
void GTWidget::clickLabelLink(GUITestOpStatus &os, QWidget *label, int step, int indent) {
QRect r = label->rect();
int left = r.left();
int right = r.right();
int top = r.top() + indent;
int bottom = r.bottom();
for (int i = left; i < right; i += step) {
for (int j = top; j < bottom; j += step) {
GTMouseDriver::moveTo(label->mapToGlobal(QPoint(i, j)));
if (label->cursor().shape() == Qt::PointingHandCursor) {
GTGlobals::sleep(500);
GTMouseDriver::click();
return;
}
}
}
GT_CHECK(false, "label does not contain link");
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "clickWindowTitle"
void GTWidget::clickWindowTitle(GUITestOpStatus &os, QWidget *window) {
GT_CHECK(window != nullptr, "Window is NULL");
QStyleOptionTitleBar opt;
opt.initFrom(window);
const QRect titleLabelRect = window->style()->subControlRect(QStyle::CC_TitleBar, &opt, QStyle::SC_TitleBarLabel);
GTMouseDriver::moveTo(getWidgetGlobalTopLeftPoint(os, window) + titleLabelRect.center());
GTMouseDriver::click();
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "moveWidgetTo"
void GTWidget::moveWidgetTo(GUITestOpStatus &os, QWidget *window, const QPoint &point) {
//QPoint(window->width()/2,3) - is hack
GTMouseDriver::moveTo(getWidgetGlobalTopLeftPoint(os, window) + QPoint(window->width() / 2, 3));
const QPoint p0 = getWidgetGlobalTopLeftPoint(os, window) + QPoint(window->width() / 2, 3);
const QPoint p1 = point + QPoint(window->width() / 2, 3);
GTMouseDriver::dragAndDrop(p0, p1);
GTGlobals::sleep(1000);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "resizeWidget"
void GTWidget::resizeWidget(GUITestOpStatus &os, QWidget *widget, const QSize &size) {
GT_CHECK(widget != nullptr, "Widget is NULL");
QRect displayRect = QApplication::desktop()->screenGeometry();
GT_CHECK((displayRect.width() >= size.width()) && (displayRect.height() >= size.height()), "Specified the size larger than the size of the screen");
bool isRequiredPositionFound = false;
QSize oldSize = widget->size();
QPoint topLeftPos = getWidgetGlobalTopLeftPoint(os, widget) + QPoint(5, 5);
for (int i = 0; i < 5; i++) {
GTMouseDriver::moveTo(topLeftPos);
QPoint newTopLeftPos = topLeftPos + QPoint(widget->frameGeometry().width() - 1, widget->frameGeometry().height() - 1) - QPoint(size.width(), size.height());
GTMouseDriver::dragAndDrop(topLeftPos, newTopLeftPos);
if (widget->size() != oldSize) {
isRequiredPositionFound = true;
break;
} else {
topLeftPos -= QPoint(1, 1);
}
}
GT_CHECK(isRequiredPositionFound, "Required mouse position to start window resize was not found");
GTGlobals::sleep(1000);
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getWidgetGlobalTopLeftPoint"
QPoint GTWidget::getWidgetGlobalTopLeftPoint(GUITestOpStatus &os, QWidget *widget) {
GT_CHECK_RESULT(widget != nullptr, "Widget is NULL", QPoint());
return (widget->isWindow() ? widget->pos() : widget->parentWidget()->mapToGlobal(QPoint(0, 0)));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getActiveModalWidget"
QWidget *GTWidget::getActiveModalWidget(GUITestOpStatus &os) {
QWidget *modalWidget = nullptr;
for (int time = 0; time < GT_OP_WAIT_MILLIS && modalWidget == nullptr; time += GT_OP_CHECK_MILLIS) {
GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS : 0);
modalWidget = QApplication::activeModalWidget();
}
GT_CHECK_RESULT(modalWidget != nullptr, "Active modal widget is NULL", nullptr);
return modalWidget;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getActivePopupWidget"
QWidget *GTWidget::getActivePopupWidget(GUITestOpStatus &os) {
QWidget *popupWidget = nullptr;
for (int time = 0; time < GT_OP_WAIT_MILLIS && popupWidget == nullptr; time += GT_OP_CHECK_MILLIS) {
GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS : 0);
popupWidget = QApplication::activePopupWidget();
}
GT_CHECK_RESULT(popupWidget != nullptr, "Active popup widget is NULL", nullptr);
return popupWidget;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "getActivePopupMenu"
QMenu *GTWidget::getActivePopupMenu(GUITestOpStatus &os) {
QMenu *popupWidget = nullptr;
for (int time = 0; time < GT_OP_WAIT_MILLIS && popupWidget == nullptr; time += GT_OP_CHECK_MILLIS) {
GTGlobals::sleep(time > 0 ? GT_OP_CHECK_MILLIS : 0);
popupWidget = qobject_cast<QMenu *>(QApplication::activePopupWidget());
}
GT_CHECK_RESULT(popupWidget != nullptr, "Active popup menu is NULL", nullptr);
return popupWidget;
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "checkEnabled"
void GTWidget::checkEnabled(GUITestOpStatus &os, QWidget *widget, bool expectedEnabledState) {
GT_CHECK(widget != nullptr, "Widget is NULL");
GT_CHECK(widget->isVisible(), "Widget is not visible");
bool actualEnabledState = widget->isEnabled();
GT_CHECK(expectedEnabledState == actualEnabledState,
QString("Widget state is incorrect: expected '%1', got '%'2")
.arg(expectedEnabledState ? "enabled" : "disabled")
.arg(actualEnabledState ? "enabled" : "disabled"));
}
#undef GT_METHOD_NAME
#define GT_METHOD_NAME "checkEnabled"
void GTWidget::checkEnabled(GUITestOpStatus &os, const QString &widgetName, bool expectedEnabledState, QWidget const *const parent) {
checkEnabled(os, GTWidget::findWidget(os, widgetName, parent), expectedEnabledState);
}
#undef GT_METHOD_NAME
#undef GT_CLASS_NAME
} // namespace HI
| 36.564039 | 164 | 0.658201 | r-barnes |
e2c17b66012062aa9824c0ee97aea7250fc91417 | 1,817 | cc | C++ | tools/traceline/traceline/assembler_unittest.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | tools/traceline/traceline/assembler_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | tools/traceline/traceline/assembler_unittest.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdio.h>
#include "assembler.h"
int main(int argc, char** argv) {
char buf[1024];
CodeBuffer cb(buf);
// Branching tests first so the offsets are not always adjusting in the
// output diassembler when we add new tests.
cb.spin();
cb.call(EAX);
cb.call(Operand(EAX));
cb.call(Operand(EDX, 15));
cb.fs(); cb.mov(EAX, Operand(3));
cb.fs(); cb.mov(EDX, Operand(0x04));
cb.lea(EAX, Operand(EAX));
cb.lea(EAX, Operand(0x12345678));
cb.lea(EAX, Operand(EBX, 0x12345678));
cb.lea(EAX, Operand(EBX, ECX, SCALE_TIMES_2, 0x12345678));
cb.lea(EAX, Operand(ECX, SCALE_TIMES_2, 0x12345678));
cb.lea(EAX, Operand(EAX, SCALE_TIMES_2, 0));
cb.lea(EAX, Operand(EBX, SCALE_TIMES_2, 0));
cb.lea(EBP, Operand(EBP, SCALE_TIMES_2, 1));
cb.lodsb();
cb.lodsd();
cb.mov(EAX, ECX);
cb.mov(ESI, ESP);
cb.mov(EAX, Operand(ESP, 0x20));
cb.mov(EAX, Operand(EBP, 8));
cb.mov_imm(ESP, 1);
cb.mov_imm(EAX, 0x12345678);
cb.pop(EBX);
cb.pop(Operand(EBX));
cb.pop(Operand(EBX, 0));
cb.pop(Operand(EBX, 12));
cb.push(EBX);
cb.push(Operand(EBX));
cb.push(Operand(EBX, 0));
cb.push(Operand(EDI, -4));
cb.push(Operand(EDI, -8));
cb.push_imm(0x12);
cb.push_imm(0x1234);
cb.push(Operand(EBX, 12));
cb.push(Operand(ESP, 0x1234));
cb.ret();
cb.ret(0);
cb.ret(12);
cb.stosb();
cb.stosd();
cb.sysenter();
cb.which_cpu();
cb.which_thread();
cb.xchg(EAX, EAX);
cb.xchg(EBX, EAX);
cb.xchg(EAX, EBX);
cb.xchg(ECX, ESP);
cb.xchg(ECX, Operand(ESP));
cb.xchg(ECX, Operand(ESP, 5));
cb.xchg(ECX, Operand(EDX, 4));
fwrite(buf, 1, cb.size(), stdout);
return 0;
}
| 21.630952 | 73 | 0.636214 | zealoussnow |
e2c2581c230d99a85295d58416f984ae1d900bc8 | 1,348 | cpp | C++ | tests/transform/Dct.cpp | ulikoehler/aquila | d5e3bde3c8d07678a95f225b657a7bb23d0c4730 | [
"MIT"
] | 361 | 2015-01-06T20:12:35.000Z | 2022-03-29T01:58:49.000Z | tests/transform/Dct.cpp | ulikoehler/aquila | d5e3bde3c8d07678a95f225b657a7bb23d0c4730 | [
"MIT"
] | 30 | 2015-01-13T12:17:13.000Z | 2021-06-03T14:12:10.000Z | tests/transform/Dct.cpp | ulikoehler/aquila | d5e3bde3c8d07678a95f225b657a7bb23d0c4730 | [
"MIT"
] | 112 | 2015-01-14T12:01:00.000Z | 2022-03-29T06:42:00.000Z | #include "aquila/global.h"
#include "aquila/transform/Dct.h"
#include "UnitTest++/UnitTest++.h"
#include <cstddef>
#include <vector>
SUITE(Dct)
{
TEST(AlternatingOnes)
{
const std::size_t SIZE = 4;
const double testArray[SIZE] = {1.0, -1.0, 1.0, -1.0};
std::vector<double> vec(testArray, testArray + SIZE);
Aquila::Dct dct;
auto output = dct.dct(vec, SIZE);
double expected[SIZE] = {0.0, 0.76536686, 0.0, 1.84775907};
CHECK_ARRAY_CLOSE(expected, output, SIZE, 0.0001);
}
TEST(ConstantInput)
{
const std::size_t SIZE = 4;
const double testArray[SIZE] = {1.0, 1.0, 1.0, 1.0};
std::vector<double> vec(testArray, testArray + SIZE);
Aquila::Dct dct;
auto output = dct.dct(vec, SIZE);
double expected[SIZE] = {2.0, 0.0, 0.0, 0.0};
CHECK_ARRAY_CLOSE(expected, output, SIZE, 0.0001);
}
TEST(UseCachedCosines)
{
const std::size_t SIZE = 4;
const double testArray[SIZE] = {1.0, 1.0, 1.0, 1.0};
std::vector<double> vec(testArray, testArray + SIZE);
Aquila::Dct dct;
auto output = dct.dct(vec, SIZE);
auto output2 = dct.dct(vec, SIZE);
double expected[SIZE] = {2.0, 0.0, 0.0, 0.0};
CHECK_ARRAY_CLOSE(expected, output2, SIZE, 0.0001);
}
}
| 26.96 | 67 | 0.575668 | ulikoehler |
e2c5da21e0c4be2c2cdde04b62a614c9b5c97567 | 605 | cpp | C++ | Game/Source/Boss.cpp | BooStarGamer/Makers-Vs-Players-v2 | db7f32e978f682e55f9d2542ac5879f7137e40ff | [
"MIT"
] | null | null | null | Game/Source/Boss.cpp | BooStarGamer/Makers-Vs-Players-v2 | db7f32e978f682e55f9d2542ac5879f7137e40ff | [
"MIT"
] | null | null | null | Game/Source/Boss.cpp | BooStarGamer/Makers-Vs-Players-v2 | db7f32e978f682e55f9d2542ac5879f7137e40ff | [
"MIT"
] | null | null | null | #include "Boss.h"
#include "App.h"
#include "Textures.h"
Boss::Boss() : Entity(EntityType::BOSS)
{
}
Boss::Boss(BossClass bClass) : Entity(EntityType::BOSS)
{
bossClass = bClass;
// LIFE -> ((x / 1.5) + 20)
// STRG -> ((x / 2) + 8)
// DEFS -> ((x / 4) + 2) nose
// EXPR -> expActLvl + expNextLvl / 2
}
Boss::~Boss()
{
}
void Boss::SetUp(SDL_Rect combatCollider, int xexp, int xhealth, int xstrength, int xdefense)
{
colliderCombat = combatCollider;
exp = xexp;
health = xhealth;
maxHealth = xhealth;
strength = xstrength;
defense = xdefense;
}
void Boss::Refill()
{
health = maxHealth;
}
| 16.805556 | 93 | 0.634711 | BooStarGamer |
e2c6d4dcf2ef538a5ee27808e7c3a82e63a97086 | 20,493 | cxx | C++ | resip/stack/Contents.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | resip/stack/Contents.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | resip/stack/Contents.cxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | #include <vector>
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#include "resip/stack/Contents.hxx"
#include "rutil/ParseBuffer.hxx"
#include "rutil/Logger.hxx"
#include "resip/stack/OctetContents.hxx"
#include "rutil/MD5Stream.hxx"
#include "rutil/WinLeakCheck.hxx"
using namespace resip;
using namespace std;
#define RESIPROCATE_SUBSYSTEM Subsystem::CONTENTS
H_ContentID resip::h_ContentID;
H_ContentDescription resip::h_ContentDescription;
Contents::Contents(const HeaderFieldValue& headerFieldValue,
const Mime& contentType)
: LazyParser(headerFieldValue),
mType(contentType)
{
init();
}
Contents::Contents(const Mime& contentType)
: mType(contentType)
{
init();
}
Contents::Contents(const Contents& rhs)
: LazyParser(rhs)
{
init(rhs);
}
Contents::Contents(const Contents& rhs,HeaderFieldValue::CopyPaddingEnum e)
: LazyParser(rhs,e)
{
init(rhs);
}
Contents::Contents(const HeaderFieldValue& headerFieldValue,
HeaderFieldValue::CopyPaddingEnum e,
const Mime& contentsType)
: LazyParser(headerFieldValue,e),
mType(contentsType)
{
init();
}
Contents::~Contents()
{
freeMem();
}
static const Data errorContextData("Contents");
const Data&
Contents::errorContext() const
{
return errorContextData;
}
Contents&
Contents::operator=(const Contents& rhs)
{
if (this != &rhs)
{
freeMem();
LazyParser::operator=(rhs);
init(rhs);
}
return *this;
}
void
Contents::init(const Contents& orig)
{
mBufferList.clear();
mType = orig.mType;
if (orig.mDisposition)
{
mDisposition = new H_ContentDisposition::Type(*orig.mDisposition);
}
else
{
mDisposition = 0;
}
if (orig.mTransferEncoding)
{
mTransferEncoding = new H_ContentTransferEncoding::Type(*orig.mTransferEncoding);
}
else
{
mTransferEncoding = 0;
}
if (orig.mLanguages)
{
mLanguages = new H_ContentLanguages::Type(*orig.mLanguages);
}
else
{
mLanguages = 0;
}
if (orig.mId)
{
mId = new Token(*orig.mId);
}
else
{
mId = 0;
}
if (orig.mDescription)
{
mDescription = new StringCategory(*orig.mDescription);
}
else
{
mDescription = 0;
}
if(orig.mLength)
{
mLength = new StringCategory(*orig.mLength);
}
else
{
mLength = 0;
}
mVersion = orig.mVersion;
mMinorVersion = orig.mMinorVersion;
}
Contents*
Contents::createContents(const Mime& contentType,
const Data& contents)
{
// !ass! why are we asserting that the Data doesn't own the buffer?
// .dlb. because this method is to be called only within a multipart
// !ass! HFV is an overlay -- then setting c->mIsMine to true ?? dlb Q
// .dlb. we are telling the content that it owns its HFV, not the data that it
// .dlb. owns its memory
// .bwc. So, we are _violating_ _encapsulation_, to make an assertion that the
// Data is an intermediate instead of owning the buffer itself? What do we
// care how this buffer is owned? All we require is that the buffer doesn't
// get dealloced/modified while we're still around. The assertion might mean
// that the Data will not do either of these things, but it affords no
// protection from the actual owner doing so. We are no more protected with
// the assertion, so I am removing it.
// assert(!contents.mMine);
HeaderFieldValue hfv(contents.data(), (unsigned int)contents.size());
// !bwc! This padding stuff is now the responsibility of the Contents class.
// if(contentType.subType()=="sipfrag"||contentType.subType()=="external-body")
// {
// // .bwc. The parser for sipfrag requires padding at the end of the hfv.
// HeaderFieldValue* temp = hfv;
// hfv = new HeaderFieldValue(*temp,HeaderFieldValue::CopyPadding);
// delete temp;
// }
Contents* c;
if (ContentsFactoryBase::getFactoryMap().find(contentType) != ContentsFactoryBase::getFactoryMap().end())
{
c = ContentsFactoryBase::getFactoryMap()[contentType]->create(hfv, contentType);
}
else
{
c = new OctetContents(hfv, contentType);
}
return c;
}
bool
Contents::exists(const HeaderBase& headerType) const
{
checkParsed();
switch (headerType.getTypeNum())
{
case Headers::ContentType :
{
return true;
}
case Headers::ContentDisposition :
{
return mDisposition != 0;
}
case Headers::ContentTransferEncoding :
{
return mTransferEncoding != 0;
}
case Headers::ContentLanguage :
{
return mLanguages != 0;
}
default : return false;
}
}
bool
Contents::exists(const MIME_Header& type) const
{
if (&type == &h_ContentID)
{
return mId != 0;
}
if (&type == &h_ContentDescription)
{
return mDescription != 0;
}
assert(false);
return false;
}
void
Contents::remove(const HeaderBase& headerType)
{
switch (headerType.getTypeNum())
{
case Headers::ContentDisposition :
{
delete mDisposition;
mDisposition = 0;
break;
}
case Headers::ContentLanguage :
{
delete mLanguages;
mLanguages = 0;
break;
}
case Headers::ContentTransferEncoding :
{
delete mTransferEncoding;
mTransferEncoding = 0;
break;
}
default :
;
}
}
void
Contents::remove(const MIME_Header& type)
{
if (&type == &h_ContentID)
{
delete mId;
mId = 0;
return;
}
if (&type == &h_ContentDescription)
{
delete mDescription;
mDescription = 0;
return;
}
assert(false);
}
const H_ContentType::Type&
Contents::header(const H_ContentType& headerType) const
{
return mType;
}
H_ContentType::Type&
Contents::header(const H_ContentType& headerType)
{
return mType;
}
const H_ContentDisposition::Type&
Contents::header(const H_ContentDisposition& headerType) const
{
checkParsed();
if (mDisposition == 0)
{
ErrLog(<< "You called "
"Contents::header(const H_ContentDisposition& headerType) _const_ "
"without first calling exists(), and the header does not exist. Our"
" behavior in this scenario is to implicitly create the header(using const_cast!); "
"this is probably not what you want, but it is either this or "
"assert/throw an exception. Since this has been the behavior for "
"so long, we are not throwing here, _yet_. You need to fix your "
"code, before we _do_ start throwing. This is why const-correctness"
" should never be made a TODO item </rant>");
Contents* ncthis = const_cast<Contents*>(this);
ncthis->mDisposition = new H_ContentDisposition::Type;
}
return *mDisposition;
}
H_ContentDisposition::Type&
Contents::header(const H_ContentDisposition& headerType)
{
checkParsed();
if (mDisposition == 0)
{
mDisposition = new H_ContentDisposition::Type;
}
return *mDisposition;
}
const H_ContentTransferEncoding::Type&
Contents::header(const H_ContentTransferEncoding& headerType) const
{
checkParsed();
if (mTransferEncoding == 0)
{
ErrLog(<< "You called "
"Contents::header(const H_ContentTransferEncoding& headerType) _const_ "
"without first calling exists(), and the header does not exist. Our"
" behavior in this scenario is to implicitly create the header(using const_cast!); "
"this is probably not what you want, but it is either this or "
"assert/throw an exception. Since this has been the behavior for "
"so long, we are not throwing here, _yet_. You need to fix your "
"code, before we _do_ start throwing. This is why const-correctness"
" should never be made a TODO item </rant>");
Contents* ncthis = const_cast<Contents*>(this);
ncthis->mTransferEncoding = new H_ContentTransferEncoding::Type;
}
return *mTransferEncoding;
}
H_ContentTransferEncoding::Type&
Contents::header(const H_ContentTransferEncoding& headerType)
{
checkParsed();
if (mTransferEncoding == 0)
{
mTransferEncoding = new H_ContentTransferEncoding::Type;
}
return *mTransferEncoding;
}
const H_ContentLanguages::Type&
Contents::header(const H_ContentLanguages& headerType) const
{
checkParsed();
if (mLanguages == 0)
{
ErrLog(<< "You called "
"Contents::header(const H_ContentLanguages& headerType) _const_ "
"without first calling exists(), and the header does not exist. Our"
" behavior in this scenario is to implicitly create the header(using const_cast!); "
"this is probably not what you want, but it is either this or "
"assert/throw an exception. Since this has been the behavior for "
"so long, we are not throwing here, _yet_. You need to fix your "
"code, before we _do_ start throwing. This is why const-correctness"
" should never be made a TODO item </rant>");
Contents* ncthis = const_cast<Contents*>(this);
ncthis->mLanguages = new H_ContentLanguages::Type;
}
return *mLanguages;
}
H_ContentLanguages::Type&
Contents::header(const H_ContentLanguages& headerType)
{
checkParsed();
if (mLanguages == 0)
{
mLanguages = new H_ContentLanguages::Type;
}
return *mLanguages;
}
const H_ContentDescription::Type&
Contents::header(const H_ContentDescription& headerType) const
{
checkParsed();
if (mDescription == 0)
{
ErrLog(<< "You called "
"Contents::header(const H_ContentDescription& headerType) _const_ "
"without first calling exists(), and the header does not exist. Our"
" behavior in this scenario is to implicitly create the header(using const_cast!); "
"this is probably not what you want, but it is either this or "
"assert/throw an exception. Since this has been the behavior for "
"so long, we are not throwing here, _yet_. You need to fix your "
"code, before we _do_ start throwing. This is why const-correctness"
" should never be made a TODO item </rant>");
Contents* ncthis = const_cast<Contents*>(this);
ncthis->mDescription = new H_ContentDescription::Type;
}
return *mDescription;
}
H_ContentDescription::Type&
Contents::header(const H_ContentDescription& headerType)
{
checkParsed();
if (mDescription == 0)
{
mDescription = new H_ContentDescription::Type;
}
return *mDescription;
}
const H_ContentID::Type&
Contents::header(const H_ContentID& headerType) const
{
checkParsed();
if (mId == 0)
{
ErrLog(<< "You called "
"Contents::header(const H_ContentID& headerType) _const_ "
"without first calling exists(), and the header does not exist. Our"
" behavior in this scenario is to implicitly create the header(using const_cast!); "
"this is probably not what you want, but it is either this or "
"assert/throw an exception. Since this has been the behavior for "
"so long, we are not throwing here, _yet_. You need to fix your "
"code, before we _do_ start throwing. This is why const-correctness"
" should never be made a TODO item </rant>");
Contents* ncthis = const_cast<Contents*>(this);
ncthis->mId = new H_ContentID::Type;
}
return *mId;
}
H_ContentID::Type&
Contents::header(const H_ContentID& headerType)
{
checkParsed();
if (mId == 0)
{
mId = new H_ContentID::Type;
}
return *mId;
}
// !dlb! headers except Content-Disposition may contain (comments)
void
Contents::preParseHeaders(ParseBuffer& pb)
{
const char* start = pb.position();
Data all( start, pb.end()-start);
Data headerName;
try
{
while (!pb.eof())
{
const char* anchor = pb.skipWhitespace();
pb.skipToOneOf(Symbols::COLON, ParseBuffer::Whitespace);
pb.data(headerName, anchor);
pb.skipWhitespace();
pb.skipChar(Symbols::COLON[0]);
anchor = pb.skipWhitespace();
pb.skipToTermCRLF();
Headers::Type type = Headers::getType(headerName.data(), (int)headerName.size());
ParseBuffer subPb(anchor, pb.position() - anchor);
switch (type)
{
case Headers::ContentType :
{
// already set
break;
}
case Headers::ContentDisposition :
{
mDisposition = new H_ContentDisposition::Type;
mDisposition->parse(subPb);
break;
}
case Headers::ContentTransferEncoding :
{
mTransferEncoding = new H_ContentTransferEncoding::Type;
mTransferEncoding->parse(subPb);
break;
}
// !dlb! not sure this ever happens?
case Headers::ContentLanguage :
{
if (mLanguages == 0)
{
mLanguages = new H_ContentLanguages::Type;
}
subPb.skipWhitespace();
while (!subPb.eof() && *subPb.position() != Symbols::COMMA[0])
{
H_ContentLanguages::Type::value_type tmp;
header(h_ContentLanguages).push_back(tmp);
header(h_ContentLanguages).back().parse(subPb);
subPb.skipLWS();
}
break; // .kw. added -- this is needed, right?
}
default :
{
if (isEqualNoCase(headerName, "Content-Transfer-Encoding"))
{
mTransferEncoding = new StringCategory();
mTransferEncoding->parse(subPb);
}
else if (isEqualNoCase(headerName, "Content-Description"))
{
mDescription = new StringCategory();
mDescription->parse(subPb);
}
else if (isEqualNoCase(headerName, "Content-Id"))
{
mId = new Token();
mId->parse(subPb);
}
// Some people put this in ...
else if (isEqualNoCase(headerName, "Content-Length"))
{
mLength = new StringCategory();
mLength->parse(subPb);
}
else if (isEqualNoCase(headerName, "MIME-Version"))
{
subPb.skipWhitespace();
if (!subPb.eof() && *subPb.position() == Symbols::LPAREN[0])
{
subPb.skipToEndQuote(Symbols::RPAREN[0]);
subPb.skipChar(Symbols::RPAREN[0]);
}
mVersion = subPb.integer();
if (!subPb.eof() && *subPb.position() == Symbols::LPAREN[0])
{
subPb.skipToEndQuote(Symbols::RPAREN[0]);
subPb.skipChar(Symbols::RPAREN[0]);
}
subPb.skipChar(Symbols::PERIOD[0]);
if (!subPb.eof() && *subPb.position() == Symbols::LPAREN[0])
{
subPb.skipToEndQuote(Symbols::RPAREN[0]);
subPb.skipChar(Symbols::RPAREN[0]);
}
mMinorVersion = subPb.integer();
}
else
{
// add to application headers someday
std::cerr << "Unknown MIME Content- header: " << headerName << std::endl;
ErrLog(<< "Unknown MIME Content- header: " << headerName);
assert(false);
}
}
}
}
}
catch (ParseException & e )
{
ErrLog( << "Some problem parsing contents: " << e );
throw e;
}
}
EncodeStream&
Contents::encodeHeaders(EncodeStream& str) const
{
if (mVersion != 1 || mMinorVersion != 0)
{
str << "MIME-Version" << Symbols::COLON[0] << Symbols::SPACE[0]
<< mVersion << Symbols::PERIOD[0] << mMinorVersion
<< Symbols::CRLF;
}
str << "Content-Type" << Symbols::COLON[0] << Symbols::SPACE[0]
<< mType
<< Symbols::CRLF;
if (exists(h_ContentDisposition))
{
str << "Content-Disposition" << Symbols::COLON[0] << Symbols::SPACE[0];
header(h_ContentDisposition).encode(str);
str << Symbols::CRLF;
}
if (exists(h_ContentLanguages))
{
str << "Content-Languages" << Symbols::COLON[0] << Symbols::SPACE[0];
size_t count = 0;
size_t size = header(h_ContentLanguages).size();
for (H_ContentLanguages::Type::const_iterator
i = header(h_ContentLanguages).begin();
i != header(h_ContentLanguages).end(); ++i)
{
i->encode(str);
if (++count < size)
str << Symbols::COMMA << Symbols::SPACE;
}
str << Symbols::CRLF;
}
if (mTransferEncoding)
{
str << "Content-Transfer-Encoding" << Symbols::COLON[0] << Symbols::SPACE[0]
<< *mTransferEncoding
<< Symbols::CRLF;
}
if (mId)
{
str << "Content-Id" << Symbols::COLON[0] << Symbols::SPACE[0]
<< *mId
<< Symbols::CRLF;
}
if (mDescription)
{
str << "Content-Description" << Symbols::COLON[0] << Symbols::SPACE[0]
<< *mDescription
<< Symbols::CRLF;
}
if (mLength)
{
str << "Content-Length" << Symbols::COLON[0] << Symbols::SPACE[0]
<< *mLength
<< Symbols::CRLF;
}
str << Symbols::CRLF;
return str;
}
Data
Contents::getBodyData() const
{
checkParsed();
return Data::from(*this);
}
void
Contents::addBuffer(char* buf)
{
mBufferList.push_back(buf);
}
bool
resip::operator==(const Contents& lhs, const Contents& rhs)
{
MD5Stream lhsStream;
lhsStream << lhs;
MD5Stream rhsStream;
rhsStream << rhs;
return lhsStream.getHex() == rhsStream.getHex();
}
bool
resip::operator!=(const Contents& lhs, const Contents& rhs)
{
return !operator==(lhs,rhs);
}
/* ====================================================================
* The Vovida Software License, Version 1.0
*
* Copyright (c) 2000-2005
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The names "VOCAL", "Vovida Open Communication Application Library",
* and "Vovida Open Communication Application Library (VOCAL)" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact vocal@vovida.org.
*
* 4. Products derived from this software may not be called "VOCAL", nor
* may "VOCAL" appear in their name, without prior written
* permission of Vovida Networks, Inc.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA
* NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
* IN EXCESS OF $1,000, NOR FOR ANY 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.
*
* ====================================================================
*
* This software consists of voluntary contributions made by Vovida
* Networks, Inc. and many individuals on behalf of Vovida Networks,
* Inc. For more information on Vovida Networks, Inc., please see
* <http://www.vovida.org/>.
*
*/
| 28.0342 | 108 | 0.611819 | dulton |
e2c7250919917ab7e48d5f7a5ccb8bdb691ee30b | 11,209 | cpp | C++ | droneTrajectoryPlanner/src/sources/potencialFieldMap.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneTrajectoryPlanner/src/sources/potencialFieldMap.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | droneTrajectoryPlanner/src/sources/potencialFieldMap.cpp | MorS25/cvg_quadrotor_swarm | da75d02049163cf65fd7305bc46a16359a851c7c | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////
// potencialFieldMap.cpp
//
// Created on: Jul 3, 2013
// Author: joselusl
//
// Last modification on: Oct 26, 2013
// Author: joselusl
//
//////////////////////////////////////////////////////
#include "potencialFieldMap.h"
using namespace std;
////////////////// ObstacleInPotencialMap ////////////////////////
ObstacleInPotencialMap::ObstacleInPotencialMap()
{
init();
return;
}
ObstacleInPotencialMap::~ObstacleInPotencialMap()
{
clear();
return;
}
int ObstacleInPotencialMap::init()
{
obstacleAltitudeDef=OBSTACLE_ALTITUDE_DEF;
obstaclePrecissionDef=OBSTACLE_PRECISSION_DEF;
return 1;
}
int ObstacleInPotencialMap::clear()
{
return 1;
}
int ObstacleInPotencialMap::define(double obstacleAltitudeDefIn, double obstaclePrecissionDefIn)
{
obstacleAltitudeDef=obstacleAltitudeDefIn;
obstaclePrecissionDef=obstaclePrecissionDefIn;
return 1;
}
int ObstacleInPotencialMap::calculateAltitudePotMap(double &valueAltitudeOut, double valueImplicitEquation)
{
//double value=0.0;
//value=implicitEquation(pointIn);
if(valueImplicitEquation<0.0)
{
valueAltitudeOut=obstacleAltitudeDef/2.0;
return 1;
}
valueAltitudeOut=obstacleAltitudeDef/(1+exp(obstaclePrecissionDef*valueImplicitEquation));
return 1;
}
////////////////// EllipseObstacleInPotencialMap2d ////////////////////////
/*
double EllipseObstacleInPotencialMap2d::calculateAltitudePotMap(std::vector<double> pointIn)
{
double valueImplicitEquation=TheEllipseObstacle2d->implicitEquation(pointIn);
return ObstacleInPotencialMap::calculateAltitudePotMap(valueImplicitEquation);
}
*/
////////////////// PotencialFieldMap ////////////////////////
PotencialFieldMap::PotencialFieldMap()
{
init();
return;
}
PotencialFieldMap::~PotencialFieldMap()
{
clear();
return;
}
int PotencialFieldMap::init()
{
pointInitAltitude=0.0;
pointFinAltitude=0.0;
return 1;
}
int PotencialFieldMap::clear()
{
return 1;
}
int PotencialFieldMap::setDimension(unsigned int dimensionIn)
{
dimension=dimensionIn;
//cout<<"dim="<<dimension<<endl;
pointInit.resize(dimension);
pointFin.resize(dimension);
return 1;
}
int PotencialFieldMap::setRobotDimensions(std::vector<double> robotDimensionsIn)
{
robotDimensions=robotDimensionsIn;
return 1;
}
int PotencialFieldMap::setRealMap(WorldMap* RealMapIn)
{
RealMap=RealMapIn;
//cout<<"Real map dime="<<RealMap->dimension.at(0)<<";"<<RealMap->dimension[1]<<endl;
return 1;
}
int PotencialFieldMap::setPointsInitFin(std::vector<double> pointInitIn, std::vector<double> pointFinIn, double pointInitAltitudeIn, double pointFinAltitudeIn)
{
pointInit=pointInitIn;
pointFin=pointFinIn;
if(pointInit.size()!=dimension && pointFin.size()!=dimension)
return 0;
if(pointFinAltitudeIn==0.0)
pointFinAltitude=0.0;
else
pointFinAltitude=pointFinAltitudeIn;
if(pointInitAltitudeIn==-1.0)
{
pointInitAltitude=0.0;
for(unsigned int i=0;i<pointInit.size();i++)
{
pointInitAltitude+=pow(pointInit[i]-pointFin[i],2);
}
pointInitAltitude=sqrt(pointInitAltitude);
}
else
pointInitAltitude=pointInitAltitudeIn;
if(pointInitAltitude<pointFinAltitude)
return 0;
//cout<<"pointIn="<<pointInit[0]<<"; "<<pointInit[1]<<endl;
//cout<<"pointFin="<<pointFin[0]<<"; "<<pointFin[1]<<endl;
//cout<<"altitudes in and fin="<<pointInitAltitude<<"; "<<pointFinAltitude<<endl;
if(!calculatePotMapCurve())
return 0;
return 1;
}
int PotencialFieldMap::setPointInit(std::vector<double> pointInitIn, double pointInitAltitudeIn)
{
// cout<<"b0"<<endl;
pointInit=pointInitIn;
//cout<<"b1"<<endl;
if(pointInitAltitudeIn==-1.0)
{
//cout<<"b2"<<endl;
pointInitAltitude=0.0;
for(unsigned int i=0;i<pointInit.size();i++)
{
pointInitAltitude+=pow(pointInit[i]-pointFin[i],2);
}
//cout<<"b3"<<endl;
pointInitAltitude=sqrt(pointInitAltitude);
}
else
pointInitAltitude=pointInitAltitudeIn;
//cout<<"b"<<endl;
if(!calculatePotMapCurve())
return 0;
//cout<<"bb"<<endl;
return 1;
}
int PotencialFieldMap::setPointFin(std::vector<double> pointFinIn, double pointFinAltitudeIn)
{
//cout<<"b"<<endl;
pointFin=pointFinIn;
if(pointFinAltitudeIn==0.0)
pointFinAltitude=0.0;
else
pointFinAltitude=pointFinAltitudeIn;
//cout<<"bn-1"<<endl;
if(!calculatePotMapCurve())
return 0;
//cout<<"bn"<<endl;
return 1;
}
int PotencialFieldMap::updateObstacleMap()
{
ObstaclesList.resize(RealMap->getNumberObstacles());
#ifdef VERBOSE_POTENCIAL_FIELD_MAP
cout<<"[PFM] (updateObstacleMap) number of obstacles in potencial field map="<<RealMap->getNumberObstacles()<<endl;
#endif
return 1;
}
int PotencialFieldMap::calculateAltitudePotMapCurve(double &valueAltitudeOut, std::vector<double> pointIn)
{
return 0;
}
int PotencialFieldMap::calculateAltitudePotMapObstacleI(double &valueAltitudeOut, std::vector<double> pointIn, unsigned int numObstacleI)
{
double value=0.0;
//cout<<"calculateAltitudePotMapObstacleI"<<endl;
//getHandleObstacle(numObstacleI)
//value=RealMap->obstaclesList[numObstacleI]->implicitEquation(pointIn,robotDimensions);
if(!RealMap->implicitEquationObstacleI(value,numObstacleI,pointIn,robotDimensions))
return 0;
//cout<<"Inside pot field map:"<<value<<endl;
//value=obstacleAltitudeDef/(1+exp(obstaclePrecissionDef*value));
return ObstaclesList[numObstacleI].calculateAltitudePotMap(valueAltitudeOut,value);
}
int PotencialFieldMap::calculatePotMapCurve()
{
return 0;
}
int PotencialFieldMap::calculateDistPotMap(double &distanceOut, std::vector<double> pointIn, std::vector<double> pointFin, bool useObstacles, bool useCurve)
{
distanceOut=0.0;
//end
return 0;
}
////////////////// PotencialFieldMap2d ////////////////////////
PotencialFieldMap2d::PotencialFieldMap2d()
{
init();
return;
}
PotencialFieldMap2d::~PotencialFieldMap2d()
{
clear();
return;
}
int PotencialFieldMap2d::init()
{
dimension=2;
return 1;
}
int PotencialFieldMap2d::clear()
{
return 1;
}
int PotencialFieldMap2d::calculatePotMapCurve()
{
potFieldMapCurve.resize(dimension);
potFieldMapCurve[0]= ( (pow(pointInit[0]-pointFin[0],2)+pow(pointInit[1]-pointFin[1],2)) / (pointInitAltitude-pointFinAltitude) );
potFieldMapCurve[1]= ( (pow(pointInit[0]-pointFin[0],2)+pow(pointInit[1]-pointFin[1],2)) / (pointInitAltitude-pointFinAltitude) );
return 1;
}
int PotencialFieldMap2d::setRealMap(WorldMap2d* RealMapIn)
{
RealMap=RealMapIn;
unsigned int dimensionIn;
if(!RealMap->getDimension(dimensionIn))
return 0;
//cout<<"[inside potFieldMap2d] dimension real map="<<dimensionIn<<endl;
if(!setDimension(dimensionIn))
return 0;
return 1;
}
int PotencialFieldMap2d::calculateAltitudePotMapCurve(double &valueAltitudeOut, std::vector<double> pointIn)
{
//cout<<"PointFin="<<pointFin[0]<<"; "<<pointFin[1]<<endl;
valueAltitudeOut=pointFinAltitude+pow((pointIn[0]-pointFin[0]),2)/potFieldMapCurve[0]+pow((pointIn[1]-pointFin[1]),2)/potFieldMapCurve[1];
//cout<<"altitude curve="<<valueAltitudeOut<<endl;
return 1;
}
int PotencialFieldMap2d::calculateDistPotMap(double &distanceOut, std::vector<double> pointInitIn, std::vector<double> pointFinIn, bool useObstacles, bool useCurve)
{
//cout<<"aqui\n";
//cout<<"calculateDistPotMap"<<endl;
//Change of variable
double angleAlpha=atan2(pointFinIn[1]-pointInitIn[1],pointFinIn[0]-pointInitIn[0]);
double smin=0.0;
double smax=sqrt( pow(pointFinIn[1]-pointInitIn[1],2)+pow(pointFinIn[0]-pointInitIn[0],2) );
//Iteration vars
double stepSize=STEP_SIZE_IN_INTEGRATION_S;
int numSteps=floor((smax-smin)/stepSize);
//cout<<"smax="<<smax<<endl;
//cout<<"numSteps="<<numSteps<<endl;
//Point to change the variables
vector<double> pointSwap(dimension);
//Altitudes for integration
double altitudeInit;
double altitudeFin;
//Init algorithm
distanceOut=0.0;
double s=0.0;
//Point of change the variables
pointSwap[0]=pointInitIn[0]+s*cos(angleAlpha);
pointSwap[1]=pointInitIn[1]+s*sin(angleAlpha);
//Init loop
altitudeInit=0.0;
//cout<<"aqui"<<endl;
//Potencial of curve
if(useCurve)
{
double aux=0.0;
if(!calculateAltitudePotMapCurve(aux,pointSwap))
return 0;
altitudeInit+=aux;
}
//cout<<"aqui"<<endl;
//cout<<altitudeInit<<endl;
//Potencial of obstacles
if(useObstacles)
{
double aux=0.0;
for(unsigned int numObstacleI=0;numObstacleI<ObstaclesList.size();numObstacleI++)
{
if(!calculateAltitudePotMapObstacleI(aux,pointSwap,numObstacleI))
return 0;
altitudeInit+=aux;
}
}
//cout<<"aqui"<<endl;
//cout<<altitudeInit<<endl;
for(int numStepI=0;numStepI<numSteps;numStepI++)
{
//Take step
s+=stepSize;
//Old variables
pointSwap[0]=pointInitIn[0]+s*cos(angleAlpha);
pointSwap[1]=pointInitIn[1]+s*sin(angleAlpha);
//ALtitude fin
altitudeFin=0.0;
//Potencial of curve
if(useCurve)
{
double aux=0.0;
if(!calculateAltitudePotMapCurve(aux,pointSwap))
return 0;
altitudeFin+=aux;
}
//Potencial of obstacles
if(useObstacles)
{
double aux=0.0;
for(unsigned int numObstacleI=0;numObstacleI<ObstaclesList.size();numObstacleI++)
{
if(!calculateAltitudePotMapObstacleI(aux,pointSwap,numObstacleI))
return 0;
altitudeFin+=aux;
}
}
//Longitud arc
distanceOut+=sqrt( pow(altitudeFin-altitudeInit,2) + pow(stepSize,2) );
//Update for next step
altitudeInit=altitudeFin;
}
//Last step
double lastDs=(smax-smin)-stepSize*numSteps;
s+=lastDs;
//Old variables
pointSwap[0]=pointInitIn[0]+s*cos(angleAlpha);
pointSwap[1]=pointInitIn[1]+s*sin(angleAlpha);
//ALtitude fin
altitudeFin=0.0;
//Potencial of curve
if(useCurve)
{
double aux=0.0;
if(!calculateAltitudePotMapCurve(aux,pointSwap))
return 0;
altitudeFin+=aux;
}
//Potencial of obstacles
if(useObstacles)
{
double aux=0.0;
for(unsigned int numObstacleI=0;numObstacleI<ObstaclesList.size();numObstacleI++)
{
if(!calculateAltitudePotMapObstacleI(aux,pointSwap,numObstacleI))
return 0;
altitudeFin+=aux;
}
}
//Longitud arc
distanceOut+=sqrt( pow(altitudeFin-altitudeInit,2) + pow(lastDs,2) );
//end
return 1;
}
| 21.514395 | 164 | 0.646356 | MorS25 |
e2d33d0bd8b5d9b6fde3a5f8833ffda6bd1ff5a2 | 8,973 | cc | C++ | gazebo/rendering/selection_buffer/SelectionBuffer.cc | siconos/gazebo-siconos | 612f6a78184cb95d5e7a6898c42003c4109ae3c6 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-14T19:36:51.000Z | 2020-04-01T06:47:59.000Z | gazebo/rendering/selection_buffer/SelectionBuffer.cc | siconos/gazebo-siconos | 612f6a78184cb95d5e7a6898c42003c4109ae3c6 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | gazebo/rendering/selection_buffer/SelectionBuffer.cc | siconos/gazebo-siconos | 612f6a78184cb95d5e7a6898c42003c4109ae3c6 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2016 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.
*
*/
#include <memory>
#include "gazebo/common/Console.hh"
#include "gazebo/rendering/ogre_gazebo.h"
#include "gazebo/rendering/RenderTypes.hh"
#include "gazebo/rendering/selection_buffer/SelectionRenderListener.hh"
#include "gazebo/rendering/selection_buffer/MaterialSwitcher.hh"
#include "gazebo/rendering/selection_buffer/SelectionBuffer.hh"
using namespace gazebo;
using namespace rendering;
namespace gazebo
{
namespace rendering
{
struct SelectionBufferPrivate
{
/// \brief This is the material listener - Note: it is controlled by a
/// separate RenderTargetListener, not applied globally to all
/// targets. The class associates a color to an ogre entity
std::unique_ptr<MaterialSwitcher> materialSwitchListener;
/// \brief A render target listener that sets up the material switcher
/// to run on every update of this render target.
std::unique_ptr<SelectionRenderListener> selectionTargetListener;
/// \brief Ogre scene manager
Ogre::SceneManager *sceneMgr;
/// \brief Pointer to the camera that will be used to render to texture
Ogre::Camera *camera;
/// \brief Ogre render target
Ogre::RenderTarget *renderTarget;
/// \brief Ogre texture
Ogre::TexturePtr texture;
/// \brief Ogre render texture
Ogre::RenderTexture *renderTexture;
/// \brief Render texture data buffer
uint8_t *buffer;
/// \brief Ogre pixel box that contains description of the data buffer
Ogre::PixelBox *pixelBox;
/// \brief A 2D overlay used for debugging the selection buffer. It
/// is hidden by default.
Ogre::Overlay *selectionDebugOverlay;
};
}
}
/////////////////////////////////////////////////
SelectionBuffer::SelectionBuffer(const std::string &_cameraName,
Ogre::SceneManager *_mgr, Ogre::RenderTarget *_renderTarget)
: dataPtr(new SelectionBufferPrivate)
{
this->dataPtr->sceneMgr = _mgr;
this->dataPtr->renderTarget = _renderTarget;
this->dataPtr->renderTexture = 0;
this->dataPtr->buffer = 0;
this->dataPtr->pixelBox = 0;
this->dataPtr->camera = this->dataPtr->sceneMgr->getCamera(_cameraName);
this->dataPtr->materialSwitchListener.reset(new MaterialSwitcher());
this->dataPtr->selectionTargetListener.reset(new SelectionRenderListener(
this->dataPtr->materialSwitchListener.get()));
this->CreateRTTBuffer();
this->CreateRTTOverlays();
}
/////////////////////////////////////////////////
SelectionBuffer::~SelectionBuffer()
{
this->DeleteRTTBuffer();
}
/////////////////////////////////////////////////
void SelectionBuffer::Update()
{
if (!this->dataPtr->renderTexture)
return;
this->UpdateBufferSize();
this->dataPtr->materialSwitchListener->Reset();
// FIXME: added try-catch block to prevent crash in deferred rendering mode.
// RTT does not like VPL.material as it references a texture in the compositor
// pipeline. A possible workaround is to add the deferred rendering
// compositors to the renderTexture
try
{
this->dataPtr->renderTexture->update();
}
catch(...)
{
}
this->dataPtr->renderTexture->copyContentsToMemory(*this->dataPtr->pixelBox,
Ogre::RenderTarget::FB_FRONT);
}
/////////////////////////////////////////////////
void SelectionBuffer::DeleteRTTBuffer()
{
if (!this->dataPtr->texture.isNull() && this->dataPtr->texture->isLoaded())
this->dataPtr->texture->unload();
if (this->dataPtr->buffer)
delete [] this->dataPtr->buffer;
if (this->dataPtr->pixelBox)
delete this->dataPtr->pixelBox;
}
/////////////////////////////////////////////////
void SelectionBuffer::CreateRTTBuffer()
{
unsigned int width = this->dataPtr->renderTarget->getWidth();
unsigned int height = this->dataPtr->renderTarget->getHeight();
try
{
this->dataPtr->texture = Ogre::TextureManager::getSingleton().createManual(
"SelectionPassTex",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, width, height, 0, Ogre::PF_R8G8B8,
Ogre::TU_RENDERTARGET);
}
catch(...)
{
this->dataPtr->renderTexture = NULL;
gzerr << "Unable to create selection buffer.\n";
return;
}
this->dataPtr->renderTexture =
this->dataPtr->texture->getBuffer()->getRenderTarget();
this->dataPtr->renderTexture->setAutoUpdated(false);
this->dataPtr->renderTexture->setPriority(0);
this->dataPtr->renderTexture->addViewport(this->dataPtr->camera);
this->dataPtr->renderTexture->getViewport(0)->setOverlaysEnabled(false);
this->dataPtr->renderTexture->getViewport(0)->setClearEveryFrame(true);
this->dataPtr->renderTexture->addListener(
this->dataPtr->selectionTargetListener.get());
this->dataPtr->renderTexture->getViewport(0)->setMaterialScheme("aa");
this->dataPtr->renderTexture->getViewport(0)->setVisibilityMask(
GZ_VISIBILITY_SELECTABLE);
Ogre::HardwarePixelBufferSharedPtr pixelBuffer =
this->dataPtr->texture->getBuffer();
size_t bufferSize = pixelBuffer->getSizeInBytes();
this->dataPtr->buffer = new uint8_t[bufferSize];
this->dataPtr->pixelBox = new Ogre::PixelBox(pixelBuffer->getWidth(),
pixelBuffer->getHeight(), pixelBuffer->getDepth(),
pixelBuffer->getFormat(), this->dataPtr->buffer);
}
/////////////////////////////////////////////////
void SelectionBuffer::UpdateBufferSize()
{
if (!this->dataPtr->renderTexture)
return;
unsigned int width = this->dataPtr->renderTarget->getWidth();
unsigned int height = this->dataPtr->renderTarget->getHeight();
if (width != this->dataPtr->renderTexture->getWidth() ||
height != this->dataPtr->renderTexture->getHeight())
{
this->DeleteRTTBuffer();
this->CreateRTTBuffer();
}
}
/////////////////////////////////////////////////
Ogre::Entity *SelectionBuffer::OnSelectionClick(int _x, int _y)
{
if (!this->dataPtr->renderTexture)
return NULL;
if (_x < 0 || _y < 0
|| _x >= static_cast<int>(this->dataPtr->renderTarget->getWidth())
|| _y >= static_cast<int>(this->dataPtr->renderTarget->getHeight()))
return 0;
this->Update();
size_t posInStream = (this->dataPtr->pixelBox->getWidth() * _y) * 4;
posInStream += _x * 4;
common::Color::BGRA color(0);
memcpy(static_cast<void *>(&color), this->dataPtr->buffer + posInStream, 4);
common::Color cv;
cv.SetFromARGB(color);
cv.a = 1.0;
const std::string &entName =
this->dataPtr->materialSwitchListener->GetEntityName(cv);
if (entName.empty())
return 0;
else
return this->dataPtr->sceneMgr->getEntity(entName);
}
/////////////////////////////////////////////////
void SelectionBuffer::CreateRTTOverlays()
{
Ogre::OverlayManager *mgr = Ogre::OverlayManager::getSingletonPtr();
if (mgr && mgr->getByName("SelectionDebugOverlay"))
return;
Ogre::MaterialPtr baseWhite =
Ogre::MaterialManager::getSingleton().getDefaultSettings();
Ogre::MaterialPtr selectionBufferTexture =
baseWhite->clone("SelectionDebugMaterial");
Ogre::TextureUnitState *textureUnit =
selectionBufferTexture->getTechnique(0)->getPass(0)->
createTextureUnitState();
textureUnit->setTextureName("SelectionPassTex");
this->dataPtr->selectionDebugOverlay = mgr->create("SelectionDebugOverlay");
Ogre::OverlayContainer *panel =
static_cast<Ogre::OverlayContainer *>(
mgr->createOverlayElement("Panel", "SelectionDebugPanel"));
if (panel)
{
panel->setMetricsMode(Ogre::GMM_PIXELS);
panel->setPosition(10, 10);
panel->setDimensions(400, 280);
panel->setMaterialName("SelectionDebugMaterial");
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR <= 9
this->dataPtr->selectionDebugOverlay->add2D(panel);
this->dataPtr->selectionDebugOverlay->hide();
#endif
}
else
{
gzlog << "Unable to create selection buffer overlay. "
"This will not effect Gazebo unless you're trying to debug "
"the selection buffer.\n";
}
}
/////////////////////////////////////////////////
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR <= 9
void SelectionBuffer::ShowOverlay(bool _show)
{
if (_show)
this->dataPtr->selectionDebugOverlay->show();
else
this->dataPtr->selectionDebugOverlay->hide();
}
#else
void SelectionBuffer::ShowOverlay(bool /*_show*/)
{
gzerr << "Selection debug overlay disabled for Ogre > 1.9\n";
}
#endif
| 32.046429 | 80 | 0.674134 | siconos |
e2d957adf0fc88c1af7466201525729df6da168a | 731 | cpp | C++ | Cpp_Programs/lougu/oj/P1008.cpp | xiazeyu/OI_Resource | 1de0ab9a84ee22ae4edb612ddeddc712c3c38e56 | [
"Apache-2.0"
] | 2 | 2018-10-01T09:03:35.000Z | 2019-05-24T08:53:06.000Z | Cpp_Programs/lougu/oj/P1008.cpp | xiazeyu/OI_Resource | 1de0ab9a84ee22ae4edb612ddeddc712c3c38e56 | [
"Apache-2.0"
] | null | null | null | Cpp_Programs/lougu/oj/P1008.cpp | xiazeyu/OI_Resource | 1de0ab9a84ee22ae4edb612ddeddc712c3c38e56 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <iostream>
using namespace std;
bool check(int a, int b, int c){
if((a > 999) || (b > 999) || (c > 999)) return false;
int i;
int t[10] = {0};
t[a % 10] = 1;
t[(a % 100) / 10] = 1;
t[a / 100] = 1;
t[b % 10] = 1;
t[(b % 100) / 10] = 1;
t[b / 100] = 1;
t[c % 10] = 1;
t[(c % 100) / 10] = 1;
t[c / 100] = 1;
for(i = 1; i <= 9; i++){
if(t[i] == 0) return false;
}
return true;
}
int main(){
int a, b, c;
for(a = 100; a <= 999; a++){
b = a * 2;
c = a * 3;
if(check(a, b, c)) printf("%d %d %d\n", a, b, c);
}
return 0;
} | 17 | 58 | 0.347469 | xiazeyu |
e2db74577ced00a689d0405635de3263496311e0 | 3,775 | cpp | C++ | algorithms/cpp/Problems 201-300/_210_CourseScheduleII.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 201-300/_210_CourseScheduleII.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | algorithms/cpp/Problems 201-300/_210_CourseScheduleII.cpp | shivamacs/LeetCode | f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a | [
"MIT"
] | null | null | null | /* Source - https://leetcode.com/problems/course-schedule-ii/
Author - Shivam Arora
*/
#include <bits/stdc++.h>
using namespace std;
bool dfs(vector<vector<int>>& graph, unordered_set<int>& visited, vector<bool>& recStack, stack<int>& st, int src) {
visited.insert(src);
recStack[src] = true;
for(int i = 0; i < graph[src].size(); i++) {
int nbr = graph[src][i];
if(recStack[nbr])
return true;
if(visited.find(nbr) == visited.end()) {
bool answer = dfs(graph, visited, recStack, st, nbr);
if(answer)
return true;
}
}
st.push(src);
recStack[src] = false;
return false;
}
// approach 1
vector<int> findOrderUsingDFS(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
for(int i = 0; i < prerequisites.size(); i++)
graph[prerequisites[i][1]].push_back(prerequisites[i][0]);
unordered_set<int> visited;
stack<int> st;
vector<bool> recStack(numCourses);
for(int i = 0; i < graph.size(); i++) {
if(visited.find(i) == visited.end()) {
bool answer = dfs(graph, visited, recStack, st, i);
if(answer == true)
return {};
}
}
if(visited.size() != numCourses)
return {};
vector<int> result;
while(!st.empty()) {
result.push_back(st.top());
st.pop();
}
return result;
}
// approach 2
vector<int> findOrderUsingKahnsAlgo(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
for(int i = 0; i < prerequisites.size(); i++)
graph[prerequisites[i][1]].push_back(prerequisites[i][0]);
vector<int> indegree(numCourses);
for(int i = 0; i < graph.size(); i++) {
for(int j = 0; j < graph[i].size(); j++)
indegree[graph[i][j]]++;
}
queue<int> q;
int count = 0;
for(int i = 0; i < indegree.size(); i++) {
if(indegree[i] == 0) {
q.push(i);
count++;
}
}
vector<int> result;
while(!q.empty()) {
int front = q.front();
q.pop();
result.push_back(front);
for(int i = 0; i < graph[front].size(); i++) {
int nbr = graph[front][i];
if(--indegree[nbr] == 0) {
q.push(nbr);
count++;
}
}
}
if(count != numCourses)
return {};
return result;
}
int main()
{
int numCourses;
cout<<"Enter number of courses: ";
cin>>numCourses;
int p;
cout<<"Enter number of prerequisite pairs: ";
cin>>p;
vector<vector<int>> prerequisites(p);
int f, s;
cout<<"Enter prerequisite pairs: "<<endl;
for(int i = 0; i < p; i++) {
cin>>f>>s;
prerequisites[i].push_back(f);
prerequisites[i].push_back(s);
}
vector<int> result = findOrderUsingDFS(numCourses, prerequisites);
cout<<"Correct ordering of courses to finish all courses (using DFS - recursive): [";
if(result.size() > 0) {
for(int i = 0; i < result.size() - 1; i++)
cout<<result[i]<<", ";
cout<<result[result.size() - 1];
}
cout<<"]"<<endl;
result = findOrderUsingKahnsAlgo(numCourses, prerequisites);
cout<<"Correct ordering of courses to finish all courses (using Kahn's Algo - iterative): [";
if(result.size() > 0) {
for(int i = 0; i < result.size() - 1; i++)
cout<<result[i]<<", ";
cout<<result[result.size() - 1];
}
cout<<"]"<<endl;
} | 24.673203 | 116 | 0.509934 | shivamacs |
e2dd208984ed94df4115b83769db56f19d659153 | 4,586 | cpp | C++ | services/sms_receive_indexer.cpp | openharmony-gitee-mirror/telephony_sms_mms | 4f5eee78093bea8ca3198d54b5999ef889b52b19 | [
"Apache-2.0"
] | null | null | null | services/sms_receive_indexer.cpp | openharmony-gitee-mirror/telephony_sms_mms | 4f5eee78093bea8ca3198d54b5999ef889b52b19 | [
"Apache-2.0"
] | null | null | null | services/sms_receive_indexer.cpp | openharmony-gitee-mirror/telephony_sms_mms | 4f5eee78093bea8ca3198d54b5999ef889b52b19 | [
"Apache-2.0"
] | 1 | 2021-09-13T12:07:15.000Z | 2021-09-13T12:07:15.000Z | /*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* 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 "sms_receive_indexer.h"
namespace OHOS {
namespace Telephony {
SmsReceiveIndexer::SmsReceiveIndexer()
{
timestamp_ = 0;
destPort_ = 0;
msgSeqId_ = 0;
msgRefId_ = -1;
msgCount_ = 1;
isCdma_ = false;
isCdmaWapPdu_ = false;
}
SmsReceiveIndexer::SmsReceiveIndexer(const std::vector<uint8_t> &pdu, long timestamp, int16_t destPort,
bool isCdma, const std::string &address, const std::string &visibleAddress, int16_t msgRefId,
uint16_t msgSeqId, uint16_t msgCount, bool isCdmaWapPdu, const std::string &messageBody)
: pdu_(pdu), timestamp_(timestamp), destPort_(destPort), isCdma_(isCdma), isCdmaWapPdu_(isCdmaWapPdu),
visibleMessageBody_(messageBody), originatingAddress_(address), msgRefId_(msgRefId), msgSeqId_(msgSeqId),
msgCount_(msgCount), visibleAddress_(visibleAddress)
{}
SmsReceiveIndexer::SmsReceiveIndexer(const std::vector<uint8_t> &pdu, long timestamp, int16_t destPort,
bool isCdma, bool isCdmaWapPdu, const std::string &address, const std::string &visibleAddress,
const std::string &messageBody)
: pdu_(pdu), timestamp_(timestamp), destPort_(destPort), isCdma_(isCdma), isCdmaWapPdu_(isCdmaWapPdu),
visibleMessageBody_(messageBody), originatingAddress_(address), visibleAddress_(visibleAddress)
{
if (isCdma_ && isCdmaWapPdu_) {
msgSeqId_ = 0;
} else {
msgSeqId_ = 1;
}
msgRefId_ = -1;
msgCount_ = 1;
}
std::string SmsReceiveIndexer::GetVisibleAddress() const
{
return visibleAddress_;
}
void SmsReceiveIndexer::SetVisibleAddress(const std::string &visibleAddress)
{
visibleAddress_ = visibleAddress;
}
std::string SmsReceiveIndexer::GetEraseRefId() const
{
return eraseRefId_;
}
void SmsReceiveIndexer::SetEraseRefId(const std::string &eraseRefId)
{
eraseRefId_ = eraseRefId;
}
uint16_t SmsReceiveIndexer::GetMsgCount() const
{
return msgCount_;
}
void SmsReceiveIndexer::SetMsgCount(uint16_t msgCount)
{
msgCount_ = msgCount;
}
uint16_t SmsReceiveIndexer::GetMsgSeqId() const
{
return msgSeqId_;
}
void SmsReceiveIndexer::SetMsgSeqId(uint16_t msgSeqId)
{
msgSeqId_ = msgSeqId;
}
uint16_t SmsReceiveIndexer::GetMsgRefId() const
{
return msgRefId_;
}
void SmsReceiveIndexer::SetMsgRefId(uint16_t msgRefId)
{
msgRefId_ = msgRefId;
}
std::string SmsReceiveIndexer::GetOriginatingAddress() const
{
return originatingAddress_;
}
void SmsReceiveIndexer::SetOriginatingAddress(const std::string &address)
{
originatingAddress_ = address;
}
std::string SmsReceiveIndexer::GetVisibleMessageBody() const
{
return visibleMessageBody_;
}
void SmsReceiveIndexer::SetVisibleMessageBody(const std::string &messageBody)
{
visibleMessageBody_ = messageBody;
}
bool SmsReceiveIndexer::GetIsCdmaWapPdu() const
{
return isCdmaWapPdu_;
}
void SmsReceiveIndexer::SetIsCdmaWapPdu(bool isCdmaWapPdu)
{
isCdmaWapPdu_ = isCdmaWapPdu;
}
bool SmsReceiveIndexer::GetIsCdma() const
{
return isCdma_;
}
void SmsReceiveIndexer::SetIsCdma(bool isCdma)
{
isCdma_ = isCdma;
}
int16_t SmsReceiveIndexer::GetDestPort() const
{
return destPort_;
}
void SmsReceiveIndexer::SetDestPort(int16_t destPort)
{
destPort_ = destPort;
}
long SmsReceiveIndexer::GetTimestamp() const
{
return timestamp_;
}
void SmsReceiveIndexer::SetTimestamp(long timestamp)
{
timestamp_ = timestamp;
}
const std::vector<uint8_t> &SmsReceiveIndexer::GetPdu() const
{
return pdu_;
}
void SmsReceiveIndexer::SetPdu(const std::vector<uint8_t> &pdu)
{
pdu_ = pdu;
}
void SmsReceiveIndexer::SetPdu(const std::vector<uint8_t> &&pdu)
{
pdu_ = std::forward<const std::vector<uint8_t>>(pdu);
}
bool SmsReceiveIndexer::GetIsText() const
{
return (destPort_ == TEXT_PORT_NUM);
}
bool SmsReceiveIndexer::GetIsWapPushMsg() const
{
return (destPort_ == WAP_PUSH_PORT);
}
bool SmsReceiveIndexer::IsSingleMsg() const
{
return msgCount_ == 1;
}
} // namespace Telephony
} // namespace OHOS | 23.639175 | 111 | 0.73986 | openharmony-gitee-mirror |
e2ddc96b8f612c794049531c117810a073c8de18 | 4,671 | cpp | C++ | app/genCSV.cpp | yukatayu/tentee_image_similarity | ae787c1b530483b30fdd152dbe51e8b50a1d9c5b | [
"MIT"
] | 9 | 2020-05-07T17:30:04.000Z | 2020-07-22T02:11:45.000Z | app/genCSV.cpp | yukatayu/tentee_image_similarity | ae787c1b530483b30fdd152dbe51e8b50a1d9c5b | [
"MIT"
] | null | null | null | app/genCSV.cpp | yukatayu/tentee_image_similarity | ae787c1b530483b30fdd152dbe51e8b50a1d9c5b | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include <utility>
#include <string>
#include <algorithm>
#include <fstream>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/features2d.hpp>
#include <illust_image_similarity.hpp>
using namespace illust_image_similarity::feature;
std::vector<std::string> getFileNames(std::string pathStr) {
std::vector<std::string> res;
namespace fs = boost::filesystem;
const fs::path path(pathStr);
BOOST_FOREACH(const fs::path& p, std::make_pair(fs::directory_iterator(path), fs::directory_iterator())) {
if (!fs::is_directory(p))
res.push_back(p.filename().string());
}
return res;
}
int main(){
cv::Mat mask = cv::imread("tentee_patch/mask/mask.png", 0);
// vvv For testing vvv //
// b1, b3, y1 -> double edge
// b2, p1, p2, p3 -> single edge
// p3 -> no edge
/*std::map<std::string, cv::Mat> images = {
{ "blue1", cv::imread("../tentee_patch/dream/0001.png") },
{ "blue2", cv::imread("../tentee_patch/dream/0087.png") },
{ "blue3", cv::imread("../tentee_patch/dream/0006.png") },
{ "blue4", cv::imread("../tentee_patch/dream/0255.png") },
{ "yell1", cv::imread("../tentee_patch/dream/0005.png") },
{ "pink1", cv::imread("../tentee_patch/dream/0002.png") },
{ "pink2", cv::imread("../tentee_patch/dream/0132.png") },
{ "pink3", cv::imread("../tentee_patch/dream/0138.png") },
{ "pink4", cv::imread("../tentee_patch/dream/0004.png") }
};*/
// memo: 1と12は近い, 2は遠い
// memo: 255と2はどちらも縞
// ^^^ For testing ^^^ //
std::map<std::string, cv::Mat> images;
auto fileList = getFileNames("../tentee_patch/dream/");
{
int cnt = 0;
for(auto&& fName : fileList){
cv::Mat img = cv::imread("../tentee_patch/dream/" + fName);
if(++cnt % 10 == 0)
std::cout << "loading: " << cnt << " images..." << std::endl;
if(img.data)
images[fName] = img;
}
}
std::cout << "start" << std::endl;
std::map<std::string, cv::MatND> hists;
for(auto&& [name, img] : images)
hists[name] = img | hueHistgramAlgorithm(mask);
std::map<std::string, cv::MatND> placements;
for(auto&& [name, img] : images)
placements[name] = img | placementAlgorithm;
std::map<std::string, std::vector<double>> directions;
for(auto&& [name, img] : images)
directions[name] = img | directionPreprocess | directionVec(mask);
int cnt = 0;
auto cdot = [](const std::vector<double>& lhs, const std::vector<double>& rhs) -> double {
int dim = std::min(lhs.size(), rhs.size());
double res = 0;
for(int i=0; i<dim; ++i)
res += lhs[i] * rhs[i];
return res;
};
// from, type [hue, edge, dir], to, index (0-), score (0-1)
const int maxIndex = 5;
std::ofstream data("recommend_data.csv");
for(auto&& [name, img] : images){
if(++cnt % 10 == 0)
std::cout << cnt << " / " << images.size() << " ... " << std::endl;
std::vector<std::pair<double, std::string>> list_hue;
std::vector<std::pair<double, std::string>> list_edge;
std::vector<std::pair<double, std::string>> list_dir;
auto&& pls = placements.at(name);
auto&& hist = hists.at(name);
auto&& dir = directions.at(name);
// target
for(auto&& [tName, tImg] : images){
if(name == tName) continue; // 自身とは比較しない (edge,dir,hueのスコアは常に1)
auto&& tPls = placements.at(tName);
auto&& tHist = hists.at(tName);
auto&& tDir = directions.at(tName);
list_hue.emplace_back(cv::compareHist(hist, tHist, cv::HISTCMP_CORREL), tName);
cv::Mat tmp;
// Normalized Cross-Correlation
//list_edge.emplace_back(cv::norm(img, tImg, cv::NORM_L1), tName);
cv::matchTemplate(pls, tPls, tmp, CV_TM_CCOEFF_NORMED);
list_edge.emplace_back(tmp.at<float>(0,0), tName);
// dot product
list_dir.emplace_back(cdot(dir, tDir), tName);
}
std::sort(list_edge.begin(), list_edge.end());
std::reverse(list_edge.begin(), list_edge.end());
std::sort(list_dir.begin(), list_dir.end());
std::reverse(list_dir.begin(), list_dir.end());
std::sort(list_hue.begin(), list_hue.end());
std::reverse(list_hue.begin(), list_hue.end());
for(int i=0; i<maxIndex && i < list_hue.size(); ++i){
auto [tHist, tName] = list_hue[i];
data << name << "," << "hue" << "," << tName << "," << i << "," << tHist << "\n";
}
for(int i=0; i<maxIndex && i < list_edge.size(); ++i){
auto [tHist, tName] = list_edge[i];
data << name << "," << "edge" << "," << tName << "," << i << "," << tHist << "\n";
}
for(int i=0; i<maxIndex && i < list_dir.size(); ++i){
auto [tHist, tName] = list_dir[i];
data << name << "," << "dir" << "," << tName << "," << i << "," << tHist << "\n";
}
data << std::flush;
}
std::cout << "end" << std::endl;
}
| 32.213793 | 107 | 0.61079 | yukatayu |
e2de3d31e386a752773e0ca890b7840b971b84b9 | 43 | cpp | C++ | morse/DotNet/cellImageBuilders/Processes.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | 1 | 2019-12-24T15:52:45.000Z | 2019-12-24T15:52:45.000Z | morse/DotNet/cellImageBuilders/Processes.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | morse/DotNet/cellImageBuilders/Processes.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "Processes.h"
| 14.333333 | 22 | 0.72093 | jonnyzzz |
e2e0191f848a36905cd9e826c939e59b0ed66ac0 | 335 | cc | C++ | nofx/nofx_ofTexture/nofx_ofGetUsingCustomTextureWrap.cc | sepehr-laal/nofx | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | [
"MIT"
] | null | null | null | nofx/nofx_ofTexture/nofx_ofGetUsingCustomTextureWrap.cc | sepehr-laal/nofx | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | [
"MIT"
] | null | null | null | nofx/nofx_ofTexture/nofx_ofGetUsingCustomTextureWrap.cc | sepehr-laal/nofx | 7abc9da3d4fc0f5b72c6b3d591a08cf44d00277e | [
"MIT"
] | null | null | null | #include "nofx_ofGetUsingCustomTextureWrap.h"
#include "ofTexture.h"
namespace nofx
{
namespace ClassWrappers
{
NAN_METHOD(nofx_ofGetUsingCustomTextureWrap)
{
NanReturnValue(ofGetUsingCustomTextureWrap());
} // !nofx_ofGetUsingCustomTextureWrap
} // !namespace ClassWrappers
} // !namespace nofx | 25.769231 | 52 | 0.722388 | sepehr-laal |
e2e31c6b3373fb7ce53c18dcc608b4c927e31ddf | 21,317 | cpp | C++ | kwset.cpp | h4ck3rm1k3/php-fss-FastStringSearch | 2093d69f1b951add5354e5b722842edd9854d8cb | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | kwset.cpp | h4ck3rm1k3/php-fss-FastStringSearch | 2093d69f1b951add5354e5b722842edd9854d8cb | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | kwset.cpp | h4ck3rm1k3/php-fss-FastStringSearch | 2093d69f1b951add5354e5b722842edd9854d8cb | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | /* kwset.c - search for any of a set of keywords.
Copyright 1989, 1998, 2000, 2005 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
02110-1301, USA. */
/* Written August 1989 by Mike Haertel.
The author may be reached (Email) at the address mike@ai.mit.edu,
or (US mail) as Mike Haertel c/o Free Software Foundation. */
/* The algorithm implemented by these routines bears a startling resemblence
to one discovered by Beate Commentz-Walter, although it is not identical.
See "A String Matching Algorithm Fast on the Average," Technical Report,
IBM-Germany, Scientific Center Heidelberg, Tiergartenstrasse 15, D-6900
Heidelberg, Germany. See also Aho, A.V., and M. Corasick, "Efficient
String Matching: An Aid to Bibliographic Search," CACM June 1975,
Vol. 18, No. 6, which describes the failure function used below. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <sys/types.h>
#include <limits.h>
//#include "hphp/runtime/base/base-includes.h"
#include "hphp/runtime/ext/extension.h"
#include "kwset.h"
#include "obstack.h"
void *kws_emalloc_wrapper(size_t size);
void kws_efree_wrapper(void *ptr);
#define NCHAR (UCHAR_MAX + 1)
#define obstack_chunk_alloc kws_emalloc_wrapper
#define obstack_chunk_free kws_efree_wrapper
#define U(c) ((unsigned char) (c))
/* Balanced tree of edges and labels leaving a given trie node. */
struct tree
{
struct tree *llink; /* Left link; MUST be first field. */
struct tree *rlink; /* Right link (to larger labels). */
struct trie *trie; /* Trie node pointed to by this edge. */
unsigned char label; /* Label on this edge. */
char balance; /* Difference in depths of subtrees. */
};
/* Node of a trie representing a set of reversed keywords. */
struct trie
{
unsigned int accepting; /* Word index of accepted word, or zero. */
struct tree *links; /* Tree of edges leaving this node. */
struct trie *parent; /* Parent of this node. */
struct trie *next; /* List of all trie nodes in level order. */
struct trie *fail; /* Aho-Corasick failure function. */
int depth; /* Depth of this node from the root. */
int shift; /* Shift function for search failures. */
int maxshift; /* Max shift of self and descendents. */
};
/* Structure returned opaquely to the caller, containing everything. */
struct kwset
{
struct obstack obstack; /* Obstack for node allocation. */
int words; /* Number of words in the trie. */
struct trie *trie; /* The trie itself. */
int mind; /* Minimum depth of an accepting node. */
int maxd; /* Maximum depth of any node. */
unsigned char delta[NCHAR]; /* Delta table for rapid search. */
struct trie *next[NCHAR]; /* Table of children of the root. */
char *target; /* Target string if there's only one. */
int mind2; /* Used in Boyer-Moore search for one string. */
char const *trans; /* Character translation table. */
};
void *kws_emalloc_wrapper(size_t size)
{
return HPHP::smart_malloc(size);
}
void kws_efree_wrapper(void *ptr)
{
HPHP::smart_free(ptr);
}
/* Allocate and initialize a keyword set object, returning an opaque
pointer to it. Return NULL if memory is not available. */
kwset_t
kwsalloc (char const *trans)
{
struct kwset *kwset;
kwset = (struct kwset *) kws_emalloc_wrapper(sizeof (struct kwset));
if (!kwset)
return NULL;
obstack_init(&kwset->obstack);
kwset->words = 0;
kwset->trie
= (struct trie *) obstack_alloc(&kwset->obstack, sizeof (struct trie));
if (!kwset->trie)
{
kwsfree((kwset_t) kwset);
return NULL;
}
kwset->trie->accepting = 0;
kwset->trie->links = NULL;
kwset->trie->parent = NULL;
kwset->trie->next = NULL;
kwset->trie->fail = NULL;
kwset->trie->depth = 0;
kwset->trie->shift = 0;
kwset->mind = INT_MAX;
kwset->maxd = -1;
kwset->target = NULL;
kwset->trans = trans;
return (kwset_t) kwset;
}
/* This upper bound is valid for CHAR_BIT >= 4 and
exact for CHAR_BIT in { 4..11, 13, 15, 17, 19 }. */
#define DEPTH_SIZE (CHAR_BIT + CHAR_BIT/2)
/* Add the given string to the contents of the keyword set. Return NULL
for success, an error message otherwise. */
const char *
kwsincr (kwset_t kws, char const *text, size_t len)
{
struct kwset *kwset;
register struct trie *trie;
register unsigned char label;
register struct tree *link;
register int depth;
struct tree *links[DEPTH_SIZE];
enum { L, R } dirs[DEPTH_SIZE];
struct tree *t, *r, *l, *rl, *lr;
kwset = (struct kwset *) kws;
trie = kwset->trie;
text += len;
/* Descend the trie (built of reversed keywords) character-by-character,
installing new nodes when necessary. */
while (len--)
{
label = kwset->trans ? kwset->trans[U(*--text)] : *--text;
/* Descend the tree of outgoing links for this trie node,
looking for the current character and keeping track
of the path followed. */
link = trie->links;
links[0] = (struct tree *) &trie->links;
dirs[0] = L;
depth = 1;
while (link && label != link->label)
{
links[depth] = link;
if (label < link->label)
dirs[depth++] = L, link = link->llink;
else
dirs[depth++] = R, link = link->rlink;
}
/* The current character doesn't have an outgoing link at
this trie node, so build a new trie node and install
a link in the current trie node's tree. */
if (!link)
{
link = (struct tree *) obstack_alloc(&kwset->obstack,
sizeof (struct tree));
if (!link)
return "memory exhausted";
link->llink = NULL;
link->rlink = NULL;
link->trie = (struct trie *) obstack_alloc(&kwset->obstack,
sizeof (struct trie));
if (!link->trie)
{
obstack_free(&kwset->obstack, link);
return "memory exhausted";
}
link->trie->accepting = 0;
link->trie->links = NULL;
link->trie->parent = trie;
link->trie->next = NULL;
link->trie->fail = NULL;
link->trie->depth = trie->depth + 1;
link->trie->shift = 0;
link->label = label;
link->balance = 0;
/* Install the new tree node in its parent. */
if (dirs[--depth] == L)
links[depth]->llink = link;
else
links[depth]->rlink = link;
/* Back up the tree fixing the balance flags. */
while (depth && !links[depth]->balance)
{
if (dirs[depth] == L)
--links[depth]->balance;
else
++links[depth]->balance;
--depth;
}
/* Rebalance the tree by pointer rotations if necessary. */
if (depth && ((dirs[depth] == L && --links[depth]->balance)
|| (dirs[depth] == R && ++links[depth]->balance)))
{
switch (links[depth]->balance)
{
case (char) -2:
switch (dirs[depth + 1])
{
case L:
r = links[depth], t = r->llink, rl = t->rlink;
t->rlink = r, r->llink = rl;
t->balance = r->balance = 0;
break;
case R:
r = links[depth], l = r->llink, t = l->rlink;
rl = t->rlink, lr = t->llink;
t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;
l->balance = t->balance != 1 ? 0 : -1;
r->balance = t->balance != (char) -1 ? 0 : 1;
t->balance = 0;
break;
default:
abort ();
}
break;
case 2:
switch (dirs[depth + 1])
{
case R:
l = links[depth], t = l->rlink, lr = t->llink;
t->llink = l, l->rlink = lr;
t->balance = l->balance = 0;
break;
case L:
l = links[depth], r = l->rlink, t = r->llink;
lr = t->llink, rl = t->rlink;
t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl;
l->balance = t->balance != 1 ? 0 : -1;
r->balance = t->balance != (char) -1 ? 0 : 1;
t->balance = 0;
break;
default:
abort ();
}
break;
default:
abort ();
}
if (dirs[depth - 1] == L)
links[depth - 1]->llink = t;
else
links[depth - 1]->rlink = t;
}
}
trie = link->trie;
}
/* Mark the node we finally reached as accepting, encoding the
index number of this word in the keyword set so far. */
if (!trie->accepting)
trie->accepting = 1 + 2 * kwset->words;
++kwset->words;
/* Keep track of the longest and shortest string of the keyword set. */
if (trie->depth < kwset->mind)
kwset->mind = trie->depth;
if (trie->depth > kwset->maxd)
kwset->maxd = trie->depth;
return NULL;
}
/* Enqueue the trie nodes referenced from the given tree in the
given queue. */
static void
enqueue (struct tree *tree, struct trie **last)
{
if (!tree)
return;
enqueue(tree->llink, last);
enqueue(tree->rlink, last);
(*last) = (*last)->next = tree->trie;
}
/* Compute the Aho-Corasick failure function for the trie nodes referenced
from the given tree, given the failure function for their parent as
well as a last resort failure node. */
static void
treefails (register struct tree const *tree, struct trie const *fail,
struct trie *recourse)
{
register struct tree *link;
if (!tree)
return;
treefails(tree->llink, fail, recourse);
treefails(tree->rlink, fail, recourse);
/* Find, in the chain of fails going back to the root, the first
node that has a descendent on the current label. */
while (fail)
{
link = fail->links;
while (link && tree->label != link->label)
if (tree->label < link->label)
link = link->llink;
else
link = link->rlink;
if (link)
{
tree->trie->fail = link->trie;
return;
}
fail = fail->fail;
}
tree->trie->fail = recourse;
}
/* Set delta entries for the links of the given tree such that
the preexisting delta value is larger than the current depth. */
static void
treedelta (register struct tree const *tree,
register unsigned int depth,
unsigned char delta[])
{
if (!tree)
return;
treedelta(tree->llink, depth, delta);
treedelta(tree->rlink, depth, delta);
if (depth < delta[tree->label])
delta[tree->label] = depth;
}
/* Return true if A has every label in B. */
static int
hasevery (register struct tree const *a, register struct tree const *b)
{
if (!b)
return 1;
if (!hasevery(a, b->llink))
return 0;
if (!hasevery(a, b->rlink))
return 0;
while (a && b->label != a->label)
if (b->label < a->label)
a = a->llink;
else
a = a->rlink;
return !!a;
}
/* Compute a vector, indexed by character code, of the trie nodes
referenced from the given tree. */
static void
treenext (struct tree const *tree, struct trie *next[])
{
if (!tree)
return;
treenext(tree->llink, next);
treenext(tree->rlink, next);
next[tree->label] = tree->trie;
}
/* Compute the shift for each trie node, as well as the delta
table and next cache for the given keyword set. */
const char *
kwsprep (kwset_t kws)
{
register struct kwset *kwset;
register int i;
register struct trie *curr;
register char const *trans;
unsigned char delta[NCHAR];
kwset = (struct kwset *) kws;
/* Initial values for the delta table; will be changed later. The
delta entry for a given character is the smallest depth of any
node at which an outgoing edge is labeled by that character. */
memset(delta, kwset->mind < UCHAR_MAX ? kwset->mind : UCHAR_MAX, NCHAR);
/* Check if we can use the simple boyer-moore algorithm, instead
of the hairy commentz-walter algorithm. */
if (kwset->words == 1 && kwset->trans == NULL)
{
char c;
/* Looking for just one string. Extract it from the trie. */
kwset->target = (char *)obstack_alloc(&kwset->obstack, kwset->mind);
if (!kwset->target)
return "memory exhausted";
for (i = kwset->mind - 1, curr = kwset->trie; i >= 0; --i)
{
kwset->target[i] = curr->links->label;
curr = curr->links->trie;
}
/* Build the Boyer Moore delta. Boy that's easy compared to CW. */
for (i = 0; i < kwset->mind; ++i)
delta[U(kwset->target[i])] = kwset->mind - (i + 1);
/* Find the minimal delta2 shift that we might make after
a backwards match has failed. */
c = kwset->target[kwset->mind - 1];
for (i = kwset->mind - 2; i >= 0; --i)
if (kwset->target[i] == c)
break;
kwset->mind2 = kwset->mind - (i + 1);
}
else
{
register struct trie *fail;
struct trie *last, *next[NCHAR];
/* Traverse the nodes of the trie in level order, simultaneously
computing the delta table, failure function, and shift function. */
for (curr = last = kwset->trie; curr; curr = curr->next)
{
/* Enqueue the immediate descendents in the level order queue. */
enqueue(curr->links, &last);
curr->shift = kwset->mind;
curr->maxshift = kwset->mind;
/* Update the delta table for the descendents of this node. */
treedelta(curr->links, curr->depth, delta);
/* Compute the failure function for the decendents of this node. */
treefails(curr->links, curr->fail, kwset->trie);
/* Update the shifts at each node in the current node's chain
of fails back to the root. */
for (fail = curr->fail; fail; fail = fail->fail)
{
/* If the current node has some outgoing edge that the fail
doesn't, then the shift at the fail should be no larger
than the difference of their depths. */
if (!hasevery(fail->links, curr->links))
if (curr->depth - fail->depth < fail->shift)
fail->shift = curr->depth - fail->depth;
/* If the current node is accepting then the shift at the
fail and its descendents should be no larger than the
difference of their depths. */
if (curr->accepting && fail->maxshift > curr->depth - fail->depth)
fail->maxshift = curr->depth - fail->depth;
}
}
/* Traverse the trie in level order again, fixing up all nodes whose
shift exceeds their inherited maxshift. */
for (curr = kwset->trie->next; curr; curr = curr->next)
{
if (curr->maxshift > curr->parent->maxshift)
curr->maxshift = curr->parent->maxshift;
if (curr->shift > curr->maxshift)
curr->shift = curr->maxshift;
}
/* Create a vector, indexed by character code, of the outgoing links
from the root node. */
for (i = 0; i < NCHAR; ++i)
next[i] = NULL;
treenext(kwset->trie->links, next);
if ((trans = kwset->trans) != NULL)
for (i = 0; i < NCHAR; ++i)
kwset->next[i] = next[U(trans[i])];
else
memcpy(kwset->next, next, NCHAR * sizeof(struct trie *));
}
/* Fix things up for any translation table. */
if ((trans = kwset->trans) != NULL)
for (i = 0; i < NCHAR; ++i)
kwset->delta[i] = delta[U(trans[i])];
else
memcpy(kwset->delta, delta, NCHAR);
return NULL;
}
/* Fast boyer-moore search. */
static size_t
bmexec (kwset_t kws, char const *text, size_t size)
{
struct kwset const *kwset;
register unsigned char const *d1;
register char const *ep, *sp, *tp;
register int d, gc, i, len, md2;
kwset = (struct kwset const *) kws;
len = kwset->mind;
if (len == 0)
return 0;
if (len > size)
return -1;
if (len == 1)
{
tp = (char *)memchr (text, kwset->target[0], size);
return tp ? tp - text : -1;
}
d1 = kwset->delta;
sp = kwset->target + len;
gc = U(sp[-2]);
md2 = kwset->mind2;
tp = text + len;
/* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
if (size > 12 * len)
/* 11 is not a bug, the initial offset happens only once. */
for (ep = text + size - 11 * len;;)
{
while (tp <= ep)
{
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d == 0)
goto found;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d == 0)
goto found;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
if (d == 0)
goto found;
d = d1[U(tp[-1])], tp += d;
d = d1[U(tp[-1])], tp += d;
}
break;
found:
if (U(tp[-2]) == gc)
{
for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
;
if (i > len)
return tp - len - text;
}
tp += md2;
}
/* Now we have only a few characters left to search. We
carefully avoid ever producing an out-of-bounds pointer. */
ep = text + size;
d = d1[U(tp[-1])];
while (d <= ep - tp)
{
d = d1[U((tp += d)[-1])];
if (d != 0)
continue;
if (U(tp[-2]) == gc)
{
for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
;
if (i > len)
return tp - len - text;
}
d = md2;
}
return -1;
}
/* Hairy multiple string search. */
static size_t
cwexec (kwset_t kws, char const *text, size_t len, struct kwsmatch *kwsmatch)
{
struct kwset const *kwset;
struct trie * const *next;
struct trie const *trie;
struct trie const *accept;
char const *beg, *lim, *mch, *lmch;
register unsigned char c;
register unsigned char const *delta;
register int d;
register char const *end, *qlim;
register struct tree const *tree;
register char const *trans;
#ifdef lint
accept = NULL;
#endif
/* Initialize register copies and look for easy ways out. */
kwset = (struct kwset *) kws;
if (len < kwset->mind)
return -1;
next = kwset->next;
delta = kwset->delta;
trans = kwset->trans;
lim = text + len;
end = text;
if ((d = kwset->mind) != 0)
mch = NULL;
else
{
mch = text, accept = kwset->trie;
goto match;
}
if (len >= 4 * kwset->mind)
qlim = lim - 4 * kwset->mind;
else
qlim = NULL;
while (lim - end >= d)
{
if (qlim && end <= qlim)
{
end += d - 1;
while ((d = delta[c = *end]) && end < qlim)
{
end += d;
end += delta[U(*end)];
end += delta[U(*end)];
}
++end;
}
else
d = delta[c = (end += d)[-1]];
if (d)
continue;
beg = end - 1;
trie = next[c];
if (trie->accepting)
{
mch = beg;
accept = trie;
}
d = trie->shift;
while (beg > text)
{
c = trans ? trans[U(*--beg)] : *--beg;
tree = trie->links;
while (tree && c != tree->label)
if (c < tree->label)
tree = tree->llink;
else
tree = tree->rlink;
if (tree)
{
trie = tree->trie;
if (trie->accepting)
{
mch = beg;
accept = trie;
}
}
else
break;
d = trie->shift;
}
if (mch)
goto match;
}
return -1;
match:
/* Given a known match, find the longest possible match anchored
at or before its starting point. This is nearly a verbatim
copy of the preceding main search loops. */
if (lim - mch > kwset->maxd)
lim = mch + kwset->maxd;
lmch = 0;
d = 1;
while (lim - end >= d)
{
if ((d = delta[c = (end += d)[-1]]) != 0)
continue;
beg = end - 1;
if (!(trie = next[c]))
{
d = 1;
continue;
}
if (trie->accepting && beg <= mch)
{
lmch = beg;
accept = trie;
}
d = trie->shift;
while (beg > text)
{
c = trans ? trans[U(*--beg)] : *--beg;
tree = trie->links;
while (tree && c != tree->label)
if (c < tree->label)
tree = tree->llink;
else
tree = tree->rlink;
if (tree)
{
trie = tree->trie;
if (trie->accepting && beg <= mch)
{
lmch = beg;
accept = trie;
}
}
else
break;
d = trie->shift;
}
if (lmch)
{
mch = lmch;
goto match;
}
if (!d)
d = 1;
}
if (kwsmatch)
{
kwsmatch->index = accept->accepting / 2;
kwsmatch->offset[0] = mch - text;
kwsmatch->size[0] = accept->depth;
}
return mch - text;
}
/* Search through the given text for a match of any member of the
given keyword set. Return a pointer to the first character of
the matching substring, or NULL if no match is found. If FOUNDLEN
is non-NULL store in the referenced location the length of the
matching substring. Similarly, if FOUNDIDX is non-NULL, store
in the referenced location the index number of the particular
keyword matched. */
size_t
kwsexec (kwset_t kws, char const *text, size_t size,
struct kwsmatch *kwsmatch)
{
struct kwset const *kwset = (struct kwset *) kws;
if (kwset->words == 1 && kwset->trans == NULL)
{
size_t ret = bmexec (kws, text, size);
if (kwsmatch != NULL && ret != (size_t) -1)
{
kwsmatch->index = 0;
kwsmatch->offset[0] = ret;
kwsmatch->size[0] = kwset->mind;
}
return ret;
}
else
return cwexec(kws, text, size, kwsmatch);
}
/* Free the components of the given keyword set. */
void
kwsfree (kwset_t kws)
{
struct kwset *kwset;
kwset = (struct kwset *) kws;
obstack_free(&kwset->obstack, NULL);
kws_efree_wrapper(kws);
}
| 27.05203 | 77 | 0.599381 | h4ck3rm1k3 |
e2e3b44726b15ea0fa6726997db88f50fdcb0b6c | 5,867 | cpp | C++ | src/sorting_network.cpp | afnaanhashmi/smt-switch | 73dd8ccf3c737e6bcf214d9f967df4a16b437eb8 | [
"BSD-3-Clause"
] | 49 | 2018-02-20T12:47:28.000Z | 2021-08-14T17:06:19.000Z | src/sorting_network.cpp | afnaanhashmi/smt-switch | 73dd8ccf3c737e6bcf214d9f967df4a16b437eb8 | [
"BSD-3-Clause"
] | 117 | 2017-06-30T18:26:02.000Z | 2021-08-17T19:50:18.000Z | src/sorting_network.cpp | afnaanhashmi/smt-switch | 73dd8ccf3c737e6bcf214d9f967df4a16b437eb8 | [
"BSD-3-Clause"
] | 21 | 2019-10-10T22:22:03.000Z | 2021-07-22T14:15:10.000Z | /********************* */
/*! \file sorting_network.cpp
** \verbatim
** Top contributors (to current version):
** Makai Mann
** This file is part of the smt-switch project.
** Copyright (c) 2020 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file LICENSE in the top-level source
** directory for licensing information.\endverbatim
**
** \brief Implements a symbolic sorting network for boolean-sorted variables.
**
**/
#include "sorting_network.h"
#include <assert.h>
#include "exceptions.h"
namespace smt {
// implementation based on SortingNetwork in the predecessor, CoSA:
// https://github.com/cristian-mattarei/CoSA/blob/141be4b23f4012c6ad5676907d7c211ae2b6614a/cosa/utils/formula_mngm.py#L198
TermVec SortingNetwork::sorting_network(const TermVec & unsorted) const
{
if (unsorted.empty())
{
return {};
}
// check that all the terms in unsorted are boolean sorted
// for sort aliasing solvers, best to compare to the object
// rather than rely on the SortKind
Sort boolsort = solver_->make_sort(BOOL);
Sort sort;
for (const auto & tt : unsorted)
{
sort = tt->get_sort();
if (tt->get_sort() != boolsort)
{
throw IncorrectUsageException("Expected all boolean sorts but got "
+ tt->to_string() + ":"
+ sort->to_string());
}
}
return sorting_network_rec(unsorted);
}
TermVec SortingNetwork::sort_two(const Term & t1, const Term & t2) const
{
return { solver_->make_term(Or, t1, t2), solver_->make_term(And, t1, t2) };
}
TermVec SortingNetwork::merge(const TermVec & sorted1,
const TermVec & sorted2) const
{
size_t len1 = sorted1.size();
size_t len2 = sorted2.size();
if (len1 == 0)
{
return sorted2;
}
else if (len2 == 0)
{
return sorted1;
}
else if (len1 == 1 && len2 == 1)
{
return sort_two(sorted1[0], sorted2[0]);
}
bool sorted1_is_even = (len1 % 2) == 0;
bool sorted2_is_even = (len2 % 2) == 0;
if (!sorted1_is_even and sorted2_is_even)
{
// normalize so we don't have to do all cases
return merge(sorted2, sorted1);
}
TermVec even_sorted1;
TermVec odd_sorted1;
for (size_t i = 0; i < len1; ++i)
{
if (i % 2 == 0)
{
odd_sorted1.push_back(sorted1[i]);
}
else
{
even_sorted1.push_back(sorted1[i]);
}
}
TermVec even_sorted2;
TermVec odd_sorted2;
for (size_t i = 0; i < len2; ++i)
{
if (i % 2 == 0)
{
odd_sorted2.push_back(sorted2[i]);
}
else
{
even_sorted2.push_back(sorted2[i]);
}
}
TermVec res_even = merge(even_sorted1, even_sorted2);
TermVec res_odd = merge(odd_sorted1, odd_sorted2);
size_t len_res_even = res_even.size();
size_t len_res_odd = res_odd.size();
TermVec res;
res.reserve(len1 + len2);
if (sorted1_is_even && sorted2_is_even)
{
assert(len_res_even == len_res_odd);
// if both inputs were even, they have same number of elements
// need to interleave and compare all inner elements
// the first odd result and last even result have already
// been compared via the base case of merge (two length 1
// lists)
Term first_res_odd = res_odd[0];
res.push_back(first_res_odd);
for (size_t i = 0; i < len_res_odd - 1; ++i)
{
const TermVec & two_sorted = sort_two(res_odd[i + 1], res_even[i]);
assert(two_sorted.size() == 2);
res.push_back(two_sorted[0]);
res.push_back(two_sorted[1]);
}
Term last_res_even = res_even.back();
res.push_back(last_res_even);
}
else if (sorted1_is_even && !sorted2_is_even)
{
assert(len_res_even + 1 == len_res_odd);
// if first element was even and second was odd,
// then there's one extra element in the merged
// odd list
// the first odd element has already been fully
// processed down to the base case of merge
Term first_res_odd = res_odd[0];
res.push_back(first_res_odd);
for (size_t i = 0; i < len_res_even; ++i)
{
const TermVec & two_sorted = sort_two(res_odd[i + 1], res_even[i]);
assert(two_sorted.size() == 2);
res.push_back(two_sorted[0]);
res.push_back(two_sorted[1]);
}
}
else if (!sorted1_is_even && !sorted2_is_even)
{
assert(len_res_even + 2 == len_res_odd);
// if both inputs were odd, then there are
// two more elements in the odd merged list
// the first and last elements have already
// been fully processed down to the base
// case of merge
// the rest need to be merged with the even
// merged list
Term first_res_odd = res_odd[0];
Term last_res_odd = res_odd.back();
res.push_back(first_res_odd);
for (size_t i = 0; i < len_res_even; ++i)
{
const TermVec & two_sorted = sort_two(res_odd[i + 1], res_even[i]);
assert(two_sorted.size() == 2);
res.push_back(two_sorted[0]);
res.push_back(two_sorted[1]);
}
res.push_back(last_res_odd);
}
else
{
// should not occur to due normalization above
assert(false);
}
assert(res.size() == len1 + len2);
return res;
}
// protected methods
TermVec SortingNetwork::sorting_network_rec(const TermVec & unsorted) const
{
size_t len = unsorted.size();
if (len == 1)
{
return unsorted;
}
else if (len == 2)
{
return sort_two(unsorted[0], unsorted[1]);
}
size_t pivot = len / 2;
auto begin = unsorted.begin();
TermVec left_vec(begin, begin + pivot);
TermVec right_vec(begin + pivot, unsorted.end());
TermVec left_res = sorting_network_rec(left_vec);
TermVec right_res = sorting_network_rec(right_vec);
return merge(left_res, right_res);
}
} // namespace smt
| 26.309417 | 122 | 0.63593 | afnaanhashmi |
e2eb0f892f50f04886c4aa27d03cc01a76b60bcd | 2,264 | cpp | C++ | zap/src/zap.cpp | colugomusic/blockhead_fx | e03f493b76f8747aea5522d214f3e8c3bb404110 | [
"MIT"
] | null | null | null | zap/src/zap.cpp | colugomusic/blockhead_fx | e03f493b76f8747aea5522d214f3e8c3bb404110 | [
"MIT"
] | null | null | null | zap/src/zap.cpp | colugomusic/blockhead_fx | e03f493b76f8747aea5522d214f3e8c3bb404110 | [
"MIT"
] | null | null | null | #include <rack++/module/smooth_param.h>
#include <rack++/module/channel.h>
#include <snd/misc.h>
#include "zap.h"
using namespace rack;
using namespace std::placeholders;
Zap::Zap()
: BasicStereoEffect("Zap")
{
param_spread_ = add_smooth_param(0.0f, "Spread");
param_spread_->set_transform([](const ml::DSPVector& v)
{
const auto x = v / 100.0f;
return x * x * ml::signBit(x);
});
param_spread_->set_size_hint(0.75);
param_spread_->set_format_hint(Rack_ParamFormatHint_Percentage);
param_spread_->set_min(-100.0f);
param_spread_->set_max(100.0f);
param_freq_ = add_smooth_param(1000.0f, "Frequency");
param_freq_->set_format_hint(Rack_ParamFormatHint_Hertz);
param_freq_->set_min(MIN_FREQ);
param_freq_->set_max(MAX_FREQ);
param_res_ = add_smooth_param(50.0f, "Resonance");
param_res_->set_transform([](const ml::DSPVector& v) { return v / 100.0f; });
param_res_->set_size_hint(0.75);
param_res_->set_format_hint(Rack_ParamFormatHint_Percentage);
param_res_->set_min(0.0f);
param_res_->set_max(100.0f);
param_mix_ = add_smooth_param(100.0f, "Mix");
param_mix_->set_transform([](const ml::DSPVector& v) { return v / 100.0f; });
param_mix_->set_size_hint(0.5);
param_mix_->set_format_hint(Rack_ParamFormatHint_Percentage);
param_mix_->set_min(0.0f);
param_mix_->set_max(100.0f);
param_spread_->begin_notify();
param_freq_->begin_notify();
param_res_->begin_notify();
param_mix_->begin_notify();
}
ml::DSPVectorArray<2> Zap::operator()(const ml::DSPVectorArray<2>& in)
{
ml::DSPVectorArray<2> out;
const auto& spread = (*param_spread_)();
const auto& base_freq = (*param_freq_)();
const auto& res = (*param_res_)();
const auto& mix = (*param_mix_)();
const auto offset = spread * 1000.0f;
const ml::DSPVector min_freq(MIN_FREQ);
const ml::DSPVector max_freq(MAX_FREQ);
const auto freq_L = ml::clamp(base_freq - offset, min_freq, max_freq);
const auto freq_R = ml::clamp(base_freq + offset, min_freq, max_freq);
const auto freq = ml::concatRows(freq_L, freq_R);
out = filter_(in, sample_rate_, freq, ml::repeatRows<2>(res));
return ml::lerp(in, out, ml::repeatRows<2>(mix));
}
void Zap::effect_clear()
{
filter_.clear();
}
| 29.025641 | 79 | 0.699647 | colugomusic |
e2edde13f8bd56ca97d153ea6c610c7940641ed8 | 5,174 | hpp | C++ | eagleye_util/fix2kml/include/fix2kml/GoogleEarthPath.hpp | lonfr/eagleye | 8c5880827cd41ce62b6f2a1e2f10e90351bab19b | [
"BSD-3-Clause"
] | 329 | 2020-03-19T00:41:00.000Z | 2022-03-31T05:52:33.000Z | eagleye_util/fix2kml/include/fix2kml/GoogleEarthPath.hpp | yxw027/eagleye | b5eab2fd162841d7be17ef320faf0bbd4f9627c4 | [
"BSD-3-Clause"
] | 22 | 2020-03-20T09:14:19.000Z | 2022-03-24T23:47:55.000Z | eagleye_util/fix2kml/include/fix2kml/GoogleEarthPath.hpp | yxw027/eagleye | b5eab2fd162841d7be17ef320faf0bbd4f9627c4 | [
"BSD-3-Clause"
] | 79 | 2020-03-19T03:08:29.000Z | 2022-03-09T00:54:03.000Z | // 1 tab = 8 spaces
/**
* ID: GoogleEarthPath.hpp
* EDITED: 23-09-2014
* AUTOR: Andres Gongora
*
* +------ Description: -----------------------------------------------------------+
* | |
* | Class to store GPS coordinates in a Google Earth compatible KML file. |
* | This can then be loaded and displayed as a route on Google Earth. |
* | |
* | |
* | EXAMPLE OF USE: |
* | 1 #include <GoogleEarthPath.hpp> //This class |
* | 2 #include <unistd.h> //Sleep |
* | 3 #include <magic_GPS_library.hpp> //Your GPS library |
* | 4 |
* | 5 int main() |
* | 6 { |
* | 7 // CREATE PATH |
* | 8 GoogleEarthPath path(myPath.kml, NameToShowInGEarth) |
* | 9 double longitude, latitude; |
* | 10 |
* | 11 for(int i=0; i < 10; i++) |
* | 12 { |
* | 13 //SOMEHOW GET GPS COORDINATES |
* | 14 yourGPSfunction(longitude,latitude); |
* | 15 |
* | 16 //ADD POINT TO PATH |
* | 17 path.addPoint(longitude,latitude); |
* | 18 |
* | 19 //WAIT FOR NEW POINTS |
* | 20 sleep(10); //sleep 10 seconds |
* | 21 } |
* | 22 return 0; |
* | 23 } |
* | |
* | This example code obtains GPS coordenates from an external function |
* | and stores them in the GoogleEarthPath instance. It samples 10 points |
* | during 100 seconds. Once the desctructor is called, the file |
* | myPath.kml is ready to be imported in G.E. |
* | |
* +-------------------------------------------------------------------------------+
*
**/
/*
* Copyright (C) 2014 Andres Gongora
* <https://yalneb.blogspot.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GOOGLEEARTHPATH_HPP_INCLUDED
#define GOOGLEEARTHPATH_HPP_INCLUDED
//----- INCLUDE ------------------------------------------------------------------------------------
#include <iostream>
#include <fstream> // File I/O
#include <iomanip> // std::setprecision
using namespace std;
//----- DEFINE -------------------------------------------------------------------------------------
//##### DECLARATION ################################################################################
class GoogleEarthPath
{
public:
GoogleEarthPath(const char*, const char*); //Requires log filename & Path name (to show inside googleearth)
~GoogleEarthPath(); // Default destructor
inline void addPoint(double, double, double);
private:
fstream fileDescriptor; // File descriptor
};
//##### DEFINITION #################################################################################
/***************************************************************************************************
* Constructor & Destructor
**************************************************************************************************/
GoogleEarthPath::GoogleEarthPath(const char* file, const char* pathName)
{
fileDescriptor.open(file, ios::out | ios::trunc); // Delete previous file if it exists
if(!fileDescriptor)
std::cerr << "GoogleEarthPath::\tCould not open file file! " << file << std::endl;
fileDescriptor << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << "\n"
<< "<kml xmlns=\"http://earth.google.com/kml/2.2\">" << "\n"
<< "<Document>" << "\n"
<< "<Placemark>" << "\n"
<< "<name>"<< pathName <<"</name>" << "\n"
<< "<Style>" << "\n"
<< "<LineStyle>" << "\n"
<< "<color>ff0000ff</color>" << "\n"
<< "<width>5.00</width>" << "\n"
<< "</LineStyle>" << "\n"
<< "</Style>" << "\n"
<< "<LineString>" << "\n"
<< "<tessellate>1</tessellate>" << "\n"
<< "<coordinates>" << "\n" ;
}
GoogleEarthPath::~GoogleEarthPath()
{
if(fileDescriptor)
{
fileDescriptor << "</coordinates>" << "\n"
<< "</LineString>" << "\n"
<< "</Placemark>" << "\n"
<< "</Document>" << "\n"
<< "</kml>" << "\n";
}
}
/***************************************************************************************************
* Path handling
**************************************************************************************************/
inline void GoogleEarthPath::addPoint(double longitude, double latitude, double altitude)
{
if(fileDescriptor)
{
fileDescriptor << setprecision(13)
<< longitude <<","
<< setprecision(13)
<< latitude << ","
<< setprecision(13)
<< altitude << "\n"
<< flush;
}
}
#endif //GOOGLEEARTHPATH
| 32.3375 | 111 | 0.473521 | lonfr |
e2f0970a4793179463cf01ac6c1cd4a28c13fce6 | 294 | cpp | C++ | codeforces/contests/round/622-div2/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | 4 | 2020-10-05T19:24:10.000Z | 2021-07-15T00:45:43.000Z | codeforces/contests/round/622-div2/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | codeforces/contests/round/622-div2/b.cpp | tysm/cpsols | 262212646203e516d1706edf962290de93762611 | [
"MIT"
] | null | null | null | #include <cpplib/stdinc.hpp>
int32_t main(){
desync();
int t;
cin >> t;
while(t--){
int n, x, y;
cin >> n >> x >> y;
int lo = min(n, 1+max((int)0, (x+y)-n));
int hi = min(n, x+y-1);
cout << lo << ' ' << hi << endl;
}
return 0;
}
| 18.375 | 48 | 0.394558 | tysm |
e2f1d06519c6d2cd8e39dd1e185e10a2c047a274 | 4,112 | cc | C++ | tests/test_puzzle_private.cc | joshleeb/Sudoku | 4e20ea1e7b1f39280b44bb1f0101c1bc4378f5cc | [
"MIT"
] | null | null | null | tests/test_puzzle_private.cc | joshleeb/Sudoku | 4e20ea1e7b1f39280b44bb1f0101c1bc4378f5cc | [
"MIT"
] | null | null | null | tests/test_puzzle_private.cc | joshleeb/Sudoku | 4e20ea1e7b1f39280b44bb1f0101c1bc4378f5cc | [
"MIT"
] | null | null | null | #include <vector>
#include <catch/catch.hpp>
#define private public
#include "../src/puzzle.h"
SCENARIO("getting available moves", "[puzzle]") {
GIVEN("a puzzle with a valid 9x9 board") {
std::vector<int> expected_moves{};
puzzle new_puzzle(std::vector<int>{
5, 3, -1, -1, 7, -1, -1, -1, -1, 6, -1, -1, 1, 9, 5, -1, -1,
-1, -1, 9, 8, -1, -1, -1, -1, 6, -1, 8, -1, -1, -1, 6, -1, -1,
-1, 3, 4, -1, -1, 8, -1, 3, -1, -1, 1, 7, -1, -1, -1, 2, -1,
-1, -1, 6, -1, 6, -1, -1, -1, -1, 2, 8, -1, -1, -1, -1, 4, 1,
9, -1, -1, 5, -1, -1, -1, -1, 8, -1, -1, 7, 9,
});
THEN("should return available moves") {
expected_moves = {1, 2, 4};
REQUIRE(new_puzzle.get_moves(2) == expected_moves);
expected_moves = {2, 6};
REQUIRE(new_puzzle.get_moves(3) == expected_moves);
expected_moves = {2, 4, 6, 8};
REQUIRE(new_puzzle.get_moves(5) == expected_moves);
expected_moves = {1, 4, 8, 9};
REQUIRE(new_puzzle.get_moves(6) == expected_moves);
expected_moves = {1, 2, 4, 9};
REQUIRE(new_puzzle.get_moves(7) == expected_moves);
expected_moves = {2, 4, 8};
REQUIRE(new_puzzle.get_moves(8) == expected_moves);
}
WHEN("having already tried options") {
new_puzzle.attempts[7] = std::vector<int>{1, 2, 4};
THEN("should return available moves without tries options") {
expected_moves = {9};
REQUIRE(new_puzzle.get_moves(7) == expected_moves);
}
}
}
GIVEN("a puzzle with a valid 4x4 board") {
std::vector<int> expected_moves{};
puzzle new_puzzle(std::vector<int>{2, 1, -1, -1, -1, 3, 2, -1, -1, -1,
-1, 4, 1, -1, -1, -1});
THEN("should return available moves") {
expected_moves = {3, 4};
REQUIRE(new_puzzle.get_moves(2) == expected_moves);
expected_moves = {3};
REQUIRE(new_puzzle.get_moves(3) == expected_moves);
expected_moves = {4};
REQUIRE(new_puzzle.get_moves(4) == expected_moves);
expected_moves = {1};
REQUIRE(new_puzzle.get_moves(7) == expected_moves);
expected_moves = {3};
REQUIRE(new_puzzle.get_moves(8) == expected_moves);
expected_moves = {2};
REQUIRE(new_puzzle.get_moves(9) == expected_moves);
expected_moves = {1, 3};
REQUIRE(new_puzzle.get_moves(10) == expected_moves);
expected_moves = {2, 4};
REQUIRE(new_puzzle.get_moves(13) == expected_moves);
expected_moves = {3};
REQUIRE(new_puzzle.get_moves(14) == expected_moves);
expected_moves = {2, 3};
REQUIRE(new_puzzle.get_moves(15) == expected_moves);
}
WHEN("having already tried options") {
new_puzzle.attempts[2] = std::vector<int>{3};
THEN("should return available moves without tries options") {
expected_moves = {4};
REQUIRE(new_puzzle.get_moves(2) == expected_moves);
}
}
}
}
SCENARIO("getting index from row and column", "[puzzle]") {
GIVEN("a puzzle") {
puzzle new_puzzle({});
new_puzzle.board_width = 16;
THEN("should get index of row and column") {
REQUIRE(new_puzzle.get_index(1, 4) == 20);
}
}
}
SCENARIO("getting row from index", "[puzzle]") {
GIVEN("a puzzle") {
puzzle new_puzzle({});
new_puzzle.board_width = 16;
THEN("should get row from index") {
REQUIRE(new_puzzle.get_row(20) == 1);
}
}
}
SCENARIO("getting column from index", "[puzzle]") {
GIVEN("a puzzle") {
puzzle new_puzzle({});
new_puzzle.board_width = 16;
THEN("should get column from index") {
REQUIRE(new_puzzle.get_column(20) == 4);
}
}
}
| 31.875969 | 79 | 0.514835 | joshleeb |
e2f2ef30eee8ee1f57f2d867a14644b8ba1910f4 | 939 | cpp | C++ | third_party/WebKit/Source/core/css/properties/CSSPropertyAPIWebkitLineClamp.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/css/properties/CSSPropertyAPIWebkitLineClamp.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/css/properties/CSSPropertyAPIWebkitLineClamp.cpp | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/css/properties/CSSPropertyAPIWebkitLineClamp.h"
#include "core/css/parser/CSSPropertyParserHelpers.h"
class CSSParserLocalContext;
namespace blink {
const CSSValue* CSSPropertyAPIWebkitLineClamp::parseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) {
if (range.Peek().GetType() != kPercentageToken &&
range.Peek().GetType() != kNumberToken)
return nullptr;
CSSPrimitiveValue* clamp_value =
CSSPropertyParserHelpers::ConsumePercent(range, kValueRangeNonNegative);
if (clamp_value)
return clamp_value;
// When specifying number of lines, don't allow 0 as a valid value.
return CSSPropertyParserHelpers::ConsumePositiveInteger(range);
}
} // namespace blink
| 33.535714 | 78 | 0.765708 | metux |
e2f4e5d6fd6503f904d0b2a84f5d395f65b78a0c | 473 | cpp | C++ | C++/Sorting/insertion_sort.cpp | mrjayantk237/Hacktober_Fest_2021 | 6dcd022a7116b81310534dcd0da8d66c185ac410 | [
"MIT"
] | 21 | 2021-10-02T14:14:33.000Z | 2022-01-12T16:27:49.000Z | C++/Sorting/insertion_sort.cpp | mrjayantk237/Hacktober_Fest_2021 | 6dcd022a7116b81310534dcd0da8d66c185ac410 | [
"MIT"
] | 11 | 2021-10-03T15:02:56.000Z | 2021-10-30T17:42:37.000Z | C++/Sorting/insertion_sort.cpp | mrjayantk237/Hacktober_Fest_2021 | 6dcd022a7116b81310534dcd0da8d66c185ac410 | [
"MIT"
] | 64 | 2021-10-02T09:20:19.000Z | 2021-10-31T20:21:01.000Z | #include <iostream>
using namespace std;
int main(void)
{
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
for (int i = 1; i < n; i++)
{
int temp = a[i];
int j = i - 1;
while (j >= 0 && a[j] > temp)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
return 0;
}
| 15.766667 | 37 | 0.312896 | mrjayantk237 |
e2f70fecbc94632b3e8635ec2962c9468f336e2a | 2,588 | cpp | C++ | Olimpiada/2013/betasah.cpp | rlodina99/Learn_cpp | 0c5bd9e6c52ca21e2eb95eb91597272ddc842c08 | [
"MIT"
] | null | null | null | Olimpiada/2013/betasah.cpp | rlodina99/Learn_cpp | 0c5bd9e6c52ca21e2eb95eb91597272ddc842c08 | [
"MIT"
] | null | null | null | Olimpiada/2013/betasah.cpp | rlodina99/Learn_cpp | 0c5bd9e6c52ca21e2eb95eb91597272ddc842c08 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <climits>
using namespace std;
int main(){
ifstream f("betasah.in");
int n,d,k;
f >> n >> d >> k;
int mat[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
mat[i][j]=0;
}
}
for(int i=0;i<n;i++){
for(int j=n-1;j>i;j--){
mat[i][j]=9;
}
}
int x,y;
for(int i=0;i<d;i++){
f >> x >> y;
mat[x-1][y-1]=3;
}
for(int i=0;i<k;i++){
f >> x >> y;
mat[x-1][y-1]=1;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << mat[i][j] << ' ';
}
cout << '\n';
}
int maxPatrateAlbePeRand=0,max;
for(int i=0;i<n;i++){
max=0;
for(int j=0;j<n;j++){
if(mat[i][j]==0)
max++;
}
if(max>maxPatrateAlbePeRand)
maxPatrateAlbePeRand=max;
}
cout << maxPatrateAlbePeRand;
//NUMARAM nr de patrate
int albe =0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if(mat[i][j]==3){
//DREAPTA
for(int g=j+1;g<n;g++){
if(mat[i][g]==0){
albe++;
mat[i][g]=11;
}
if(mat[i][g]==1 || mat[i][g]==9)
break;
}
//STANGA
for(int g=j-1;g>=0;g--){
if(mat[i][g]==0){
albe++;
mat[i][g]=11;
}
if(mat[i][g]==1 || mat[i][g]==9)
break;
}
//SUS
for(int k=i-1;k>=0;k--){
if(mat[k][j]==0){
albe++;
mat[k][j]=11;
}
if(mat[k][j]==1 || mat[k][j]==9)
break;
}
//JOS
for(int k=i+1;k<n;k++){
if(mat[k][j]==0){
albe++;
mat[k][j]=11;
}
if(mat[k][j]==1 || mat[k][j]==9)
break;
}
//STANGA SUS
int l=i-1;
int c=j-1;
while(l>=0 && c>=0){
if(mat[l][c]==0){
albe++;
mat[l][c]=11;
}
if(mat[l][c]==1 || mat[l][c]==9)
break;
l--;
c--;
}
//DREAPTA JOS
l=i+1;
c=j+1;
while(l<n && c<n){
if(mat[l][c]==0){
albe++;
mat[l][c]=11;
}
if(mat[l][c]==1 || mat[l][c]==9)
break;
l++;
c++;
}
//STANGA JOS
l=i+1;
c=j-1;
while(l<n && c>=0){
if(mat[l][c]==0){
albe++;
mat[l][c]=11;
}
if(mat[l][c]==1 || mat[l][c]==9)
break;
l++;
c--;
}
//DREAPTA SUS
l=i-1;
c=j+1;
while(l>=0 && c<n){
if(mat[l][c]==0){
albe++;
mat[l][c]=11;
}
if(mat[l][c]==1 || mat[l][c]==9)
break;
l--;
c++;
}
}
}
}
cout << '\n' << albe <<'\n';
return 0;
} | 15.046512 | 38 | 0.362056 | rlodina99 |
e2f97cc2ae6712cf8bf511039949bd6b92a0ce39 | 111 | cpp | C++ | src/MileStone.cpp | arpit/Helios | 433692e7ed8b4be2c7fe29781f18d0f9b68c5ee3 | [
"MIT"
] | 1 | 2017-10-21T04:27:19.000Z | 2017-10-21T04:27:19.000Z | src/MileStone.cpp | arpit/Helios | 433692e7ed8b4be2c7fe29781f18d0f9b68c5ee3 | [
"MIT"
] | null | null | null | src/MileStone.cpp | arpit/Helios | 433692e7ed8b4be2c7fe29781f18d0f9b68c5ee3 | [
"MIT"
] | null | null | null | //
// MileStone.cpp
// StartupsViz
//
// Created by Mathur, Arpit on 7/18/13.
//
//
#include "MileStone.h"
| 11.1 | 40 | 0.603604 | arpit |
e2fd2b9e121b52834370eaba288ccfb959c9505a | 1,405 | hpp | C++ | source/oc/ocEngine/Components/ocComponentAllocator.hpp | mackron/openchernobyl | 47c854ce37e1c361b184e29a59e4881a6faa387c | [
"BSD-3-Clause"
] | 2 | 2021-05-24T21:18:13.000Z | 2021-12-20T07:21:20.000Z | source/oc/ocEngine/Components/ocComponentAllocator.hpp | openchernobyl/openchernobyl | 47c854ce37e1c361b184e29a59e4881a6faa387c | [
"BSD-3-Clause"
] | null | null | null | source/oc/ocEngine/Components/ocComponentAllocator.hpp | openchernobyl/openchernobyl | 47c854ce37e1c361b184e29a59e4881a6faa387c | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2018 David Reid. See included LICENSE file.
typedef ocComponent* (* ocCreateComponentProc)(ocEngineContext* pEngine, ocComponentType type, ocWorldObject* pObject, void* pUserData);
typedef void (* ocDeleteComponentProc)(ocComponent* pComponent, void* pUserData);
struct ocComponentAllocatorInstance
{
ocComponentType type;
ocCreateComponentProc onCreate;
ocDeleteComponentProc onDelete;
void* pUserData;
};
struct ocComponentAllocator
{
ocEngineContext* pEngine;
ocComponentAllocatorInstance* pAllocators;
};
//
ocResult ocComponentAllocatorInit(ocEngineContext* pEngine, ocComponentAllocator* pAllocator);
//
void ocComponentAllocatorUninit(ocComponentAllocator* pAllocator);
// Registers an allocator for a specific type of component.
//
// This will return OC_INVALID_ARGS if an allocator for the specified type has already been registered.
ocResult ocComponentAllocatorRegister(ocComponentAllocator* pAllocator, ocComponentType type, ocCreateComponentProc onCreate, ocDeleteComponentProc onDelete, void* pUserData);
// Creates an instance of a component of the given type.
ocComponent* ocComponentAllocatorCreateComponent(ocComponentAllocator* pAllocator, ocComponentType type, ocWorldObject* pObject);
// Deletes an instance of a component.
void ocComponentAllocatorDeleteComponent(ocComponentAllocator* pAllocator, ocComponent* pComponent); | 37.972973 | 175 | 0.814235 | mackron |
e2fd49c1a4ad988db34e8acb9d050ed78d2ee2bb | 6,653 | cpp | C++ | book_samples/opencl_interop/my_vx_tensor_map_impl.cpp | jwinarske/openvx_tutorial | 3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c | [
"MIT"
] | 220 | 2016-03-20T00:48:58.000Z | 2022-03-31T09:46:21.000Z | book_samples/opencl_interop/my_vx_tensor_map_impl.cpp | jwinarske/openvx_tutorial | 3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c | [
"MIT"
] | 28 | 2016-06-16T19:17:41.000Z | 2021-09-16T16:19:18.000Z | book_samples/opencl_interop/my_vx_tensor_map_impl.cpp | jwinarske/openvx_tutorial | 3b57b1c043c5e28e03b6c7121bad87f4ce67ea8c | [
"MIT"
] | 84 | 2016-03-24T01:13:07.000Z | 2022-03-22T04:37:03.000Z | /*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are 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 Materials.
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/*!
* \file my_vx_tensor_map_impl.c
* \brief This is a simple reference implementation (not optimized)
* to demonstrate vxMapTensorPatch functionality, since it is
* not yet available in KhronosGroup/OpenVX-sample-impl repo
* \author Radhakrishna Giduthuri <radhakrishna.giduthuri@ieee.org>
*/
#include <VX/vx_khr_opencl_interop.h>
#include "my_vx_tensor_map_impl.h"
#include "common.h"
////
// constants
//
#define MAX_TENSOR_DIMS 6
////
// local data structure to pass data between vxMapTensorPatch & vxUnmapTensorPatch
//
struct my_vx_tensor_map_id {
vx_size number_of_dims;
vx_size view_start[MAX_TENSOR_DIMS];
vx_size view_end[MAX_TENSOR_DIMS];
vx_size stride[MAX_TENSOR_DIMS];
void * ptr;
vx_enum usage;
vx_enum mem_type;
};
////
// simple reference implementation (not optimized) for vxMapTensorPatch
// this creates a temporary buffer and uses a copy, instead of returning
// OpenVX internal buffer allocated for the tensor (so the copy overheads)
//
vx_status myVxMapTensorPatch(
vx_tensor tensor,
vx_size number_of_dims,
const vx_size* view_start,
const vx_size* view_end,
vx_map_id* map_id,
vx_size* stride,
void** ptr,
vx_enum usage,
vx_enum mem_type)
{
////
// calculate output stride values
//
vx_enum data_type;
vx_size dims[MAX_TENSOR_DIMS];
ERROR_CHECK_STATUS( vxQueryTensor(tensor, VX_TENSOR_DATA_TYPE, &data_type, sizeof(vx_enum)) );
ERROR_CHECK_STATUS( vxQueryTensor(tensor, VX_TENSOR_DIMS, &dims, sizeof(vx_size)*number_of_dims) );
switch(data_type) {
case VX_TYPE_INT16: stride[0] = sizeof(vx_int16); break;
case VX_TYPE_UINT8: stride[0] = sizeof(vx_uint8); break;
default: return VX_ERROR_NOT_SUPPORTED;
}
for(size_t dim = 1; dim < number_of_dims; dim++) {
stride[dim] = dims[dim-1] * stride[dim-1];
}
vx_size size = dims[number_of_dims-1] * stride[number_of_dims-1];
////
// create map_id and allocate temporary buffers to return
//
my_vx_tensor_map_id * id = new my_vx_tensor_map_id;
ERROR_CHECK_NOT_NULL( id );
id->number_of_dims = number_of_dims;
id->usage = usage;
id->mem_type = mem_type;
if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER)
{
vx_context context = vxGetContext((vx_reference)tensor);
cl_context opencl_ctx;
ERROR_CHECK_STATUS( vxQueryContext(context, VX_CONTEXT_CL_CONTEXT, &opencl_ctx, sizeof(cl_context)) );
cl_int err;
id->ptr = clCreateBuffer(opencl_ctx, CL_MEM_READ_WRITE, size, NULL, &err);
ERROR_CHECK_STATUS( err );
}
else
{
id->ptr = new vx_uint8[size];
ERROR_CHECK_NOT_NULL( id->ptr );
}
for(size_t dim = 0; dim < number_of_dims; dim++) {
id->view_start[dim] = view_start ? view_start[dim] : 0;
id->view_end[dim] = view_end ? view_end[dim] : dims[dim];
id->stride[dim] = stride[dim];
}
*map_id = (vx_map_id)id;
*ptr = id->ptr;
////
// copy tensor patch into temporarily allocated map buffer if read requested
//
if(id->usage == VX_READ_ONLY || id->usage == VX_READ_AND_WRITE)
{
vx_status status = vxCopyTensorPatch(tensor, id->number_of_dims,
id->view_start, id->view_end, id->stride, id->ptr,
VX_READ_ONLY, id->mem_type);
if(status != VX_SUCCESS)
{
// release resources in case or error
if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) {
ERROR_CHECK_STATUS( clReleaseMemObject((cl_mem)id->ptr) );
}
else {
delete (vx_uint8 *)id->ptr;
}
delete id;
return status;
}
}
return VX_SUCCESS;
}
////
// simple reference implementation (not optimized) for vxUnmapTensorPatch
// this uses the temporary buffer used for mapping in myVxMapTensorPatch
//
vx_status myVxUnmapTensorPatch(
vx_tensor tensor,
const vx_map_id map_id)
{
////
// access mapped data
//
my_vx_tensor_map_id * id = (my_vx_tensor_map_id *)map_id;
////
// copy tensor patch into temporarily allocated map buffer if read requested
//
if(id->usage == VX_WRITE_ONLY || id->usage == VX_READ_AND_WRITE)
{
vx_status status = vxCopyTensorPatch(tensor, id->number_of_dims,
id->view_start, id->view_end, id->stride, id->ptr,
VX_WRITE_ONLY, id->mem_type);
if(status != VX_SUCCESS) {
// release resources in case or error
if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) {
ERROR_CHECK_STATUS( clReleaseMemObject((cl_mem)id->ptr) );
}
else {
delete (vx_uint8 *)id->ptr;
}
delete id;
return status;
}
}
////
// release temporary buffers allocated for mapping
//
if(id->mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) {
ERROR_CHECK_STATUS( clReleaseMemObject((cl_mem)id->ptr) );
}
else {
delete (vx_uint8 *)id->ptr;
}
delete id;
return VX_SUCCESS;
}
| 35.57754 | 110 | 0.620171 | jwinarske |
c3b3be02cd5e6b18b4c670130f18b31ae9fcae99 | 20,235 | cxx | C++ | test/unit/config/config_test.cxx | ANSAKsoftware/ansak-lib | 93eff12a50464f3071b27c8eb16336f93d0d04c6 | [
"BSD-2-Clause"
] | null | null | null | test/unit/config/config_test.cxx | ANSAKsoftware/ansak-lib | 93eff12a50464f3071b27c8eb16336f93d0d04c6 | [
"BSD-2-Clause"
] | null | null | null | test/unit/config/config_test.cxx | ANSAKsoftware/ansak-lib | 93eff12a50464f3071b27c8eb16336f93d0d04c6 | [
"BSD-2-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Arthur N. Klassen
// 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.
//
///////////////////////////////////////////////////////////////////////////
//
// 2015.01.02 - First Version
//
// May you do good and not evil.
// May you find forgiveness for yourself and forgive others.
// May you share freely, never taking more than you give.
//
///////////////////////////////////////////////////////////////////////////
//
// configTest.cxx -- unit tests for the configuration collection
//
///////////////////////////////////////////////////////////////////////////
#include <gtest/gtest.h>
#include <config.hxx>
#include <config_atom.hxx>
#include <config_types.hxx>
#include <runtime_exception.hxx>
#include <ansak/string.hxx>
#include <string>
#include <vector>
using namespace std;
using namespace ansak;
using namespace ansak::internal;
using namespace testing;
//===========================================================================
TEST(ConfigTest, testSimpleInit)
{
Config simple;
EXPECT_TRUE(simple.getValueNames().empty());
simple.initValue("foo", true);
EXPECT_FALSE(simple.getValueNames().empty());
}
//===========================================================================
TEST(ConfigTest, testUnchangeableInitValues)
{
Config un;
un.initValue("b", true, Config::immutable);
un.initValue("i", 23, Config::immutable);
un.initValue("f", 3.1415926535f, Config::immutable);
un.initValue("d", 4.222333344444555555, Config::immutable);
un.initValue("s", string("Now is the time"), Config::immutable);
un.initValue("cp", "for all good men to come", Config::immutable);
un.initValue("pt", toPoint(3, 4), Config::immutable);
un.initValue("r", toRect(100, 60, 50, 30), Config::immutable);
bool b, changed;
int i;
float f;
double d;
string s, cp;
Point pt;
Rect r; changed = true;
EXPECT_TRUE(un.get("b", b, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("bb", b, &changed)); changed = true;
EXPECT_TRUE(un.get("i", i, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("ii", i, &changed)); changed = true;
EXPECT_TRUE(un.get("f", f, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("ff", f, &changed)); changed = false;
// retrieving a double value -- officially, we only store floats in settings,
// so retrieving a double is always a change from the original
EXPECT_TRUE(un.get("d", d, &changed)); EXPECT_TRUE(changed);
EXPECT_FALSE(un.get("dd", d, &changed)); changed = true;
EXPECT_TRUE(un.get("s", s, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("ss", s, &changed)); changed = true;
EXPECT_TRUE(un.get("cp", cp, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("ccp", cp, &changed)); changed = true;
EXPECT_TRUE(un.get("pt", pt, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("ppt", pt, &changed)); changed = true;
EXPECT_TRUE(un.get("r", r, &changed)); EXPECT_FALSE(changed);
EXPECT_FALSE(un.get("rr", r, &changed)); changed = true;
EXPECT_TRUE(b);
EXPECT_EQ(23, i);
EXPECT_TRUE(floatEqual(3.1415926535f, f));
EXPECT_TRUE(floatEqual(4.222333344444555555, d));
EXPECT_EQ(string("Now is the time"), s);
EXPECT_EQ(string("for all good men to come"), cp);
EXPECT_EQ(3, x(pt));
EXPECT_EQ(4, y(pt));
EXPECT_EQ(100, left(r));
EXPECT_EQ(60, top(r));
EXPECT_EQ(50, width(r));
EXPECT_EQ(30, height(r));
EXPECT_THROW(un.put("b", false), RuntimeException);
}
//===========================================================================
TEST(ConfigTest, testChangeableInitValues)
{
Config ch;
ch.initValue("b", true);
ch.initValue("i", 23);
ch.initValue("f", 3.1415926535f);
ch.initValue("d", 4.222333344444555555);
ch.initValue("s", string("Now is the time"));
ch.initValue("cp", "for all good men to come");
ch.initValue("pt", toPoint(3, 4));
ch.initValue("r", toRect(100, 60, 50, 30));
bool b, changed;
int i;
float f, d;
string s, cp;
Point pt;
Rect r; changed = true;
EXPECT_TRUE(ch.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("i", i, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("f", f, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("d", d, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("s", s, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("cp", cp, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("pt", pt, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(ch.get("r", r, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(b);
EXPECT_EQ(23, i);
EXPECT_TRUE(floatEqual(3.1415926535f, f));
EXPECT_TRUE(floatEqual(4.222333344444555555, d));
EXPECT_EQ(string("Now is the time"), s);
EXPECT_EQ(string("for all good men to come"), cp);
EXPECT_EQ(3, x(pt));
EXPECT_EQ(4, y(pt));
EXPECT_EQ(100, left(r));
EXPECT_EQ(60, top(r));
EXPECT_EQ(50, width(r));
EXPECT_EQ(30, height(r));
ch.put("b", false);
ch.put("i", 32);
ch.put("f", 2.7182818301f);
ch.put("d", 5.6677788889999900000111111);
ch.put("s", "Et Earello Endorenna utulien.");
ch.put("cp", "Sinome maruvan ar Hildinyar tenn' ambar metta.");
ch.put("pt", toPoint(5, 6));
ch.put("r", toRect(500, 300, 20, 20));
changed = false;
EXPECT_TRUE(ch.get("b", b, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("i", i, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("f", f, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("d", d, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("s", s, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("cp", cp, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("pt", pt, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_TRUE(ch.get("r", r, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_FALSE(b);
EXPECT_EQ(32, i);
EXPECT_TRUE(floatEqual(2.7182818301f, f));
EXPECT_TRUE(floatEqual(5.6677788889999900000111111, d));
EXPECT_EQ(string("Et Earello Endorenna utulien."), s);
EXPECT_EQ(string("Sinome maruvan ar Hildinyar tenn' ambar metta."), cp);
EXPECT_EQ(5, x(pt));
EXPECT_EQ(6, y(pt));
EXPECT_EQ(500, left(r));
EXPECT_EQ(300, top(r));
EXPECT_EQ(20, width(r));
EXPECT_EQ(20, height(r));
}
//===========================================================================
TEST(ConfigTest, testGetValueNames)
{
Config ch;
ch.initValue("b", true);
ch.initValue("i", 23);
ch.initValue("f", 3.1415926535f);
ch.initValue("d", 4.222333344444555555);
ch.initValue("s", string("Now is the time"));
ch.initValue("cp", "for all good men to come");
ch.initValue("pt", toPoint(3, 4));
ch.initValue("r", toRect(100, 60, 50, 30));
bool gotB = false;
bool gotI = false;
bool gotF = false;
bool gotD = false;
bool gotS = false;
bool gotCP = false;
bool gotPT = false;
bool gotR = false;
auto names = ch.getValueNames();
EXPECT_EQ(static_cast<size_t>(8), names.size());
for (auto n : names)
{
if (n == "b") gotB = true;
else if (n == "i") gotI = true;
else if (n == "f") gotF = true;
else if (n == "d") gotD = true;
else if (n == "s") gotS = true;
else if (n == "cp") gotCP = true;
else if (n == "pt") gotPT = true;
else if (n == "r") gotR = true;
}
EXPECT_TRUE(gotB);
EXPECT_TRUE(gotI);
EXPECT_TRUE(gotF);
EXPECT_TRUE(gotD);
EXPECT_TRUE(gotS);
EXPECT_TRUE(gotCP);
EXPECT_TRUE(gotPT);
EXPECT_TRUE(gotR);
}
//===========================================================================
TEST(ConfigTest, testTemplatedConstructor)
{
const vector<string> utf8v{
"b=true",
"i=23",
"f=3.14159265",
"d=5.66777888899999",
"s=ash nazg durbatuluk",
"pt=3,4",
"",
"r=(100,40),(60,20)",
"q=v=w"
};
Config c0(utf8v);
bool b, changed;
int i;
float f, d;
string s,q;
Point pt;
Rect r; changed = true;
EXPECT_TRUE(c0.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("i", i, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("f", f, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("d", d, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("s", s, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("pt", pt, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("r", r, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(c0.get("q", q, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(b);
EXPECT_EQ(23, i);
EXPECT_TRUE(floatEqual(3.14159265f, f));
EXPECT_TRUE(floatEqual(5.66777888899999, d));
EXPECT_EQ(string("ash nazg durbatuluk"), s);
EXPECT_EQ(3, x(pt));
EXPECT_EQ(4, y(pt));
EXPECT_EQ(100, left(r));
EXPECT_EQ(40, top(r));
EXPECT_EQ(60, width(r));
EXPECT_EQ(20, height(r));
EXPECT_EQ(string("v=w"), q);
}
//===========================================================================
TEST(ConfigTest, testGetValues)
{
Config ch;
ch.initValue("b", true);
ch.initValue("i", 23);
ch.initValue("f", 3.1415926535f);
ch.initValue("d", 4.222333344444555555);
ch.initValue("s", string("Now is the time"));
ch.initValue("cp", "for all good men to come");
ch.initValue("pt", toPoint(3, 4));
ch.initValue("r", toRect(100, 60, 50, 30));
bool b;
int i;
float f;
double d;
string s;
Point pt;
Rect r;
EXPECT_TRUE(ch.get("b", b)); EXPECT_TRUE(b);
EXPECT_TRUE(ch.get("b", i)); EXPECT_EQ(1, i);
EXPECT_TRUE(ch.get("b", f)); EXPECT_TRUE(floatEqual(1.0f, f));
EXPECT_TRUE(ch.get("b", d)); EXPECT_TRUE(floatEqual(1.0, d));
EXPECT_TRUE(ch.get("b", s)); EXPECT_EQ(string("true"), s);
EXPECT_FALSE(ch.get("b", pt));
EXPECT_FALSE(ch.get("b", r));
EXPECT_TRUE(ch.get("i", b)); EXPECT_TRUE(b);
EXPECT_TRUE(ch.get("i", i)); EXPECT_EQ(23, i);
EXPECT_TRUE(ch.get("i", f)); EXPECT_TRUE(floatEqual(23.0f, f));
EXPECT_TRUE(ch.get("i", d)); EXPECT_TRUE(floatEqual(23.0, d));
EXPECT_TRUE(ch.get("i", s)); EXPECT_EQ(string("23"), s);
EXPECT_FALSE(ch.get("i", pt));
EXPECT_FALSE(ch.get("i", r));
EXPECT_TRUE(ch.get("f", b)); EXPECT_TRUE(b);
EXPECT_FALSE(ch.get("f", i));
EXPECT_TRUE(ch.get("f", f)); EXPECT_TRUE(floatEqual(3.1415926535f, f));
EXPECT_TRUE(ch.get("f", d)); EXPECT_TRUE(floatEqual(3.1415926535, d));
EXPECT_TRUE(ch.get("f", s)); EXPECT_EQ(string("3.14159"), s);
EXPECT_FALSE(ch.get("f", pt));
EXPECT_FALSE(ch.get("f", r));
EXPECT_TRUE(ch.get("d", b)); EXPECT_TRUE(b);
EXPECT_FALSE(ch.get("d", i));
EXPECT_TRUE(ch.get("d", f)); EXPECT_TRUE(floatEqual(4.2223333444f, f));
EXPECT_TRUE(ch.get("d", d)); EXPECT_TRUE(floatEqual(4.2223333444, d));
EXPECT_TRUE(ch.get("d", s)); EXPECT_EQ(string("4.22233"), s);
EXPECT_FALSE(ch.get("d", pt));
EXPECT_FALSE(ch.get("d", r));
EXPECT_FALSE(ch.get("s", b));
EXPECT_FALSE(ch.get("s", i));
EXPECT_FALSE(ch.get("s", f));
EXPECT_FALSE(ch.get("s", d));
EXPECT_TRUE(ch.get("s", s)); EXPECT_EQ(string("Now is the time"), s);
EXPECT_FALSE(ch.get("s", pt));
EXPECT_FALSE(ch.get("s", r));
EXPECT_FALSE(ch.get("cp", b));
EXPECT_FALSE(ch.get("cp", i));
EXPECT_FALSE(ch.get("cp", f));
EXPECT_FALSE(ch.get("cp", d));
EXPECT_TRUE(ch.get("cp", s)); EXPECT_EQ(string("for all good men to come"), s);
EXPECT_FALSE(ch.get("cp", pt));
EXPECT_FALSE(ch.get("cp", r));
EXPECT_FALSE(ch.get("pt", b));
EXPECT_FALSE(ch.get("pt", i));
EXPECT_FALSE(ch.get("pt", f));
EXPECT_FALSE(ch.get("pt", d));
EXPECT_TRUE(ch.get("pt", s)); EXPECT_EQ(string("3,4"), s);
EXPECT_TRUE(ch.get("pt", pt));
EXPECT_EQ(3, x(pt));
EXPECT_EQ(4, y(pt));
EXPECT_FALSE(ch.get("pt", r));
EXPECT_FALSE(ch.get("r", b));
EXPECT_FALSE(ch.get("r", i));
EXPECT_FALSE(ch.get("r", f));
EXPECT_FALSE(ch.get("r", d));
EXPECT_TRUE(ch.get("r", s)); EXPECT_EQ(string("(100,60),(50,30)"), s);
EXPECT_FALSE(ch.get("r", pt));
EXPECT_TRUE(ch.get("r", r));
EXPECT_EQ(100, left(r));
EXPECT_EQ(60, top(r));
EXPECT_EQ(50, width(r));
EXPECT_EQ(30, height(r));
}
// these two "case" ideas are being tested in testChangeableInitValues
// TEST(ConfigTest, testPutValues);
// TEST(ConfigTest, testGetChangedValues);
//===========================================================================
TEST(ConfigTest, testPutForceTypeValues)
{
Config ch;
ch.initValue("b", true);
ch.initValue("i", 23);
ch.initValue("pi", 3.1415926535f, Config::immutable);
ch.initValue("d", 4.222333344444555555);
ch.initValue("s", string("Now is the time"));
ch.initValue("cp", "for all good men to come");
ch.initValue("pt", toPoint(3, 4));
ch.initValue("r", toRect(100, 60, 50, 30));
ch.put("b", 34, Config::forceTypeChange);
ch.put("i", 2.71828301, Config::forceTypeChange);
EXPECT_THROW(ch.put("pi", 3.14, Config::forceTypeChange), RuntimeException);
ch.put("d", "Sorry, Murphy, no real constants are variable.", Config::forceTypeChange);
ch.put("s", toPoint(16,22), Config::forceTypeChange);
ch.put("pt", toRect(1,4,9,16), Config::forceTypeChange);
ch.put("r", false, Config::forceTypeChange);
bool b, changed;
int i;
float pi, d;
string s;
Point pt;
Rect r; changed = false;
EXPECT_TRUE(ch.get("b", i, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_EQ(34, i);
EXPECT_TRUE(ch.get("i", d, &changed)); EXPECT_TRUE(changed); changed = true;
EXPECT_TRUE(floatEqual(2.71828301, d));
EXPECT_TRUE(ch.get("pi", pi, &changed)); EXPECT_FALSE(changed); changed = false;
EXPECT_TRUE(floatEqual(3.1415926, pi));
EXPECT_TRUE(ch.get("d", s, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_EQ(string("Sorry, Murphy, no real constants are variable."), s);
EXPECT_TRUE(ch.get("s", pt, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_EQ(16, x(pt));
EXPECT_EQ(22, y(pt));
EXPECT_TRUE(ch.get("pt", r, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_EQ(1, left(r));
EXPECT_EQ(4, top(r));
EXPECT_EQ(9, width(r));
EXPECT_EQ(16, height(r));
EXPECT_TRUE(ch.get("r", b, &changed)); EXPECT_TRUE(changed); changed = false;
EXPECT_FALSE(b);
ch.put("b", 1.618f, Config::forceTypeChange);
EXPECT_TRUE(ch.get("b", d, &changed)); EXPECT_TRUE(changed); changed = true;
EXPECT_TRUE(floatEqual(1.618, d));
}
//===========================================================================
TEST(ConfigTest, testDefaultWith)
{
Config s;
s.initValue("a", 3);
s.initValue("b", 4);
Config q;
q.initValue("c", 5);
s.defaultWith(q);
int a, b, c;
bool changed = true;
EXPECT_TRUE(s.get("a", a, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(s.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(s.get("c", c, &changed)); EXPECT_FALSE(changed);
EXPECT_EQ(3, a);
EXPECT_EQ(4, b);
EXPECT_EQ(5, c);
}
//===========================================================================
TEST(ConfigTest, testOverrideWith)
{
Config s;
s.initValue("a", "33");
s.initValue("b", 4);
s.initValue("pi", 3.141592653, Config::immutable);
Config q;
q.initValue("c", 5);
q.initValue("a", 3);
q.initValue("pi", "3.14");
s.overrideWith(q);
int a, b, c;
float f;
bool changed = true;
EXPECT_TRUE(s.get("a", a, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(s.get("b", b, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(s.get("c", c, &changed)); EXPECT_FALSE(changed); changed = true;
EXPECT_TRUE(s.get("pi", f, &changed)); EXPECT_FALSE(changed);
EXPECT_EQ(3, a);
EXPECT_EQ(4, b);
EXPECT_EQ(5, c);
EXPECT_TRUE(floatEqual(3.1415926, f));
}
//===========================================================================
TEST(ConfigTest, testKeepOverridesOf)
{
Config s;
s.initValue("a", 3);
s.initValue("b", 4);
s.initValue("c", 55);
Config q;
q.initValue("c", 5);
Config savedQ(q);
EXPECT_EQ(q, savedQ);
q.defaultWith(s);
EXPECT_NE(q, savedQ);
q.keepOverridesOf(s);
EXPECT_EQ(q, savedQ);
}
//===========================================================================
TEST(ConfigTest, testAtomTransaction)
{
const vector<string> utf8v{
"b= true ",
"i=23",
"f=3.14159265",
"d=5.66777888899999",
"s=ash nazg durbatuluk",
"pt=3,4",
"",
"r=(100,40),(60,20)",
"q=v=w"
};
Config c0(utf8v);
vector<ConfigAtomPair> atomPairs;
atomPairs.push_back(ConfigAtomPair(string("b"), c0.getAtom("b")));
atomPairs.push_back(ConfigAtomPair(string("i"), c0.getAtom("i")));
atomPairs.push_back(ConfigAtomPair(string("f"), c0.getAtom("f")));
atomPairs.push_back(ConfigAtomPair(string("d"), c0.getAtom("d")));
atomPairs.push_back(ConfigAtomPair(string("s"), c0.getAtom("s")));
atomPairs.push_back(ConfigAtomPair(string("pt"), c0.getAtom("pt")));
atomPairs.push_back(ConfigAtomPair(string("r"), c0.getAtom("r")));
atomPairs.push_back(ConfigAtomPair(string("q"), c0.getAtom("q")));
EXPECT_EQ(ConfigAtom(), c0.getAtom("notThere"));
Config c1(atomPairs);
EXPECT_EQ(c0, c1);
Config c2 = c1;
c2.put("b", false);
EXPECT_NE(c2, c1);
c1.put("b", false);
EXPECT_EQ(c2, c1);
Config c3;
c3 = c2;
EXPECT_EQ(c3, c1);
}
//===========================================================================
TEST(ConfigTest, manualAdd)
{
const vector<string> utf8v{
"b=true",
"i=23",
"f=3.14159265",
"d=5.66777888899999",
"s=ash nazg durbatuluk",
"pt=3,4",
"r=(100,40),(60,20)"
};
Config c0(utf8v);
Config c1;
c1.put("r", toRect(100,40,60,20));
c1.put("pt", toPoint(3,4));
c1.put("s", "ash nazg durbatuluk");
c1.put("d", 5.66777888899999);
c1.put("f", 3.14159265f);
c1.put("i", 23);
c1.put("b", true);
EXPECT_EQ(c0, c1);
}
| 35.437828 | 91 | 0.586064 | ANSAKsoftware |
c3b63176a0f1f33169a106afa3ff6f16cfedada4 | 1,770 | hpp | C++ | modules/sdk/include/nt2/sdk/config/compiler/report.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | 1 | 2022-03-24T03:35:10.000Z | 2022-03-24T03:35:10.000Z | modules/sdk/include/nt2/sdk/config/compiler/report.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | modules/sdk/include/nt2/sdk/config/compiler/report.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"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_SDK_CONFIG_COMPILER_REPORT_HPP_INCLUDED
#define NT2_SDK_CONFIG_COMPILER_REPORT_HPP_INCLUDED
////////////////////////////////////////////////////////////////////////////////
// Architecture configuration headers
// Defines architecture symbols for architecture related variation point.
// Documentation: http://nt2.lri.fr/sdk/config/compiler.html
////////////////////////////////////////////////////////////////////////////////
#include <nt2/sdk/config/compiler.hpp>
#include <nt2/sdk/config/details/reporter.hpp>
namespace nt2 { namespace config
{
//////////////////////////////////////////////////////////////////////////////
// Status header reporter - Head for the reporter list
//////////////////////////////////////////////////////////////////////////////
inline void compiler()
{
puts(" Compiler : " NT2_COMPILER_STRING);
puts(" Rvalue references : "
#if defined(BOOST_NO_RVALUE_REFERENCES)
"unsupported"
#else
"supported"
#endif
);
puts(" Variadic templates : "
#if defined(BOOST_NO_VARIADIC_TEMPLATES)
"unsupported"
#else
"supported"
#endif
"\n"
);
}
NT2_REGISTER_STATUS(compiler);
} }
#endif
| 35.4 | 80 | 0.472881 | brycelelbach |
c3b899b877daa6a822136cf309b6e165c4c3e3dc | 2,820 | cpp | C++ | sources/Renderer/Direct3D12/Command/D3D12CommandContext.cpp | wirx6/LLGL | 2fc63aa5ddf4f5bd006c496cd9bbf6b40c2133ee | [
"BSD-3-Clause"
] | null | null | null | sources/Renderer/Direct3D12/Command/D3D12CommandContext.cpp | wirx6/LLGL | 2fc63aa5ddf4f5bd006c496cd9bbf6b40c2133ee | [
"BSD-3-Clause"
] | null | null | null | sources/Renderer/Direct3D12/Command/D3D12CommandContext.cpp | wirx6/LLGL | 2fc63aa5ddf4f5bd006c496cd9bbf6b40c2133ee | [
"BSD-3-Clause"
] | null | null | null | /*
* D3D12CommandContext.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2018 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "D3D12CommandContext.h"
#include "../D3D12Resource.h"
#include "../../DXCommon/DXCore.h"
namespace LLGL
{
void D3D12CommandContext::SetCommandList(ID3D12GraphicsCommandList* commandList)
{
if (commandList_ != commandList)
{
FlushResourceBarrieres();
commandList_ = commandList;
}
}
void D3D12CommandContext::TransitionResource(D3D12Resource& resource, D3D12_RESOURCE_STATES newState, bool flushBarrieres)
{
auto oldState = resource.transitionState;
if (oldState != newState)
{
auto& barrier = NextResourceBarrier();
/* Initialize resource barrier for resource transition */
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
barrier.Transition.pResource = resource.native.Get();
barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
barrier.Transition.StateBefore = oldState;
barrier.Transition.StateAfter = newState;
/* Store new state in resource */
resource.transitionState = newState;
/* Flush resource barrieres if required */
if (flushBarrieres)
FlushResourceBarrieres();
}
}
void D3D12CommandContext::FlushResourceBarrieres()
{
if (numResourceBarriers_ > 0)
{
commandList_->ResourceBarrier(numResourceBarriers_, resourceBarriers_);
numResourceBarriers_ = 0;
}
}
void D3D12CommandContext::ResolveRenderTarget(
D3D12Resource& dstResource,
UINT dstSubresource,
D3D12Resource& srcResource,
UINT srcSubresource,
DXGI_FORMAT format)
{
/* Transition both resources */
TransitionResource(dstResource, D3D12_RESOURCE_STATE_RESOLVE_DEST, false);
TransitionResource(srcResource, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
/* Resolve multi-sampled render targets */
commandList_->ResolveSubresource(
dstResource.native.Get(),
dstSubresource,
srcResource.native.Get(),
srcSubresource,
format
);
/* Transition both resources */
TransitionResource(dstResource, dstResource.usageState, false);
TransitionResource(srcResource, srcResource.usageState);
}
/*
* ======= Private: =======
*/
D3D12_RESOURCE_BARRIER& D3D12CommandContext::NextResourceBarrier()
{
if (numResourceBarriers_ == g_maxNumResourceBarrieres)
FlushResourceBarrieres();
return resourceBarriers_[numResourceBarriers_++];
}
} // /namespace LLGL
// ================================================================================
| 27.647059 | 122 | 0.669149 | wirx6 |
c3b9a85b1d2b939baf36f5aa43b50e021a7dc906 | 115 | hpp | C++ | gtrc_vehicles/CfgAmmo.hpp | kzfoxx/GTRC-Framework | e60b1f6d7c5d594e22ef6c2d95c0db61d7d3d0f6 | [
"MIT"
] | null | null | null | gtrc_vehicles/CfgAmmo.hpp | kzfoxx/GTRC-Framework | e60b1f6d7c5d594e22ef6c2d95c0db61d7d3d0f6 | [
"MIT"
] | null | null | null | gtrc_vehicles/CfgAmmo.hpp | kzfoxx/GTRC-Framework | e60b1f6d7c5d594e22ef6c2d95c0db61d7d3d0f6 | [
"MIT"
] | null | null | null |
class CfgAmmo {
class BulletBase;
class Gatling_30mm_HE_Plane_CAS_01_F: BulletBase {
caliber = 6;
};
}; | 16.428571 | 52 | 0.695652 | kzfoxx |
c3bba75286889988256e08f90493166842347443 | 7,911 | cpp | C++ | src/Mesh.cpp | akoylasar/PBR | 17e6197fb5357220e2f1454898a18f8890844d4d | [
"MIT"
] | null | null | null | src/Mesh.cpp | akoylasar/PBR | 17e6197fb5357220e2f1454898a18f8890844d4d | [
"MIT"
] | null | null | null | src/Mesh.cpp | akoylasar/PBR | 17e6197fb5357220e2f1454898a18f8890844d4d | [
"MIT"
] | null | null | null | /*
* Copyright (c) Fouad Valadbeigi (akoylasar@gmail.com) */
#include "Mesh.hpp"
#include <cmath>
#include "Debug.hpp"
namespace Akoylasar
{
constexpr double kTwoPi = Neon::kPi * 2.0;
std::unique_ptr<Mesh> Mesh::buildSphere(double radius,
unsigned int hSegments,
unsigned int vSegments)
{
std::unique_ptr<Mesh> mesh = std::make_unique<Mesh>();
const int numVerts = (hSegments + 1) * (vSegments + 1);
mesh->vertices.reserve(numVerts);
for (int h = 0; h <= hSegments; ++h)
{
const double phi = static_cast<double>(h) / hSegments;
const double y = radius * std::cos(phi * Neon::kPi);
const double r = radius * std::sin(phi * Neon::kPi);
for (int v = 0; v <= vSegments; ++v)
{
Vertex vert;
const double theta = static_cast<double>(v) / vSegments;
const double x = -std::cos(theta * kTwoPi) * r;
const double z = std::sin(theta * kTwoPi) * r;
vert.position.x = x;
vert.position.y = y;
vert.position.z = z;
vert.normal = Neon::normalize(vert.position);
vert.uv.x = theta;
vert.uv.y = phi;
mesh->vertices.push_back(vert);
}
}
// Generate indices. TRIANGLE topology.
unsigned int indexCount = 6 * vSegments * (hSegments - 1);
mesh->indices.reserve(indexCount);
for (int h = 0; h < hSegments; ++h)
{
for (int v = 0; v < vSegments; ++v)
{
const unsigned int s = vSegments + 1;
const unsigned int a = h * s + (v + 1);
const unsigned int b = h * s + v;
const unsigned int c = (h + 1) * s + v;
const unsigned int d = (h + 1) * s + (v + 1);
// Avoid degenerate triangles in the caps.
if (h != 0)
{
mesh->indices.push_back(a);
mesh->indices.push_back(b);
mesh->indices.push_back(d);
}
if (h != hSegments - 1)
{
mesh->indices.push_back(b);
mesh->indices.push_back(c);
mesh->indices.push_back(d);
}
}
}
return mesh;
}
std::unique_ptr<Mesh> Mesh::buildQuad()
{
std::unique_ptr<Mesh> mesh = std::make_unique<Mesh>();
std::vector<Vertex> vertices = {
{Neon::Vec3f{-1, 1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 0}}, // top left
{Neon::Vec3f{1, 1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 0}}, // top right
{Neon::Vec3f{1, -1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 1}}, // bottom right
{Neon::Vec3f{-1, -1, 0.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 1}} // bottom left
};
std::vector<unsigned int> indices {
3, 1, 0,
3, 2, 1
};
mesh->vertices.assign(vertices.begin(), vertices.end());
mesh->indices.assign(indices.begin(), indices.end());
return mesh;
}
std::unique_ptr<Mesh> Mesh::buildCube()
{
std::unique_ptr<Mesh> mesh = std::make_unique<Mesh>();
std::vector<Vertex> vertices = {
// Front face
{Neon::Vec3f{-1, 1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 0}},
{Neon::Vec3f{1, 1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 0}},
{Neon::Vec3f{1, -1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{1, 1}},
{Neon::Vec3f{-1, -1, 1.0}, Neon::Vec3f{0, 0, 1.0}, Neon::Vec2f{0, 1}},
// Back face
{Neon::Vec3f{-1, 1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{1, 0}},
{Neon::Vec3f{1, 1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{0, 0}},
{Neon::Vec3f{1, -1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{0, 1}},
{Neon::Vec3f{-1, -1, -1.0}, Neon::Vec3f{0, 0, -1.0}, Neon::Vec2f{1, 1}},
// Left face
{Neon::Vec3f{-1, 1, -1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{0, 0}},
{Neon::Vec3f{-1, 1, 1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{1, 0}},
{Neon::Vec3f{-1, -1, 1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{1, 1}},
{Neon::Vec3f{-1, -1, -1.0}, Neon::Vec3f{-1, 0, 0}, Neon::Vec2f{0, 1}},
// Right face
{Neon::Vec3f{1, 1, -1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{1, 0}},
{Neon::Vec3f{1, 1, 1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{0, 0}},
{Neon::Vec3f{1, -1, 1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{0, 1}},
{Neon::Vec3f{1, -1, -1.0}, Neon::Vec3f{1, 0, 0}, Neon::Vec2f{1, 1}},
// Top face
{Neon::Vec3f{-1, 1, -1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{0, 0}},
{Neon::Vec3f{1, 1, -1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{1, 0}},
{Neon::Vec3f{1, 1, 1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{1, 1}},
{Neon::Vec3f{-1, 1, 1.0}, Neon::Vec3f{0, 1, 0}, Neon::Vec2f{0, 1}},
// Bottom face
{Neon::Vec3f{-1, -1, -1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{1, 0}},
{Neon::Vec3f{1, -1, -1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{0, 0}},
{Neon::Vec3f{1, -1, 1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{0, 1}},
{Neon::Vec3f{-1, -1, 1.0}, Neon::Vec3f{0, -1, 0}, Neon::Vec2f{1, 1}},
};
std::vector<unsigned int> indices {
3, 1, 0,
3, 2, 1,
4, 5, 7,
5, 6, 7,
11, 9, 8,
11, 10, 9,
12, 13, 15,
13, 14, 15,
19, 17, 16,
19, 18, 17,
20, 21, 23,
21, 22, 23
};
mesh->vertices.assign(vertices.begin(), vertices.end());
mesh->indices.assign(indices.begin(), indices.end());
return mesh;
}
GpuMesh GpuMesh::createGpuMesh(const Mesh& mesh,
GLuint positionAttribuIndex,
GLuint normalAttribuIndex,
GLuint uvAttribuIndex)
{
GpuMesh gpuMesh;
// Vao setup.
CHECK_GL_ERROR(glGenVertexArrays(1, &gpuMesh.vao));
CHECK_GL_ERROR(glBindVertexArray(gpuMesh.vao));
// Setup vertex buffer.
CHECK_GL_ERROR(glGenBuffers(1, &gpuMesh.vbo));
CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, gpuMesh.vbo));
const auto vertexBufferSize = mesh.vertices.size() * sizeof(Vertex);
CHECK_GL_ERROR(glBufferData(GL_ARRAY_BUFFER, vertexBufferSize, &mesh.vertices.at(0), GL_STATIC_DRAW));
// Setup index buffer.
CHECK_GL_ERROR(glGenBuffers(1, &gpuMesh.ebo));
CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gpuMesh.ebo));
const auto indexBufferSize = mesh.indices.size() * sizeof(std::uint32_t);
CHECK_GL_ERROR(glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBufferSize, &mesh.indices.at(0), GL_STATIC_DRAW));
// Specify vertex format.
CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, gpuMesh.vbo));
CHECK_GL_ERROR(glVertexAttribPointer(positionAttribuIndex, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, position))));
CHECK_GL_ERROR(glEnableVertexAttribArray(0));
CHECK_GL_ERROR(glVertexAttribPointer(normalAttribuIndex, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, normal))));
CHECK_GL_ERROR(glEnableVertexAttribArray(1));
CHECK_GL_ERROR(glVertexAttribPointer(uvAttribuIndex, 2, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, uv))));
CHECK_GL_ERROR(glEnableVertexAttribArray(2));
CHECK_GL_ERROR(glBindVertexArray(0));
gpuMesh.indexCount = mesh.indices.size();
gpuMesh.drawMode = GL_TRIANGLES;
return gpuMesh;
}
void GpuMesh::releaseGpuMesh(GpuMesh& gpuMesh)
{
CHECK_GL_ERROR(glDeleteBuffers(1, &gpuMesh.vbo));
CHECK_GL_ERROR(glDeleteBuffers(1, &gpuMesh.ebo));
CHECK_GL_ERROR(glDeleteVertexArrays(1, &gpuMesh.vao));
gpuMesh.vbo = 0;
gpuMesh.ebo = 0;
gpuMesh.vao = 0;
}
void GpuMesh::draw() const
{
CHECK_GL_ERROR(glBindVertexArray(vao));
CHECK_GL_ERROR(glDrawElements(drawMode,
indexCount,
GL_UNSIGNED_INT,
nullptr));
}
}
| 36.456221 | 137 | 0.551511 | akoylasar |
c3bc07d4fdcc84118cefbbc09dcf758bd40f825b | 2,567 | cpp | C++ | NaoTHSoccer/Source/Cognition/Modules/Behavior/XABSLBehaviorControl/Symbols/PathSymbols.cpp | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 15 | 2015-01-12T10:46:29.000Z | 2022-03-28T05:13:14.000Z | NaoTHSoccer/Source/Cognition/Modules/Behavior/XABSLBehaviorControl/Symbols/PathSymbols.cpp | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-01-20T21:07:50.000Z | 2020-01-22T14:00:28.000Z | NaoTHSoccer/Source/Cognition/Modules/Behavior/XABSLBehaviorControl/Symbols/PathSymbols.cpp | BerlinUnited/NaoTH | 02848ac10c16a5349f1735da8122a64d601a5c75 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2018-02-07T18:18:10.000Z | 2019-10-15T17:01:41.000Z | /**
* @file PathSymbols.cpp
*
* @author <a href="mailto:akcayyig@hu-berlin.de">Yigit Can Akcay</a>
*/
#include "PathSymbols.h"
void PathSymbols::registerSymbols(xabsl::Engine& engine)
{
// PathPlanner2018Routine
engine.registerEnumElement("path2018.routine", "path2018.routine.none", static_cast<int>(PathModel::PathPlanner2018Routine::NONE));
engine.registerEnumElement("path2018.routine", "path2018.routine.move_around_ball2", static_cast<int>(PathModel::PathPlanner2018Routine::MOVE_AROUND_BALL2));
engine.registerEnumElement("path2018.routine", "path2018.routine.forwardkick", static_cast<int>(PathModel::PathPlanner2018Routine::FORWARDKICK));
engine.registerEnumElement("path2018.routine", "path2018.routine.sidekick_left", static_cast<int>(PathModel::PathPlanner2018Routine::SIDEKICK_LEFT));
engine.registerEnumElement("path2018.routine", "path2018.routine.sidekick_right", static_cast<int>(PathModel::PathPlanner2018Routine::SIDEKICK_RIGHT));
engine.registerEnumElement("path2018.routine", "path2018.routine.sidestep", static_cast<int>(PathModel::PathPlanner2018Routine::SIDESTEP));
engine.registerEnumeratedOutputSymbol("path2018.routine", "path2018.routine", &setPathRoutine2018, &getPathRoutine2018);
// go to ball: distance and yOffset
engine.registerDecimalOutputSymbol("path.distance", &getPathModel().distance);
engine.registerDecimalOutputSymbol("path.yOffset", &getPathModel().yOffset); //TODO delete me
// move around ball: direction and radius
//engine.registerDecimalOutputSymbol("path.direction", &getPathModel().direction); // TODO this is in degrees should be converted here somehow
engine.registerDecimalOutputSymbol("path.direction", &setDirection, &getDirection);
engine.registerDecimalOutputSymbol("path.radius", &getPathModel().radius);
engine.registerBooleanOutputSymbol("path.stable", &getPathModel().stable);
engine.registerBooleanInputSymbol("path.kick_executed", &getPathModel().kick_executed);
}
PathSymbols* PathSymbols::theInstance = NULL;
void PathSymbols::execute()
{
}
void PathSymbols::setPathRoutine2018(int id) {
theInstance->getPathModel().path2018_routine = static_cast<PathModel::PathPlanner2018Routine>(id);
}
int PathSymbols::getPathRoutine2018() {
return static_cast<int>(theInstance->getPathModel().path2018_routine);
}
void PathSymbols::setDirection(double rot) {
theInstance->getPathModel().direction = Math::fromDegrees(rot);
}
double PathSymbols::getDirection() {
return Math::toDegrees(theInstance->getPathModel().direction);
}
| 45.035088 | 160 | 0.781457 | BerlinUnited |
c3c0b8d89474801267ed5e37059dfe1f44fc8778 | 730 | cpp | C++ | src/utils/InetUtils.cpp | GbaLog/wad_packer | 212af80a8e1e475221be4b5ec241bd77ec126899 | [
"MIT"
] | 4 | 2021-09-12T00:13:04.000Z | 2022-02-19T11:18:33.000Z | src/utils/InetUtils.cpp | GbaLog/wad_packer | 212af80a8e1e475221be4b5ec241bd77ec126899 | [
"MIT"
] | null | null | null | src/utils/InetUtils.cpp | GbaLog/wad_packer | 212af80a8e1e475221be4b5ec241bd77ec126899 | [
"MIT"
] | null | null | null | #include "InetUtils.h"
//-----------------------------------------------------------------------------
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
//-----------------------------------------------------------------------------
namespace ratel
{
//-----------------------------------------------------------------------------
uint16_t htons(uint16_t val)
{
return ::htons(val);
}
//-----------------------------------------------------------------------------
uint32_t htonl(uint32_t val)
{
return ::htonl(val);
}
//-----------------------------------------------------------------------------
}
//-----------------------------------------------------------------------------
| 30.416667 | 80 | 0.217808 | GbaLog |
c3c2d1148cb620429b9719256d6d9f3ddf63bfaa | 3,800 | hpp | C++ | src/decoders/novatel/api/separator.hpp | novatel/novatel_edie | d212681f1952704e50e9c8977891dd024c3338ae | [
"MIT"
] | 3 | 2021-05-04T21:14:18.000Z | 2021-07-23T17:19:54.000Z | src/decoders/novatel/api/separator.hpp | novatel/novatel_edie | d212681f1952704e50e9c8977891dd024c3338ae | [
"MIT"
] | 1 | 2022-03-07T18:04:18.000Z | 2022-03-07T18:04:18.000Z | src/decoders/novatel/api/separator.hpp | novatel/novatel_edie | d212681f1952704e50e9c8977891dd024c3338ae | [
"MIT"
] | 2 | 2021-05-04T21:18:25.000Z | 2021-06-24T08:51:43.000Z | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020 NovAtel Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
/*! \file separator.hpp
* \brief To extact the ASCII field separators (, or ;.
* Ascii field separator in message ','
* Ascii header end ';'
* Ascii bosy and CRC separator '*'
* Ascii string terminator '\0'
* Quote '"'
* Carriage return '0x0d'
*
*/
//-----------------------------------------------------------------------
// Recursive Inclusion
//-----------------------------------------------------------------------
#ifndef SEPARATOR_H
#define SEPARATOR_H
//-----------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------
#include "decoders/common/api/common.hpp"
//const char VT = 0x9; // Vertical Tab
//const char HT = 0xB; // Horizontal Tab
/*! \def CR_HEX
* \brief A macro that returns the hex value of Carriage Return(CR)
*
*/
#define CR_HEX (0x0D)
/*! \def LF_HEX
* \brief A macro that returns the hex value of Line Feed(LF)
*
*/
#define LF_HEX (0x0A)
/*! \class Separator
* \brief Return Ascii filed separators in a message.
*
*/
class Separator
{
public:
/*! A constructor
*
*/
Separator();
/*! A destructor
* \brief Set Ascii separator set array
*/
~Separator();
/*! \fn SeparatorEnum FindNext(const Format eFormat_, CHAR** psFieldStart_, CHAR** psFieldEnd_, const CHAR* pcBufferEnd_)
* \brief It will return ascii field separator
* \param [in] eFormat_ Message Format(Currently Supports ASCII)
* \param [in] psFieldStart_ Start of the field address
* \param [in] psFieldEnd_ of the field address
* \param [in] pcBufferEnd_ Buffer end point
* \return Ascii field separator Enumaration
* \sa SeparatorEnum
*/
SeparatorEnum FindNext(const Format eFormat_, CHAR** psFieldStart_, CHAR** psFieldEnd_, const CHAR* pcBufferEnd_);
private:
/*! Private Copy Constructor
*
* A copy constructor is a member function which initializes an object using another object of the same class.
*/
Separator(const Separator& Source_);
/*! Private assignment operator
*
* The copy assignment operator is called whenever selected by overload resolution,
* e.g. when an object appears on the left side of an assignment expression.
*/
const Separator& operator= (const Separator& Source_);
/*! Array of Ascii field separator */
CHAR acMyASCIISeparatorSet[6];
/*! String of Ascii field separators */
CHAR* sMyASCIISeparators;
/*! string of Ascii filed set */
std::string strSeparatorSet;
};
#endif //SEPARATOR_H
| 34.862385 | 122 | 0.629737 | novatel |
c3c872072f41504807f429c006e910bd912f2276 | 7,574 | cpp | C++ | without_vtk.cpp | Harold2017/texture_mapping | c8aca1e9d30fd53e1f15be937aec2c53993bc371 | [
"MIT"
] | 1 | 2022-01-10T07:51:40.000Z | 2022-01-10T07:51:40.000Z | without_vtk.cpp | Harold2017/texture_mapping | c8aca1e9d30fd53e1f15be937aec2c53993bc371 | [
"MIT"
] | null | null | null | without_vtk.cpp | Harold2017/texture_mapping | c8aca1e9d30fd53e1f15be937aec2c53993bc371 | [
"MIT"
] | null | null | null | //
// Created by Harold on 2021/11/17.
//
#pragma warning(disable : 4996)
#pragma warning(disable : 4819)
#include <boost/filesystem.hpp>
#include <boost/thread/thread.hpp>
#include <pcl/common/transforms.h>
#include <pcl/features/normal_3d.h>
#include <pcl/io/obj_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/texture_mapping.h>
#include <pcl/common/io.h> // for concatenateFields
#include "stopwatch.h"
//#define DEBUG_PRINT
#include "read_cam_file_hololens2.h"
#define SAVE_CAM
#ifdef SAVE_CAM
// save camera pose lines for future plotting
void SaveCameraPoints(pcl::texture_mapping::Camera const& cam);
#endif
// argv[1]: input mesh file
// argv[2]: output obj file
// argv[3]: input texture.png / camera.txt folder
int main(int argc, char **argv)
{
pcl::PolygonMesh triangles;
{
TIME_BLOCK("- load mesh");
auto mesh_ext = boost::filesystem::extension(argv[1]);
if (mesh_ext == ".ply")
pcl::io::loadPLYFile(argv[1], triangles);
else if (mesh_ext == ".obj")
pcl::io::loadOBJFile(argv[1], triangles);
else
{
std::cerr << "only support .ply or .obj mesh file" << std::endl;
exit(0);
}
}
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(triangles.cloud, *cloud);
// Create the texturemesh object that will contain our UV-mapped mesh
pcl::TextureMesh mesh;
mesh.cloud = triangles.cloud;
std::vector<pcl::Vertices> polygon_1;
// push faces into the texturemesh object
{
TIME_BLOCK("- push faces into the texturemesh object");
polygon_1.resize(triangles.polygons.size());
for (size_t i = 0; i < triangles.polygons.size(); ++i)
{
polygon_1[i] = triangles.polygons[i];
}
mesh.tex_polygons.push_back(polygon_1);
}
const boost::filesystem::path base_dir(argv[3]);
// Load textures and cameras poses and intrinsics
pcl::texture_mapping::CameraVector my_cams;
{
TIME_BLOCK("- load textures and cameras poses and intrinsics");
std::string extension(".txt");
std::vector<boost::filesystem::path> filenames;
try
{
for (boost::filesystem::directory_iterator it(base_dir);
it != boost::filesystem::directory_iterator(); ++it)
{
if (boost::filesystem::is_regular_file(it->status()) &&
boost::filesystem::extension(it->path()) == extension)
{
filenames.push_back(it->path());
}
}
}
catch (const boost::filesystem::filesystem_error &e)
{
std::cerr << e.what() << std::endl;
}
std::sort(filenames.begin(), filenames.end());
for (int i = 0; i < filenames.size(); ++i)
{
std::cout << filenames[i].string() << std::endl;
pcl::TextureMapping<pcl::PointXYZ>::Camera cam;
read_cam_pose_file(filenames[i].string(), cam);
auto texture_path = filenames[i];
texture_path.replace_extension(".png");
if (boost::filesystem::exists(texture_path))
cam.texture_file = texture_path.string();
else
{
texture_path.replace_extension(".jpg");
if (boost::filesystem::exists(texture_path))
cam.texture_file = texture_path.string();
else
std::cerr << "no corresponding texture img for camera " << texture_path << std::endl;
}
my_cams.push_back(cam);
}
}
// Create materials for each texture (and one extra for occluded faces)
{
TIME_BLOCK("- create materials for each texture (and one extra for occluded faces)");
mesh.tex_materials.resize(my_cams.size() + 1);
for (int i = 0; i <= my_cams.size(); ++i)
{
pcl::TexMaterial mesh_material;
mesh_material.tex_Ka.r = 0.2f;
mesh_material.tex_Ka.g = 0.2f;
mesh_material.tex_Ka.b = 0.2f;
mesh_material.tex_Kd.r = 0.8f;
mesh_material.tex_Kd.g = 0.8f;
mesh_material.tex_Kd.b = 0.8f;
mesh_material.tex_Ks.r = 1.0f;
mesh_material.tex_Ks.g = 1.0f;
mesh_material.tex_Ks.b = 1.0f;
mesh_material.tex_d = 1.0f;
mesh_material.tex_Ns = 75.0f;
mesh_material.tex_illum = 2;
std::stringstream tex_name;
tex_name << "material_" << i;
tex_name >> mesh_material.tex_name;
if (i < my_cams.size())
{
mesh_material.tex_file = my_cams[i].texture_file;
#ifdef SAVE_CAM
SaveCameraPoints(my_cams[i]);
#endif
}
else
mesh_material.tex_file = (base_dir / boost::filesystem::path("occluded.jpg")).string();
mesh.tex_materials[i] = mesh_material;
}
}
std::cout << "polygon mesh size: " << mesh.tex_polygons.size() << ", material size: " << mesh.tex_materials.size() << ", texture coordinate size: " << mesh.tex_coordinates.size() << std::endl;
// FIXME: texture mapping works under release mode but not under debug mode
// Sort faces
{
TIME_BLOCK("- sort faces");
pcl::TextureMapping<pcl::PointXYZ> tm; // TextureMapping object that will perform the sort
tm.textureMeshwithMultipleCameras(mesh, my_cams);
}
for (std::size_t i = 0; i <= my_cams.size(); ++i)
{
PCL_INFO("\tSub mesh %zu contains %zu faces and %zu UV coordinates.\n", i, mesh.tex_polygons[i].size(), mesh.tex_coordinates[i].size());
}
// compute normals for the mesh
pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);
{
TIME_BLOCK("- compute normals");
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> n;
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud(cloud);
n.setInputCloud(cloud);
n.setSearchMethod(tree);
n.setKSearch(20);
n.compute(*normals);
}
// Concatenate XYZ and normal fields
pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals(new pcl::PointCloud<pcl::PointNormal>);
{
TIME_BLOCK("- concatenate xyz and normal fields");
pcl::concatenateFields(*cloud, *normals, *cloud_with_normals);
pcl::toPCLPointCloud2(*cloud_with_normals, mesh.cloud);
}
{
TIME_BLOCK("- save mesh");
pcl::io::saveOBJFile(argv[2], mesh, 5);
}
std::cout << "Done" << std::endl;
return 0;
}
#ifdef SAVE_CAM
void SaveCameraPoints(pcl::texture_mapping::Camera const& cam)
{
double focal_x = cam.focal_length_w;
double focal_y = cam.focal_length_h;
double height = cam.height;
double width = cam.width;
// create a 5-point visual for each camera
pcl::PointXYZ p1, p2, p3, p4, p5;
p1.x = 0;
p1.y = 0;
p1.z = 0;
double angleX = RAD2DEG(2.0 * atan(width / (2.0 * focal_x)));
double angleY = RAD2DEG(2.0 * atan(height / (2.0 * focal_y)));
double dist = 0.75;
double minX, minY, maxX, maxY;
maxX = dist * tan(atan(width / (2.0 * focal_x)));
minX = -maxX;
maxY = dist * tan(atan(height / (2.0 * focal_y)));
minY = -maxY;
p2.x = minX;
p2.y = minY;
p2.z = dist;
p3.x = maxX;
p3.y = minY;
p3.z = dist;
p4.x = maxX;
p4.y = maxY;
p4.z = dist;
p5.x = minX;
p5.y = maxY;
p5.z = dist;
p1 = pcl::transformPoint(p1, cam.pose);
p2 = pcl::transformPoint(p2, cam.pose);
p3 = pcl::transformPoint(p3, cam.pose);
p4 = pcl::transformPoint(p4, cam.pose);
p5 = pcl::transformPoint(p5, cam.pose);
auto camera_file = boost::filesystem::path(cam.texture_file).replace_extension(".cam").string();
std::ofstream ss(camera_file);
ss << p1 << p2 << '\n'
<< p1 << p3 << '\n'
<< p1 << p4 << '\n'
<< p1 << p5 << '\n'
<< p2 << p5 << '\n'
<< p5 << p4 << '\n'
<< p4 << p3 << '\n'
<< p3 << p2;
}
#endif
| 30.175299 | 194 | 0.632691 | Harold2017 |
c3cb58cdc2d1f73b3dd9d6d5ca786bdfef916b08 | 2,134 | hxx | C++ | main/vcl/inc/unx/salstd.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/vcl/inc/unx/salstd.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/vcl/inc/unx/salstd.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _SALSTD_HXX
#define _SALSTD_HXX
// -=-= includes -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include <tools/ref.hxx>
#include <tools/string.hxx>
#include <tools/gen.hxx>
#include <vcl/sv.h>
// -=-= X-Lib forwards -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef _SVUNX_H
typedef unsigned long Pixel;
typedef unsigned long XID;
typedef unsigned long XLIB_Time;
typedef unsigned long XtIntervalId;
typedef XID Colormap;
typedef XID Drawable;
typedef XID Pixmap;
typedef XID XLIB_Cursor;
typedef XID XLIB_Font;
typedef XID XLIB_Window;
typedef struct _XDisplay Display;
typedef struct _XGC *GC;
typedef struct _XImage XImage;
typedef struct _XRegion *XLIB_Region;
typedef union _XEvent XEvent;
typedef struct _XConfigureEvent XConfigureEvent;
typedef struct _XReparentEvent XReparentEvent;
typedef struct _XClientMessageEvent XClientMessageEvent;
typedef struct _XErrorEvent XErrorEvent;
struct Screen;
struct Visual;
struct XColormapEvent;
struct XFocusChangeEvent;
struct XFontStruct;
struct XKeyEvent;
struct XPropertyEvent;
struct XTextItem;
struct XWindowChanges;
#define None 0L
#endif
#endif
| 28.837838 | 79 | 0.676664 | Grosskopf |
c3cd2c2feb1535207804a141f2d25998822e240a | 993 | cpp | C++ | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut | aabedb5cb108513173951a5fc86ad589e7c8ccbc | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut | aabedb5cb108513173951a5fc86ad589e7c8ccbc | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.cpp | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-OMTut | aabedb5cb108513173951a5fc86ad589e7c8ccbc | [
"MIT"
] | null | null | null | #include "tic_tac_toe_manager.h"
TicTacToeManager::TicTacToeManager(TicTacToeData & data)
{
games = data.get_games();
for (auto& game : games)
{
update_winner_count(game->get_winner());
}
}
void TicTacToeManager::save_game(unique_ptr<TicTacToe> & game)
{
update_winner_count(game->get_winner());
games.push_back(std::move(game));
}
void TicTacToeManager::update_winner_count(string winner)
{
if (winner == "X") { x_win++; }
if (winner == "O") { o_win++; }
if (winner == "C") { ties++; }
}
void TicTacToeManager::get_winner_total(int & o, int & x, int & c)
{
x = x_win;
o = o_win;
c = ties;
}
TicTacToeManager::~TicTacToeManager()
{
data.save_games(games);
}
ostream & operator<<(ostream & out, const TicTacToeManager & manager)
{
for (auto &game : manager.games)
{
out << *game << "\n";
}
out << "\nX Win Count: " << manager.x_win << "\n";
out << "O Win Count: " << manager.o_win << "\n";
out << "Tie Count: " << manager.ties << "\n";
return out;
}
| 16.55 | 69 | 0.632427 | acc-cosc-1337-spring-2020 |
c3ce1e2623ad89e78d9d3b8d43b3f82b4a3530b8 | 1,809 | cpp | C++ | src/res/animation.cpp | crockeo/cpp-whatisthisgame | 90fe2f69f380635050aa746f280288aa0b7c5f54 | [
"MIT"
] | null | null | null | src/res/animation.cpp | crockeo/cpp-whatisthisgame | 90fe2f69f380635050aa746f280288aa0b7c5f54 | [
"MIT"
] | 1 | 2015-02-02T02:08:02.000Z | 2015-02-02T04:48:27.000Z | src/res/animation.cpp | crockeo/cpp-whatisthisgame | 90fe2f69f380635050aa746f280288aa0b7c5f54 | [
"MIT"
] | null | null | null | #include "animation.hpp"
//////////
// Code //
// Calculating the current frame index.
unsigned int Animation::calcCurrentFrameIndex() const {
int frame = this->timer->getTime() / frameLength;
if (frame >= this->textures.size())
return this->textures.size() - 1;
return frame;
}
// Creating a new animation with its frames, its frame length, and if it
// ought to loop.
Animation::Animation(std::vector<Texture> textures, float frameLength, bool doesLoop) {
this->textures = textures;
this->frameLength = frameLength;
this->isOriginal = true;
this->doesLoop = doesLoop;
if (this->doesLoop)
this->timer = std::make_shared<Timer>(this->textures.size() * this->frameLength);
else
this->timer = std::make_shared<Timer>();
}
// Creating a new animation with all of the above, assuming that it will
// want to loop.
Animation::Animation(std::vector<Texture> textures, float frameLength) :
Animation(textures, frameLength, true) { }
// Overriding the default copy constructor.
Animation::Animation(const Animation& anim) {
this->textures = anim.textures;
this->frameLength = anim.frameLength;
this->isOriginal = false;
this->doesLoop = anim.doesLoop;
this->timer = anim.timer;
}
// Getting the timer that exists
std::shared_ptr<Timer> Animation::getTimer() { return this->timer; }
// Getting the current frame of an animation.
Texture Animation::getCurrentFrame() const {
return this->textures.at(this->calcCurrentFrameIndex());
}
// Getting the current texture ID.
GLuint Animation::getID() const { return this->getCurrentFrame().getID(); }
// Getting the texture coordinates.
std::vector<GLfloat> Animation::getTextureCoords() const {
return this->getCurrentFrame().getTextureCoords();
}
| 31.736842 | 89 | 0.688778 | crockeo |
c3cf5d9e6bcddc9dd28be593bfab79b214d31f3a | 885 | cpp | C++ | src/LWM2MObject.cpp | Tanganelli/LWM2MEmbedded | 19a2c5d4edc84a0d91e388b5a789fda8e6142956 | [
"MIT"
] | 1 | 2018-04-03T14:58:12.000Z | 2018-04-03T14:58:12.000Z | src/LWM2MObject.cpp | Tanganelli/LWM2MEmbedded | 19a2c5d4edc84a0d91e388b5a789fda8e6142956 | [
"MIT"
] | 1 | 2017-03-21T14:58:16.000Z | 2017-03-23T12:28:09.000Z | src/LWM2MObject.cpp | Tanganelli/LWM2MEmbedded | 19a2c5d4edc84a0d91e388b5a789fda8e6142956 | [
"MIT"
] | null | null | null | //
// Created by jacko on 20/01/17.
//
#include "LWM2MObject.h"
char *LWM2MObject::getObjectName() const {
return ObjectName;
}
void LWM2MObject::setObjectName(char *ObjectName) {
LWM2MObject::ObjectName = ObjectName;
}
ObjectIDType LWM2MObject::getObjectID() const {
return ObjectID;
}
void LWM2MObject::setObjectID(ObjectIDType ObjectID) {
LWM2MObject::ObjectID = ObjectID;
}
const std::list<LWM2MResource> &LWM2MObject::getResources() const {
return Resources;
}
void LWM2MObject::setResources(const std::list<LWM2MResource> &Resources) {
LWM2MObject::Resources = Resources;
}
void *const *LWM2MObject::getHandlers() const {
return handlers;
}
const std::list<LWM2MObject> &LWM2MObject::getChildren() const {
return children;
}
void LWM2MObject::setChildren(const std::list<LWM2MObject> &children) {
LWM2MObject::children = children;
}
| 21.071429 | 75 | 0.728814 | Tanganelli |
c3d326ab78155934dfa9180a0789d3b8f2f6b7c6 | 1,139 | cpp | C++ | src/erhe/scene/viewport.cpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 36 | 2021-05-03T10:47:49.000Z | 2022-03-19T12:54:03.000Z | src/erhe/scene/viewport.cpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 29 | 2020-05-17T08:26:31.000Z | 2022-03-27T08:52:47.000Z | src/erhe/scene/viewport.cpp | tksuoran/erhe | 07d1ea014e1675f6b09bff0d9d4f3568f187e0d8 | [
"Apache-2.0"
] | 2 | 2022-01-24T09:24:37.000Z | 2022-01-31T20:45:36.000Z | #include "erhe/scene/viewport.hpp"
#include "erhe/scene/log.hpp"
#include "erhe/toolkit/math_util.hpp"
namespace erhe::scene
{
auto Viewport::unproject(
const glm::mat4 world_from_clip,
const glm::vec3 window,
const float depth_range_near,
const float depth_range_far
) const -> std::optional<glm::vec3>
{
return erhe::toolkit::unproject(
world_from_clip,
window,
depth_range_near,
depth_range_far,
static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(width),
static_cast<float>(height)
);
}
auto Viewport::project_to_screen_space(
const glm::mat4 clip_from_world,
const glm::vec3 position_in_world,
const float depth_range_near,
const float depth_range_far
) const -> glm::vec3
{
return erhe::toolkit::project_to_screen_space(
clip_from_world,
position_in_world,
depth_range_near,
depth_range_far,
static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(width),
static_cast<float>(height)
);
}
} // namespace erhe::scene
| 24.234043 | 50 | 0.653205 | tksuoran |
c3d4c33e716e4cdf985d257ad205ba50d2611cf5 | 14,473 | cxx | C++ | PROPOSAL/private/PROPOSAL/scattering/Coefficients.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 1 | 2020-12-24T22:00:01.000Z | 2020-12-24T22:00:01.000Z | PROPOSAL/private/PROPOSAL/scattering/Coefficients.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | null | null | null | PROPOSAL/private/PROPOSAL/scattering/Coefficients.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 3 | 2020-07-17T09:20:29.000Z | 2021-03-30T16:44:18.000Z |
#include "PROPOSAL/scattering/Coefficients.h"
//----------------------------------------------------------------------------//
//-----------------------------Coefficients-----------------------------------//
//---for calculating the power series approximation of the moliere function---//
//----------------------------------------------------------------------------//
const double PROPOSAL::c1[100] = {
0.01824498698928826, -1.054734960967865, 1.378945800806554, -0.8101747070430586,
0.3020799653590784, -0.08217510264333025, 0.01757489395499939, -0.003095373240445565,
0.0004633127963647091, -6.029130794154548e-05, 6.939349333147516e-06, -7.159829943698265e-07,
6.694120779750297e-08, -5.721860009237694e-09, 4.504494235551189e-10, -3.286570977596057e-11,
2.234424657611573e-12, -1.422140651267253e-13, 8.50844668823957e-15, -4.80239726059346e-16,
2.56544019782712e-17, -1.3008032373069e-18, 6.276721156927733e-20, -2.888980198088948e-21,
1.271082178072295e-22, -5.356321836042788e-24, 2.165708913690074e-25, -8.415665707369898e-27,
3.14768814769592e-28, -1.134804220079789e-29, 3.948607075433194e-31, -1.327667573801528e-32,
4.318678128634822e-34, -1.360474072770111e-35, 4.154710513947732e-37, -1.231145280289021e-38,
3.543063949967192e-40, -9.910855129282805e-42, 2.69678926347067e-43, -7.143475307428035e-45,
1.843336870282648e-46, -4.636847647068766e-48, 1.137731434272442e-49, -2.724695331159021e-51,
6.372463895718094e-53, -1.4562852800865e-54, 3.253589567012378e-56, -7.110068913054863e-58,
1.520504345733737e-59, -3.183490667084008e-61, 6.528486713873094e-63, -1.311890818170701e-64,
2.584252665251881e-66, -4.99221608462446e-68, 9.460964789499932e-70, -1.759614514252362e-71,
3.212849154606866e-73, -5.761014854313268e-75, 1.014807133464239e-76, -1.756624689658179e-78,
2.98893079441324e-80, -5.000577728087579e-82, 8.228369765510281e-84, -1.332031746609897e-85,
2.121957008008998e-87, -3.327287074593805e-89, 5.136681841644386e-91, -7.809396838908658e-93,
1.169486848348948e-94, -1.72549543381347e-96, 2.508809249655915e-98, -3.595413291827729e-100,
5.079801219388072e-102, -7.076983722567338e-104, 9.723837840810993e-106, -1.317945326279369e-107,
1.762410958111165e-109, -2.325652802263962e-111, 3.028909076825982e-113, -3.89408163088736e-115,
4.942802177984765e-117, -6.195278874139763e-119, 7.668956698453442e-121, -9.377048488608183e-123,
1.132701624601603e-124, -1.351910188741138e-126, 1.594502032991125e-128, -1.858693324663112e-130,
2.141681719707223e-132, -2.43963241933955e-134, 2.747720630653711e-136, -3.060234006823078e-138,
3.370734378882746e-140, -3.672273506135163e-142, 3.957653085865992e-144, -4.219715312480803e-146,
4.451647266046611e-148, -4.647280664772496e-150, 4.80136823945151e-152, -4.909819238915968e-154
};
const double PROPOSAL::c2[100] = {
0.3692951315189029, -2.901210618562379, 4.763691522462663, -3.668389620520657,
1.743233030563621, -0.5857757559172652, 0.1507057475725596, -0.03124919421553912,
0.005411101880491738, -0.0008029915660482544, 0.0001041435915389889, -1.198693445962836e-05,
1.239576100587234e-06, -1.163301889847139e-07, 9.990755927592503e-09, -7.907851249726336e-10,
5.803579436334176e-11, -3.969886777147483e-12, 2.542633424164171e-13, -1.530925400639093e-14,
8.696260972023862e-16, -4.675164455450479e-17, 2.385523336370255e-18, -1.158267999875986e-19,
5.363958217246529e-21, -2.374296161332396e-22, 1.006470730715194e-23, -4.093159567679296e-25,
1.5996354171463e-26, -6.016551229383919e-28, 2.180970406636743e-29, -7.629492110705818e-31,
2.578781877602269e-32, -8.431429670892704e-34, 2.669429048218415e-35, -8.192196123057652e-37,
2.439244055889828e-38, -7.052895752459682e-40, 1.98198110121125e-41, -5.417437723374357e-43,
1.441367960601787e-44, -3.735506587014256e-46, 9.436466002585026e-48, -2.325045788414374e-49,
5.590871105668466e-51, -1.312817566476688e-52, 3.011935532920134e-54, -6.755103130065185e-56,
1.481773486168858e-57, -3.180564595352823e-59, 6.683429378680969e-61, -1.375495310358957e-62,
2.773751380431616e-64, -5.482786499876722e-66, 1.062748090934042e-67, -2.020774364918115e-69,
3.770691103605001e-71, -6.907025753601122e-73, 1.242436024375922e-74, -2.195383992072398e-76,
3.811853327900785e-78, -6.505522184103775e-80, 1.091628995757091e-81, -1.801512577182476e-83,
2.924740086946532e-85, -4.672395489277705e-87, 7.346918415137358e-89, -1.137343481536269e-90,
1.733816262095051e-92, -2.603397903194606e-94, 3.851253561734265e-96, -5.61413579760181e-98,
8.066318236042616e-100, -1.142534156297296e-101, 1.595701569049596e-103, -2.197898380015261e-105,
2.986204180183809e-107, -4.002834291275826e-109, 5.294562476317114e-111, -6.911669661645124e-113,
8.906363201403711e-115, -1.133064328971227e-116, 1.423363576915385e-118, -1.765846157643044e-120,
2.163876866238606e-122, -2.619510733347758e-124, 3.133137855471063e-126, -3.703162047314654e-128,
4.325741534530339e-130, -4.994619251572251e-132, 5.701067045150251e-134, -6.433962204999298e-136,
7.180006537985007e-138, -7.924088243222738e-140, 8.649775953179418e-142, -9.339923463142228e-144,
9.977353925282273e-146, -1.054558462375476e-147, 1.102954869090941e-149, -1.141626881676896e-151
};
const double PROPOSAL::c2large[50] = { 0,
0,
5.317361552716548,
39.88021164537411,
279.1614815176188,
2093.711111382141,
17273.11666890266,
157185.3616870142,
1571853.616870142,
17178114.5272237,
203990110.0107814,
2617873078.471694,
36126648482.90939,
533689125315.7068,
8405603723722.382,
140632216146893.7,
2491199257459260,
4.658542611448816e+16,
9.171505766289856e+17,
1.896343692265226e+19,
4.108744666574657e+20,
9.309550415580998e+21,
2.201708673284906e+23,
5.425639230594947e+24,
1.390936602752523e+26,
3.704124648634435e+27,
1.023264434185263e+29,
2.928582810638222e+30,
8.673110631505504e+31,
2.65493553219974e+33,
8.39149266427418e+34,
2.735915970369392e+36,
9.192677660441157e+37,
3.180369932523594e+39,
1.132012922857617e+41,
4.142138195001734e+42,
1.55695665094477e+44,
6.007628448859746e+45,
2.378019594340316e+47,
9.65026059703239e+48,
4.012476774555574e+50,
1.708389149781931e+52,
7.444305720174763e+53,
3.318163098443751e+55,
1.512134326290795e+57,
7.041974391621668e+58,
3.349739182196398e+60,
1.626856662820051e+62,
8.063550415716772e+63,
4.077239907010832e+65 };
const double PROPOSAL::s2large[50] = { 0,
0,
-0.3515783203226215,
-0.5515783203226214,
-0.6944354631797642,
-0.8055465742908754,
-0.8964556651999662,
-0.9733787421230431,
-1.04004540878971,
-1.098868938201474,
-1.151500517148843,
-1.19911956476789,
-1.242597825637456,
-1.282597825637456,
-1.319634862674493,
-1.354117621295182,
-1.386375685811311,
-1.416678716114342,
-1.44525014468577,
-1.472277171712797,
-1.497918197353823,
-1.522308441256262,
-1.54556425520975,
-1.567786477431973,
-1.589063073176654,
-1.609471236441959,
-1.629079079579214,
-1.647947004107516,
-1.666128822289334,
-1.683672681938457,
-1.70062183448083,
-1.717015277103781,
-1.732888292976797,
-1.748272908361412,
-1.76319828149574,
-1.777691035118929,
-1.791775542161182,
-1.805474172298168,
-1.818807505631502,
-1.831794518618515,
-1.844452746466616,
-1.856798425478962,
-1.868846618250046,
-1.880611324132399,
-1.892105577005962,
-1.903341532062142,
-1.914330543051153,
-1.925083231223196,
-1.93560954701267,
-1.945918825363185 };
const double PROPOSAL::C1large[50] = { 0,
-0.443113462726379,
-0.6646701940895685,
-1.661675485223921,
-5.815864198283724,
-26.17138889227676,
-143.9426389075222,
-935.6271528988941,
-7017.203646741706,
-59646.2309973045,
-566639.1944743927,
-5949711.541981123,
-68421682.73278293,
-855271034.1597866,
-11546158961.15712,
-167419304936.7782,
-2594999226520.062,
-42817487237581.03,
-749306026657668,
-1.386216149316686e+16,
-2.703121491167537e+17,
-5.541399056893451e+18,
-1.191400797232092e+20,
-2.680651793772207e+21,
-6.299531715364686e+22,
-1.543385270264348e+24,
-3.935632439174088e+25,
-1.042942596381133e+27,
-2.868092140048117e+28,
-8.174062599137132e+29,
-2.411348466745454e+31,
-7.354612823573634e+32,
-2.316703039425695e+34,
-7.529284878133508e+35,
-2.522310434174725e+37,
-8.701970997902803e+38,
-3.089199704255495e+40,
-1.127557892053256e+42,
-4.228342095199709e+43,
-1.627911706651888e+45,
-6.430251241274957e+46,
-2.604251752716358e+48,
-1.080764477377288e+50,
-4.593249028853476e+51,
-1.998063327551262e+53,
-8.891381807603116e+54,
-4.045578722459418e+56,
-1.881194105943629e+58,
-8.935672003232238e+59,
-4.333800921567636e+61 };
| 66.695853 | 101 | 0.453396 | hschwane |
c3d5eccc073a19a5adb856e00c78d3e4d7a410af | 8,567 | cpp | C++ | LMS7002M/lms7suite/controlPanelGUI/fft/PlotUpdateThread.cpp | myriadrf/lms-suite | 41c3e7e40a76d2520478e9f57bcd01d904907425 | [
"Apache-2.0"
] | 14 | 2015-01-16T17:01:05.000Z | 2020-10-31T17:52:53.000Z | LMS7002M/lms7suite/controlPanelGUI/fft/PlotUpdateThread.cpp | serojik91/lms-suite | 41c3e7e40a76d2520478e9f57bcd01d904907425 | [
"Apache-2.0"
] | null | null | null | LMS7002M/lms7suite/controlPanelGUI/fft/PlotUpdateThread.cpp | serojik91/lms-suite | 41c3e7e40a76d2520478e9f57bcd01d904907425 | [
"Apache-2.0"
] | 12 | 2015-02-01T23:32:31.000Z | 2021-01-09T16:34:51.000Z | /**
@file PlotUpdateThread.cpp
@author Lime Microsystems
@brief Class for updating fft data plots
*/
#include "PlotUpdateThread.h"
#include <stdio.h>
#include "pnlFFTviewer.h"
#include "CommonUtilities.h"
#include "SamplesCollector.h"
#include <vector>
#include <wx/time.h>
using namespace std;
const int CHANNEL_COUNT = 2;
PlotUpdateThread::PlotUpdateThread(pnlFFTviewer* mainFrame) : wxThread(wxTHREAD_JOINABLE)
{
m_mainframe = mainFrame;
m_running = false;
m_FFTsize = 0;
m_samplingFreq = 1000;
}
PlotUpdateThread::~PlotUpdateThread()
{
}
/** @brief Plots drawing procedure
*/
void* PlotUpdateThread::Entry()
{
float *amplitudes = new float[m_FFTsize];
FFTPacket *results = new FFTPacket(2*m_FFTsize);
memset(results->iqsamples, 0, sizeof(float)*results->samplesCount);
memset(results->amplitudes, 0, sizeof(float)*results->amplitudesCount);
float *ftempI = new float[m_FFTsize];
float *ftempQ = new float[m_FFTsize];
memset(ftempI, 0, sizeof(float)*m_FFTsize);
memset(ftempQ, 0, sizeof(float)*m_FFTsize);
m_running = true;
vector<float> timeVector;
timeVector.reserve(m_FFTsize);
for(int i=0; i<m_FFTsize; ++i)
{
timeVector.push_back(i);
}
vector<float> freqVector;
freqVector.resize(m_FFTsize);
for(int i=0; i<m_FFTsize; ++i)
{
float freq = i*(m_samplingFreq/m_FFTsize);
int output_index = i+m_FFTsize/2-1;
if(output_index >= m_FFTsize)
{
output_index -= m_FFTsize;
freq -= m_samplingFreq;
}
freqVector[output_index] = freq;
}
long t1, t2;
t2 = t1 = getMilis();
long minUpdateIntervalMs = 30;
long t1measure, t2measure;
t1measure = t2measure = getMilis();
int ch = 0;
//reset plots to default data
for(int i = 0; i<CHANNEL_COUNT; ++i)
{
wxCriticalSectionLocker lock(m_mainframe->m_dataCS);
m_mainframe->m_gltimePlot->series[2*i+0]->AssignValues(&timeVector[0], ftempI, m_FFTsize);
m_mainframe->m_gltimePlot->series[2*i+1]->AssignValues(&timeVector[0], ftempQ, m_FFTsize);
m_mainframe->m_glconstellationPlot->series[i]->AssignValues(results->iqsamples, results->samplesCount);
m_mainframe->m_glFFTplot->series[i]->AssignValues(&freqVector[0], results->amplitudes, results->amplitudesCount-1);
m_mainframe->m_glFFTplot->Refresh();
m_mainframe->m_gltimePlot->Refresh();
m_mainframe->m_glconstellationPlot->Refresh();
}
CalculationResults measurements;
while(m_running)
{
t2 = getMilis();
if(t2 - t1 >= minUpdateIntervalMs)
{
t2measure = t2;
bool updateMeasurements = false;
if(t2measure-t1measure > 500)
{
updateMeasurements = true;
t1measure = t2measure;
}
t1 = t2;
memset(amplitudes, 0, sizeof(float)*m_FFTsize);
bool newData = m_mainframe->m_fftOutputs->pop_front(results, 100);
if( newData == true)
{
ch = results->channel;
int i=0;
int j=0;
while(i<results->samplesCount)
{
ftempI[j] = results->iqsamples[i];
++i;
ftempQ[j] = results->iqsamples[i];
++i;
++j;
}
}
if(newData)
{
wxCriticalSectionLocker lock(m_mainframe->m_dataCS);
if(m_mainframe->chkFreezeIQtime->IsChecked() == false)
{
if(updateMeasurements)
{
float sumI = 0;
float sumQ = 0;
for(int i=0; i<m_FFTsize; ++i)
{
sumI += ftempI[i];
sumQ += ftempQ[i];
}
float meanI = sumI/m_FFTsize;
float meanQ = sumQ/m_FFTsize;
float tempMag = 0;
float averageMag = 0;
float peakMag = sqrt((ftempI[0] - meanI)*(ftempI[0] - meanI) + (ftempQ[0] - meanQ)*(ftempQ[0] - meanQ));
for(int i=0; i<m_FFTsize; ++i)
{
tempMag = sqrt((ftempI[i] - meanI)*(ftempI[i] - meanI) + (ftempQ[i] - meanQ)*(ftempQ[i] - meanQ));
averageMag += tempMag*tempMag;
if (tempMag > peakMag)
peakMag = tempMag;
}
averageMag = sqrt(averageMag/m_FFTsize);
if (averageMag != 0)
{
measurements.iqPeakToAvgRatio = 20 * log10(peakMag / averageMag);
}
else
measurements.iqPeakToAvgRatio = 0;
}
m_mainframe->m_gltimePlot->series[2*ch+0]->AssignValues(&timeVector[0], ftempI, m_FFTsize);
m_mainframe->m_gltimePlot->series[2*ch+1]->AssignValues(&timeVector[0], ftempQ, m_FFTsize);
}
if(m_mainframe->chkFreezeIversusQ->IsChecked() == false)
{
m_mainframe->m_glconstellationPlot->series[ch]->AssignValues(results->iqsamples, results->samplesCount);
}
if(m_mainframe->chkFreezeDrawing->IsChecked() == false)
{
if(updateMeasurements)
{
float chPwr[2];
double cFreq[2] = {0, 2000000};
m_mainframe->txtCFreq1->GetValue().ToDouble(&cFreq[0]);
cFreq[0] *= 1000000;
m_mainframe->txtCFreq2->GetValue().ToDouble(&cFreq[1]);
cFreq[1] *= 1000000;
double bw[2] = {2000000, 3000000};
m_mainframe->txtBW1->GetValue().ToDouble(&bw[0]);
bw[0] *= 1000000;
m_mainframe->txtBW2->GetValue().ToDouble(&bw[1]);
bw[1] *= 1000000;
char ctemp[512];
for(int c=0; c<2; ++c)
{
float f0 = cFreq[c]-bw[c]/2;
float fn = cFreq[c]+bw[c]/2;
float sum = 0;
int bins = 0;
for(int i=0; i<results->amplitudesCount; ++i)
if(f0 <= freqVector[i] && freqVector[i] <= fn)
{
sum += pow(10, results->amplitudes_dbFS[i]/10);
++bins;
}
chPwr[c] = sum;
}
measurements.pwrCh1 = 10*log10(chPwr[0]);
measurements.pwrCh2 = 10*log10(chPwr[1]);
measurements.dbc = 10*log10(chPwr[1]/chPwr[0]);
}
m_mainframe->m_glFFTplot->series[ch]->AssignValues(&freqVector[0], results->amplitudes_dbFS, results->amplitudesCount);
}
m_mainframe->m_redrawsDone++;
wxThreadEvent tevt(wxEVT_THREAD, wxEVT_COMMAND_THREAD_UPDATE);
tevt.SetPayload<CalculationResults>(measurements);
m_mainframe->GetEventHandler()->AddPendingEvent(tevt); //post event for gui thread to update
}
else
{
wxThreadEvent tevt(wxEVT_THREAD, wxEVT_COMMAND_THREAD_UPDATE);
tevt.SetPayload<CalculationResults>(measurements);
m_mainframe->GetEventHandler()->AddPendingEvent(tevt); //post event for gui thread to update
}
}
else
milSleep(minUpdateIntervalMs-(t2-t1));
}
delete []ftempI;
delete []ftempQ;
delete results;
delete []amplitudes;
printf("plot thread stopped\n");
return 0;
}
/** @brief Stops plot updating
*/
void PlotUpdateThread::Stop()
{
m_running = false;
Wait();
}
/**
*/
bool PlotUpdateThread::SetFFTsize(int size)
{
if(m_running)
return false;
m_FFTsize = size;
return true;
}
/** @brief Sets sampling frequency for display
@param freq sampling frequency in Hz
*/
bool PlotUpdateThread::SetSamplingFrequency(double freq)
{
m_samplingFreq = freq;
return true;
}
| 34.967347 | 159 | 0.514883 | myriadrf |
c3daccd7cb4ce0df04859e39032c133934ccc4d2 | 77,794 | cpp | C++ | src/vm/vm8051.cpp | koalajack/koalachain | 84b5d5351072947f79f982ca24666047e955df3d | [
"MIT"
] | null | null | null | src/vm/vm8051.cpp | koalajack/koalachain | 84b5d5351072947f79f982ca24666047e955df3d | [
"MIT"
] | null | null | null | src/vm/vm8051.cpp | koalajack/koalachain | 84b5d5351072947f79f982ca24666047e955df3d | [
"MIT"
] | null | null | null | // ComDirver.cpp: implementation of the CComDirver class.
//
//////////////////////////////////////////////////////////////////////
#include "vm8051.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "hash.h"
#include "key.h"
#include "main.h"
#include <openssl/des.h>
#include <vector>
#include "vmrunevn.h"
#include "tx.h"
//#include "Typedef.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
void CVm8051::InitalReg() {
memset(m_ChipRam, 0, sizeof(m_ChipRam));
memset(m_ChipSfr, 0, sizeof(m_ChipSfr));
memset(m_ExRam, 0, sizeof(m_ExRam));
memset(m_ExeFile, 0, sizeof(m_ExeFile));
Sys.a.SetAddr(a_addr);
Sys.b.SetAddr(b_addr);
Sys.dptr.SetAddr(dptrl);
Sys.psw.SetAddr(psw_addr);
Sys.sp.SetAddr(sp_addr);
Rges.R0.SetAddr(0x00);
Rges.R1.SetAddr(0x01);
Rges.R2.SetAddr(0x02);
Rges.R3.SetAddr(0x03);
Rges.R4.SetAddr(0x04);
Rges.R5.SetAddr(0x05);
Rges.R6.SetAddr(0x06);
Rges.R7.SetAddr(0x07);
SetRamData(0x80, 0xFF);
SetRamData(0x90, 0xFF);
SetRamData(0xa0, 0xFF);
SetRamData(0xb0, 0xFF);
Sys.sp = 0x07;
}
CVm8051::CVm8051(const vector<unsigned char> & vRom, const vector<unsigned char> &InputData) :
Sys(this), Rges(this) {
InitalReg();
//INT16U addr = 0xFC00;
memcpy(m_ExeFile, &vRom[0], vRom.size());
unsigned char *ipara = (unsigned char *) GetExRamAddr(VM_SHARE_ADDR);
int count = InputData.size();
memcpy(ipara, &count, 2);
memcpy(&ipara[2], &InputData[0],count);
}
CVm8051::~CVm8051() {
}
typedef tuple<int,int64_t,std::shared_ptr < std::vector< vector<unsigned char> > > > RET_DEFINE;
typedef tuple<int,int64_t,std::shared_ptr < std::vector< vector<unsigned char> > > > (*pFun)(unsigned char *,void *);
struct __MapExterFun {
INT16U method;
pFun fun;
};
static bool GetKeyId(const CAccountViewCache &view, vector<unsigned char> &ret,
CKeyID &KeyId) {
if (ret.size() == 6) {
CRegID reg(ret);
KeyId = reg.getKeyID(view);
} else if (ret.size() == 34) {
string addr(ret.begin(), ret.end());
KeyId = CKeyID(addr);
}else{
return false;
}
if (KeyId.IsEmpty())
return false;
return true;
}
static inline RET_DEFINE RetFalse(const string reason )
{
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
return std::make_tuple (false,0, tem);
}
static unsigned short GetParaLen(unsigned char * &pbuf) {
unsigned short ret = 0;
memcpy(&ret, pbuf, 2);
pbuf += 2;
return ret;
}
static bool GetData(unsigned char * ipara, vector<std::shared_ptr < std::vector<unsigned char> > > &ret) {
int totallen = GetParaLen(ipara);
//assert(totallen >= 0);
if(totallen <= 0)
{
return false;
}
if(totallen>= CVm8051::MAX_SHARE_RAM)
{
LogPrint("vm","%s\r\n","data over flaw");
return false;
}
while (totallen > 0) {
unsigned short length = GetParaLen(ipara);
if ((length <= 0) || (length + 2 > totallen)) {
LogPrint("vm","%s\r\n","data over flaw");
return false;
}
totallen -= (length + 2);
ret.insert(ret.end(),std::make_shared<vector<unsigned char>>(ipara, ipara + length));
ipara += length;
}
return true;
}
static RET_DEFINE ExInt64CompFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) || retdata.size() != 2||
retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int64_t m1, m2;
unsigned char rslt;
memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1));
memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2));
if (m1 > m2) {
rslt = 2;
} else if (m1 == m2) {
rslt = 0;
} else {
rslt = 1;
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << rslt;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExInt64MullFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2||
retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int64_t m1, m2, m3;
memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1));
memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2));
m3 = m1 * m2;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << m3;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExInt64AddFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2||
retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int64_t m1, m2, m3;
memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1));
memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2));
m3 = m1 + m2;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << m3;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExInt64SubFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2||
retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int64_t m1, m2, m3;
memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1));
memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2));
m3 = m1 - m2;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << m3;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExInt64DivFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2||
retdata.at(0).get()->size() != sizeof(int64_t)||retdata.at(1).get()->size() != sizeof(int64_t))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int64_t m1, m2, m3;
memcpy(&m1, &retdata.at(0).get()->at(0), sizeof(m1));
memcpy(&m2, &retdata.at(1).get()->at(0), sizeof(m2));
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if( m2 == 0)
{
return std::make_tuple (false,0, tem);
}
m3 = m1 / m2;
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << m3;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExSha256Func(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
uint256 rslt = Hash(&retdata.at(0).get()->at(0), &retdata.at(0).get()->at(0) + retdata.at(0).get()->size());
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << rslt;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExDesFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 3)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
DES_key_schedule deskey1, deskey2, deskey3;
vector<unsigned char> desdata;
vector<unsigned char> desout;
unsigned char datalen_rest = retdata.at(0).get()->size() % sizeof(DES_cblock);
desdata.assign(retdata.at(0).get()->begin(), retdata.at(0).get()->end());
if (datalen_rest) {
desdata.insert(desdata.end(), sizeof(DES_cblock) - datalen_rest, 0);
}
const_DES_cblock in;
DES_cblock out, key;
desout.resize(desdata.size());
unsigned char flag = retdata.at(2).get()->at(0);
if (flag == 1) {
if (retdata.at(1).get()->size() == 8) {
// printf("the des encrypt\r\n");
memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock));
DES_set_key_unchecked(&key, &deskey1);
for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) {
memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in));
// printf("in :%s\r\n", HexStr(in, in + 8, true).c_str());
DES_ecb_encrypt(&in, &out, &deskey1, DES_ENCRYPT);
// printf("out :%s\r\n", HexStr(out, out + 8, true).c_str());
memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out));
}
}
else if(retdata.at(1).get()->size() == 16)
{
// printf("the 3 des encrypt\r\n");
memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock));
DES_set_key_unchecked(&key, &deskey1);
DES_set_key_unchecked(&key, &deskey3);
memcpy(key, &retdata.at(1).get()->at(0) + sizeof(DES_cblock), sizeof(DES_cblock));
DES_set_key_unchecked(&key, &deskey2);
for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) {
memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in));
DES_ecb3_encrypt(&in, &out, &deskey1, &deskey2, &deskey3, DES_ENCRYPT);
memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out));
}
}
else
{
//error
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
return std::make_tuple (false,0, tem);
}
} else {
if (retdata.at(1).get()->size() == 8) {
// printf("the des decrypt\r\n");
memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock));
DES_set_key_unchecked(&key, &deskey1);
for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) {
memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in));
// printf("in :%s\r\n", HexStr(in, in + 8, true).c_str());
DES_ecb_encrypt(&in, &out, &deskey1, DES_DECRYPT);
// printf("out :%s\r\n", HexStr(out, out + 8, true).c_str());
memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out));
}
}
else if(retdata.at(1).get()->size() == 16)
{
// printf("the 3 des decrypt\r\n");
memcpy(key, &retdata.at(1).get()->at(0), sizeof(DES_cblock));
DES_set_key_unchecked(&key, &deskey1);
DES_set_key_unchecked(&key, &deskey3);
memcpy(key, &retdata.at(1).get()->at(0) + sizeof(DES_cblock), sizeof(DES_cblock));
DES_set_key_unchecked(&key, &deskey2);
for (unsigned int ii = 0; ii < desdata.size() / sizeof(DES_cblock); ii++) {
memcpy(&in, &desdata[ii * sizeof(DES_cblock)], sizeof(in));
DES_ecb3_encrypt(&in, &out, &deskey1, &deskey2, &deskey3, DES_DECRYPT);
memcpy(&desout[ii * sizeof(DES_cblock)], &out, sizeof(out));
}
}
else
{
//error
return RetFalse(string(__FUNCTION__)+"para err !");
}
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
(*tem.get()).push_back(desout);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExVerifySignatureFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 3||
retdata.at(1).get()->size() != 33||
retdata.at(2).get()->size() !=32)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CPubKey pk(retdata.at(1).get()->begin(), retdata.at(1).get()->end());
uint256 hash(*retdata.at(2).get());
auto tem = std::make_shared<std::vector<vector<unsigned char> > >();
bool rlt = CheckSignScript(hash, *retdata.at(0), pk);
if (!rlt) {
LogPrint("INFO", "ExVerifySignatureFunc call CheckSignScript verify signature failed!\n");
return std::make_tuple(false, 0, tem);
}
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << rlt;
vector<unsigned char> tep1(tep.begin(), tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple(true, 0, tem);
}
static RET_DEFINE ExSignatureFunc(unsigned char *ipara,void * pVmScriptRun) {
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExLogPrintFunc(unsigned char *ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CDataStream tep1(*retdata.at(0), SER_DISK, CLIENT_VERSION);
bool flag ;
tep1 >> flag;
string pdata((*retdata[1]).begin(), (*retdata[1]).end());
if(flag)
{
LogPrint("vm","%s\r\n", HexStr(pdata).c_str());
// LogPrint("INFO","%s\r\n", HexStr(pdata).c_str());
}else
{
LogPrint("vm","%s\r\n",pdata.c_str());
// LogPrint("INFO","%s\r\n",pdata.c_str());
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
return std::make_tuple (true, 0,tem);
}
static RET_DEFINE ExGetTxContractsFunc(unsigned char * ipara,void * pVmScriptRun) {
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != 32)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
uint256 hash1(*retdata.at(0));
// LogPrint("vm","ExGetTxContractsFunc1:%s\n",hash1.GetHex().c_str());
bool flag = false;
std::shared_ptr<CBaseTransaction> pBaseTx;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if (GetTransaction(pBaseTx, hash1, *pVmScript->GetScriptDB(), false)) {
CTransaction *tx = static_cast<CTransaction*>(pBaseTx.get());
(*tem.get()).push_back(tx->vContract);
flag = true;
}
return std::make_tuple (flag, 0,tem);
}
static RET_DEFINE ExGetTxAccountsFunc(unsigned char * ipara, void * pVmScriptRun) {
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun;
vector<std::shared_ptr<vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1|| retdata.at(0).get()->size() != 32)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CDataStream tep1(*retdata.at(0), SER_DISK, CLIENT_VERSION);
uint256 hash1;
tep1 >>hash1;
// LogPrint("vm","ExGetTxAccountsFunc:%s",hash1.GetHex().c_str());
bool flag = false;
std::shared_ptr<CBaseTransaction> pBaseTx;
auto tem = std::make_shared<std::vector<vector<unsigned char> > >();
if (GetTransaction(pBaseTx, hash1, *pVmScript->GetScriptDB(), false)) {
CTransaction *tx = static_cast<CTransaction*>(pBaseTx.get());
vector<unsigned char> item = boost::get<CRegID>(tx->srcRegId).GetVec6();
(*tem.get()).push_back(item);
flag = true;
}
return std::make_tuple(flag,0, tem);
}
static RET_DEFINE ExGetAccountPublickeyFunc(unsigned char * ipara,void * pVmScriptRun) {
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1
|| !(retdata.at(0).get()->size() == 6 || retdata.at(0).get()->size() == 34))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CKeyID addrKeyId;
if (!GetKeyId(*(pVmScript->GetCatchView()),*retdata.at(0).get(), addrKeyId)) {
return RetFalse(string(__FUNCTION__)+"para err !");
}
CUserID userid(addrKeyId);
CAccount aAccount;
if (!pVmScript->GetCatchView()->GetAccount(userid, aAccount)) {
return RetFalse(string(__FUNCTION__)+"GetAccount err !");
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
vector<char> te;
tep << aAccount.PublicKey;
assert(aAccount.PublicKey.IsFullyValid());
tep >>te;
vector<unsigned char> tep1(te.begin(),te.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExQueryAccountBalanceFunc(unsigned char * ipara,void * pVmScriptRun) {
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1
|| !(retdata.at(0).get()->size() == 6 || retdata.at(0).get()->size() == 34))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
bool flag = true;
CKeyID addrKeyId;
if (!GetKeyId(*pVmScript->GetCatchView(),*retdata.at(0).get(), addrKeyId)) {
return RetFalse(string(__FUNCTION__)+"para err !");
}
CUserID userid(addrKeyId);
CAccount aAccount;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if (!pVmScript->GetCatchView()->GetAccount(userid, aAccount)) {
flag = false;
}
else
{
uint64_t nbalance = aAccount.GetRawBalance();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << nbalance;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
}
return std::make_tuple (flag ,0, tem);
}
static RET_DEFINE ExGetTxConFirmHeightFunc(unsigned char * ipara,void * pVmScriptRun) {
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1|| retdata.at(0).get()->size() != 32)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
uint256 hash1(*retdata.at(0));
// LogPrint("vm","ExGetTxContractsFunc1:%s",hash1.GetHex().c_str());
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
int nHeight = GetTxComfirmHigh(hash1, *pVmScript->GetScriptDB());
if(-1 == nHeight)
{
return std::make_tuple (false,0, tem);
}
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << nHeight;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExGetBlockHashFunc(unsigned char * ipara,void * pVmScriptRun) {
vector<std::shared_ptr < vector<unsigned char> > > retdata;
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmScriptRun;
if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != sizeof(int))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int height = 0;
memcpy(&height, &retdata.at(0).get()->at(0), sizeof(int));
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if (height <= 0 || height >= pVmScript->GetComfirHeight())
{
return std::make_tuple (false,0, tem);
}
if(chainActive.Height() < height){
return std::make_tuple (false, 0,tem);
}
CBlockIndex *pindex = chainActive[height];
uint256 blockHash = pindex->GetBlockHash();
// LogPrint("vm","ExGetBlockHashFunc:%s",HexStr(blockHash).c_str());
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << blockHash;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExGetCurRunEnvHeightFunc(unsigned char * ipara,void * pVmEvn) {
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
int height = pVmRunEvn->GetComfirHeight();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << height;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExWriteDataDBFunc(unsigned char * ipara,void * pVmEvn) {
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
const CRegID scriptid = pVmRunEvn->GetScriptRegID();
bool flag = true;
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
CScriptDBOperLog operlog;
int64_t step = (*retdata.at(1)).size() -1;
if (!scriptDB->SetScriptData(scriptid, *retdata.at(0), *retdata.at(1),operlog)) {
flag = false;
} else {
shared_ptr<vector<CScriptDBOperLog> > m_dblog = pVmRunEvn->GetDbLog();
(*m_dblog.get()).push_back(operlog);
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << flag;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,step, tem);
}
static RET_DEFINE ExDeleteDataDBFunc(unsigned char * ipara,void * pVmEvn) {
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1)
{
LogPrint("vm", "GetData return error!\n");
return RetFalse(string(__FUNCTION__)+"para err !");
}
CRegID scriptid = pVmRunEvn->GetScriptRegID();
bool flag = true;
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
CScriptDBOperLog operlog;
int64_t nstep = 0;
vector<unsigned char> vValue;
if(scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid, *retdata.at(0), vValue)){
nstep = nstep - (int64_t)(vValue.size()+1);
}
if (!scriptDB->EraseScriptData(scriptid, *retdata.at(0), operlog)) {
LogPrint("vm", "ExDeleteDataDBFunc error key:%s!\n",HexStr(*retdata.at(0)));
flag = false;
} else {
shared_ptr<vector<CScriptDBOperLog> > m_dblog = pVmRunEvn->GetDbLog();
m_dblog.get()->push_back(operlog);
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << flag;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,nstep, tem);
}
static RET_DEFINE ExReadDataValueDBFunc(unsigned char * ipara,void * pVmEvn) {
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CRegID scriptid = pVmRunEvn->GetScriptRegID();
vector_unsigned_char vValue;
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
bool flag =true;
// LogPrint("INFO", "script run read data:%s\n", HexStr(*retdata.at(0)));
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if(!scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid, *retdata.at(0), vValue))
{
flag = false;
}
else
{
(*tem.get()).push_back(vValue);
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE ExGetDBSizeFunc(unsigned char * ipara,void * pVmEvn) {
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
CRegID scriptid = pVmRunEvn->GetScriptRegID();
int count = 0;
bool flag = true;
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if(!scriptDB->GetScriptDataCount(scriptid,count))
{
flag = false;
}
else
{
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << count;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE ExGetDBValueFunc(unsigned char * ipara,void * pVmEvn) {
if (SysCfg().GetArg("-isdbtraversal", 0) == 0) {
LogPrint("INFO","%s","ExGetDBValueFunc can't use\n");
return RetFalse(string(__FUNCTION__)+"para err !");
}
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||(retdata.size() != 2 && retdata.size() != 1))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
int index = 0;
bool flag = true;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
memcpy(&index,&retdata.at(0).get()->at(0),sizeof(int));
if(!(index == 0 ||(index == 1 && retdata.size() == 2)))
{
flag = false;
return std::make_tuple (flag,0, tem);
}
CRegID scriptid = pVmRunEvn->GetScriptRegID();
vector_unsigned_char vValue;
vector<unsigned char> vScriptKey;
if(index == 1)
{
vScriptKey.assign(retdata.at(1).get()->begin(),retdata.at(1).get()->end());
}
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
flag = scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid,index,vScriptKey,vValue);
if(flag){
LogPrint("vm", "Read key:%s,value:%s!\n",HexStr(vScriptKey),HexStr(vValue));
(*tem.get()).push_back(vScriptKey);
(*tem.get()).push_back(vValue);
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE ExGetCurTxHash(unsigned char * ipara,void * pVmEvn) {
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
uint256 hash = pVmRunEvn->GetCurTxHash();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << hash;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
// LogPrint("vm","ExGetCurTxHash:%s",HexStr(hash).c_str());
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExModifyDataDBVavleFunc(unsigned char * ipara,void * pVmEvn)
{
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2 )
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CRegID scriptid = pVmRunEvn->GetScriptRegID();
vector_unsigned_char vValue;
bool flag = false;
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
int64_t step = 0;
CScriptDBOperLog operlog;
vector_unsigned_char vTemp;
if(scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(),scriptid, *retdata.at(0), vTemp)) {
if(scriptDB->SetScriptData(scriptid,*retdata.at(0),*retdata.at(1).get(),operlog))
{
shared_ptr<vector<CScriptDBOperLog> > m_dblog = pVmRunEvn->GetDbLog();
m_dblog.get()->push_back(operlog);
flag = true;
}
}
step =(((int64_t)(*retdata.at(1)).size())- (int64_t)(vTemp.size()) -1);
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << flag;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (flag ,step, tem);
}
static RET_DEFINE ExWriteOutputFunc(unsigned char * ipara,void * pVmEvn)
{
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1 )
{
return RetFalse("para err");
}
vector<CVmOperate> source;
CVmOperate temp;
int Size = ::GetSerializeSize(temp, SER_NETWORK, PROTOCOL_VERSION);
int datadsize = retdata.at(0)->size();
int count = datadsize/Size;
if(datadsize%Size != 0)
{
// assert(0);
return RetFalse("para err");
}
CDataStream ss(*retdata.at(0),SER_DISK, CLIENT_VERSION);
while(count--)
{
ss >> temp;
source.push_back(temp);
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if(!pVmRunEvn->InsertOutputData(source)) {
// return RetFalse("InsertOutput err");
return std::make_tuple (-1 ,0, tem);
}
return std::make_tuple (true ,0, tem);
}
static RET_DEFINE ExGetScriptDataFunc(unsigned char * ipara,void * pVmEvn)
{
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2 || retdata.at(0).get()->size() != 6)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
vector_unsigned_char vValue;
bool flag =true;
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
CScriptDBViewCache* scriptDB = pVmRunEvn->GetScriptDB();
CRegID scriptid(*retdata.at(0));
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if(!scriptDB->GetScriptData(pVmRunEvn->GetComfirHeight(), scriptid, *retdata.at(1), vValue))
{
flag = false;
}
else
{
(*tem.get()).push_back(vValue);
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE ExGetScriptIDFunc(unsigned char * ipara,void * pVmEvn)
{
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector_unsigned_char scriptid = pVmRunEvn->GetScriptRegID().GetVec6();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
(*tem.get()).push_back(scriptid);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExGetCurTxAccountFunc(unsigned char * ipara,void * pVmEvn)
{
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector_unsigned_char vUserId =pVmRunEvn->GetTxAccount().GetVec6();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
(*tem.get()).push_back(vUserId);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExGetCurTxContactFunc(unsigned char * ipara, void *pVmEvn)
{
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<unsigned char> contact =pVmRunEvn->GetTxContact();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
(*tem.get()).push_back(contact);
return std::make_tuple (true,0, tem);
}
enum COMPRESS_TYPE {
U16_TYPE = 0, // U16_TYPE
I16_TYPE = 1, // I16_TYPE
U32_TYPE = 2, // U32_TYPE
I32_TYPE = 3, // I32_TYPE
U64_TYPE = 4, // U64_TYPE
I64_TYPE = 5, // I64_TYPE
NO_TYPE = 6, // NO_TYPE +n (tip char)
};
static bool Decompress(vector<unsigned char>& format,vector<unsigned char> &contact,std::vector<unsigned char> &ret){
try {
CDataStream ds(contact,SER_DISK, CLIENT_VERSION);
CDataStream retdata(SER_DISK, CLIENT_VERSION);
for (auto item = format.begin(); item != format.end();item++) {
switch(*item) {
case U16_TYPE: {
unsigned short i = 0;
ds >> VARINT(i);
retdata<<i;
break;
}
case I16_TYPE:
{
short i = 0;
ds >> VARINT(i);
retdata<<i;
break;
}
case U32_TYPE:
{
short i = 0;
ds >> VARINT(i);
retdata<<i;
break;
}
case I32_TYPE:
{
unsigned int i = 0;
ds >> VARINT(i);
retdata<<i;
break;
}
case U64_TYPE:
{
uint64_t i = 0;
ds >> VARINT(i);
retdata<<i;
break;
}
case I64_TYPE:
{
int64_t i = 0;
ds >> VARINT(i);
retdata<<i;
break;
}
case NO_TYPE:
{
unsigned char temp = 0;
item++;
int te = *item;
while (te--) {
ds >> VARINT(temp);
retdata<<temp;
}
break;
}
default:
{
return ERRORMSG("%s\r\n",__FUNCTION__);
}
}
}
ret.insert(ret.begin(),retdata.begin(),retdata.end());
} catch (...) {
LogPrint("vm","seseril err in funciton:%s",__FUNCTION__);
return false;
}
return true;
}
static RET_DEFINE ExCurDeCompressContactFunc(unsigned char *ipara,void *pVmEvn){
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1 )
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
vector<unsigned char> contact =((CVmRunEvn *)pVmEvn)->GetTxContact();
std::vector<unsigned char> outContact;
if(!Decompress(*retdata.at(0),contact,outContact))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
(*tem.get()).push_back(outContact);
return std::make_tuple (true,0, tem);
}
static RET_DEFINE ExDeCompressContactFunc(unsigned char *ipara,void *pVmEvn){
CVmRunEvn *pVmScript = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 2 || retdata.at(1).get()->size() != 32)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
uint256 hash1(*retdata.at(1));
// LogPrint("vm","ExGetTxContractsFunc1:%s\n",hash1.GetHex().c_str());
bool flag = false;
std::shared_ptr<CBaseTransaction> pBaseTx;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if (GetTransaction(pBaseTx, hash1, *pVmScript->GetScriptDB(), false)) {
CTransaction *tx = static_cast<CTransaction*>(pBaseTx.get());
std::vector<unsigned char> outContact;
if (!Decompress(*retdata.at(0), tx->vContract, outContact)) {
return RetFalse(string(__FUNCTION__) + "para err !");
}
(*tem.get()).push_back(outContact);
flag = true;
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE GetCurTxPayAmountFunc(unsigned char *ipara,void *pVmEvn){
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
uint64_t lvalue =pVmRunEvn->GetValue();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << lvalue;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
return std::make_tuple (true,0, tem);
}
struct S_APP_ID
{
unsigned char idlen; //!the len of the tag
unsigned char ID[CAppCFund::MAX_TAG_SIZE]; //! the ID for the
const vector<unsigned char> GetIdV() const {
assert(sizeof(ID) >= idlen);
vector<unsigned char> Id(&ID[0], &ID[idlen]);
return (Id);
}
}__attribute((aligned (1)));
static RET_DEFINE GetUserAppAccValue(unsigned char * ipara,void * pVmScript){
CVmRunEvn *pVmScriptRun = (CVmRunEvn *)pVmScript;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1
|| retdata.at(0).get()->size() != sizeof(S_APP_ID))
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
S_APP_ID accid;
memcpy(&accid, &retdata.at(0).get()->at(0), sizeof(S_APP_ID));
bool flag = false;
shared_ptr<CAppUserAccout> sptrAcc;
uint64_t value = 0 ;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
if(pVmScriptRun->GetAppUserAccout(accid.GetIdV(),sptrAcc))
{
value = sptrAcc->getllValues();
// cout<<"read:"<<endl;
// cout<<sptrAcc->toString()<<endl;
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << value;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
flag = true;
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE GetUserAppAccFoudWithTag(unsigned char * ipara,void * pVmScript){
CVmRunEvn *pVmScriptRun = (CVmRunEvn *)pVmScript;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
unsigned int Size(0);
CAppFundOperate temp;
Size = ::GetSerializeSize(temp, SER_NETWORK, PROTOCOL_VERSION);
if(!GetData(ipara,retdata) ||retdata.size() != 1
|| retdata.at(0).get()->size() !=Size)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CDataStream ss(*retdata.at(0),SER_DISK, CLIENT_VERSION);
CAppFundOperate userfund;
ss>>userfund;
shared_ptr<CAppUserAccout> sptrAcc;
bool flag = false;
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
CAppCFund fund;
if(pVmScriptRun->GetAppUserAccout(userfund.GetAppUserV(),sptrAcc))
{
if(!sptrAcc->GetAppCFund(fund,userfund.GetFundTagV(),userfund.outheight)) {
return RetFalse(string(__FUNCTION__)+"tag err !");
}
CDataStream tep(SER_DISK, CLIENT_VERSION);
tep << fund.getvalue() ;
vector<unsigned char> tep1(tep.begin(),tep.end());
(*tem.get()).push_back(tep1);
flag = true;
}
return std::make_tuple (flag,0, tem);
}
static RET_DEFINE ExWriteOutAppOperateFunc(unsigned char * ipara,void * pVmEvn)
{
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
CAppFundOperate temp;
unsigned int Size = ::GetSerializeSize(temp, SER_NETWORK, PROTOCOL_VERSION);
if(!GetData(ipara,retdata) ||retdata.size() != 1 || (retdata.at(0).get()->size()%Size) != 0 )
{
return RetFalse("para err");
}
int count = retdata.at(0).get()->size()/Size;
CDataStream ss(*retdata.at(0),SER_DISK, CLIENT_VERSION);
int64_t step =-1;
while(count--)
{
ss >> temp;
if(temp.mMoney < 0)
{
return RetFalse("para err");
}
pVmRunEvn->InsertOutAPPOperte(temp.GetAppUserV(),temp);
step +=Size;
}
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
return std::make_tuple (true ,step, tem);
}
static RET_DEFINE ExGetBase58AddrFunc(unsigned char * ipara,void * pVmEvn){
CVmRunEvn *pVmRunEvn = (CVmRunEvn *)pVmEvn;
vector<std::shared_ptr < vector<unsigned char> > > retdata;
if(!GetData(ipara,retdata) ||retdata.size() != 1 || retdata.at(0).get()->size() != 6)
{
return RetFalse(string(__FUNCTION__)+"para err !");
}
CKeyID addrKeyId;
if (!GetKeyId(*pVmRunEvn->GetCatchView(),*retdata.at(0).get(), addrKeyId)) {
return RetFalse(string(__FUNCTION__)+"para err !");
}
string addr = addrKeyId.ToAddress();
auto tem = std::make_shared<std::vector< vector<unsigned char> > >();
vector<unsigned char> vTemp;
vTemp.assign(addr.c_str(),addr.c_str()+addr.length());
(*tem.get()).push_back(vTemp);
return std::make_tuple (true,0, tem);
}
enum CALL_API_FUN {
COMP_FUNC = 0, //!< COMP_FUNC
MULL_MONEY, //!< MULL_MONEY
ADD_MONEY, //!< ADD_MONEY
SUB_MONEY, //!< SUB_MONEY
DIV_MONEY, //!< DIV_MONEY
SHA256_FUNC, //!< SHA256_FUNC
DES_FUNC, //!< DES_FUNC
VERFIY_SIGNATURE_FUNC, //!< VERFIY_SIGNATURE_FUNC
SIGNATURE_FUNC, //!< SIGNATURE_FUNC
PRINT_FUNC, //!< PRINT_FUNC
GETTX_CONTRACT_FUNC, //!< GETTX_CONTRACT_FUNC
GETTX_ACCOUNT_FUNC, //!< GETTX_ACCOUNT_FUNC
GETACCPUB_FUNC, //!< GETACCPUB_FUNC
QUEYACCBALANCE_FUNC, //!< QUEYACCBALANCE_FUNC
GETTXCONFIRH_FUNC, //!< GETTXCONFIRH_FUNC
GETBLOCKHASH_FUNC, //!< GETBLOCKHASH_FUNC
//// tx api
GETCTXCONFIRMH_FUNC, //!< GETCTXCONFIRMH_FUNC
WRITEDB_FUNC, //!< WRITEDB_FUNC
DELETEDB_FUNC, //!< DELETEDB_FUNC
READDB_FUNC, //!< READDB_FUNC
GETDBSIZE_FUNC, //!< GETDBSIZE_FUNC
GETDBVALUE_FUNC, //!< GETDBVALUE_FUNC
GetCURTXHASH_FUNC, //!< GetCURTXHASH_FUNC
MODIFYDBVALUE_FUNC, //!< MODIFYDBVALUE_FUNC
WRITEOUTPUT_FUNC, //!<WRITEOUTPUT_FUNC
GETSCRIPTDATA_FUNC, //!<GETSCRIPTDATA_FUNC
GETSCRIPTID_FUNC, //!<GETSCRIPTID_FUNC
GETCURTXACCOUNT_FUNC, //!<GETCURTXACCOUNT_FUNC
GETCURTXCONTACT_FUNC, //!<GETCURTXCONTACT_FUNC
GETCURDECOMPRESSCONTACR_FUNC, //!<GETCURDECOMPRESSCONTACR_FUNC
GETDECOMPRESSCONTACR_FUNC, //!<GETDECOMPRESSCONTACR_FUNC
GETCURPAYMONEY_FUN, //!<GETCURPAYMONEY_FUN
GET_APP_USER_ACC_VALUE_FUN, //!<GET_APP_USER_ACC_FUN
GET_APP_USER_ACC_FUND_WITH_TAG_FUN, //!<GET_APP_USER_ACC_FUND_WITH_TAG_FUN
GET_WIRITE_OUT_APP_OPERATE_FUN, //!<GET_WIRITE_OUT_APP_OPERATE_FUN
GET_KOALA_ADDRESS_FUN,
};
const static string API_METOHD[] =
{
"COMP_FUNC",
"MULL_MONEY",
"ADD_MONEY",
"SUB_MONEY",
"DIV_MONEY",
"SHA256_FUNC",
"DES_FUNC",
"VERFIY_SIGNATURE_FUNC",
"SIGNATURE_FUNC",
"PRINT_FUNC",
"GETTX_CONTRACT_FUNC",
"GETTX_ACCOUNT_FUNC",
"GETACCPUB_FUNC",
"QUEYACCBALANCE_FUNC",
"GETTXCONFIRH_FUNC",
"GETBLOCKHASH_FUNC",
"GETCTXCONFIRMH_FUNC",
"WRITEDB_FUNC",
"DELETEDB_FUNC",
"READDB_FUNC",
"GETDBSIZE_FUNC",
"GETDBVALUE_FUNC",
"GetCURTXHASH_FUNC",
"MODIFYDBVALUE_FUNC",
"WRITEOUTPUT_FUNC",
"GETSCRIPTDATA_FUNC",
"GETSCRIPTID_FUNC",
"GETCURTXACCOUNT_FUNC",
"GETCURTXCONTACT_FUNC",
"GETCURDECOMPRESSCONTACR_FUNC",
"GETDECOMPRESSCONTACR_FUNC",
"GETCURPAYMONEY_FUN",
"GET_APP_USER_ACC_VALUE_FUN",
"GET_APP_USER_ACC_FUND_WITH_TAG_FUN",
"GET_WIRITE_OUT_APP_OPERATE_FUN",
"GET_KOALA_ADDRESS_FUN" };
const static struct __MapExterFun FunMap[] = { //
{ COMP_FUNC, ExInt64CompFunc }, //
{ MULL_MONEY, ExInt64MullFunc }, //
{ ADD_MONEY, ExInt64AddFunc }, //
{ SUB_MONEY, ExInt64SubFunc }, //
{ DIV_MONEY, ExInt64DivFunc }, //
{ SHA256_FUNC, ExSha256Func }, //
{ DES_FUNC, ExDesFunc }, //
{ VERFIY_SIGNATURE_FUNC, ExVerifySignatureFunc }, //
{ SIGNATURE_FUNC, ExSignatureFunc }, //
{ PRINT_FUNC, ExLogPrintFunc }, //
{GETTX_CONTRACT_FUNC,ExGetTxContractsFunc}, //
{GETTX_ACCOUNT_FUNC,ExGetTxAccountsFunc},
{GETACCPUB_FUNC,ExGetAccountPublickeyFunc},
{QUEYACCBALANCE_FUNC,ExQueryAccountBalanceFunc},
{GETTXCONFIRH_FUNC,ExGetTxConFirmHeightFunc},
{GETBLOCKHASH_FUNC,ExGetBlockHashFunc},
{GETCTXCONFIRMH_FUNC,ExGetCurRunEnvHeightFunc},
{WRITEDB_FUNC,ExWriteDataDBFunc},
{DELETEDB_FUNC,ExDeleteDataDBFunc},
{READDB_FUNC,ExReadDataValueDBFunc},
{GETDBSIZE_FUNC,ExGetDBSizeFunc},
{GETDBVALUE_FUNC,ExGetDBValueFunc},
{GetCURTXHASH_FUNC,ExGetCurTxHash},
{MODIFYDBVALUE_FUNC,ExModifyDataDBVavleFunc},
{WRITEOUTPUT_FUNC,ExWriteOutputFunc},
{GETSCRIPTDATA_FUNC,ExGetScriptDataFunc},
{GETSCRIPTID_FUNC,ExGetScriptIDFunc},
{GETCURTXACCOUNT_FUNC,ExGetCurTxAccountFunc },
{GETCURTXCONTACT_FUNC,ExGetCurTxContactFunc },
{GETCURDECOMPRESSCONTACR_FUNC,ExCurDeCompressContactFunc },
{GETDECOMPRESSCONTACR_FUNC,ExDeCompressContactFunc },
{GETCURPAYMONEY_FUN,GetCurTxPayAmountFunc},
{GET_APP_USER_ACC_VALUE_FUN,GetUserAppAccValue},
{GET_APP_USER_ACC_FUND_WITH_TAG_FUN,GetUserAppAccFoudWithTag},
{GET_WIRITE_OUT_APP_OPERATE_FUN,ExWriteOutAppOperateFunc},
{GET_KOALA_ADDRESS_FUN,ExGetBase58AddrFunc},
};
RET_DEFINE CallExternalFunc(INT16U method, unsigned char *ipara,CVmRunEvn *pVmEvn) {
return FunMap[method].fun(ipara, pVmEvn);
}
int64_t CVm8051::run(uint64_t maxstep, CVmRunEvn *pVmEvn) {
INT8U code = 0;
int64_t step = 0; //uint64_t
if((maxstep == 0) || (NULL == pVmEvn)){
return -1;
}
while (1) {
code = GetOpcode();
StepRun(code);
step++;
//call func out of 8051
if (Sys.PC == 0x0012) {
//get what func will be called
INT16U methodID = ((INT16U) GetExRam(VM_FUN_CALL_ADDR) | ((INT16U) GetExRam(VM_FUN_CALL_ADDR+1) << 8));
unsigned char *ipara = (unsigned char *) GetExRamAddr(VM_SHARE_ADDR); //input para
RET_DEFINE retdata = CallExternalFunc(methodID, ipara, pVmEvn);
memset(ipara, 0, MAX_SHARE_RAM);
step += std::get<1>(retdata) - 1;
if (std::get<0>(retdata) == 1) {
auto tem = std::get<2>(retdata);
int pos = 0;
int totalsize = 0;
for (auto& it : *tem.get()) {
totalsize += it.size() + 2;
}
if (totalsize + 2 < MAX_SHARE_RAM) { //if data not over
for (auto& it : *tem.get()) {
int size = it.size();
memcpy(&ipara[pos], &size, 2);
memcpy(&ipara[pos + 2], &it.at(0), size);
pos += size + 2;
}
}
}
else if(std::get<0>(retdata) == -1){
LogPrint("CONTRACT_TX", "call method id:%d methodName:%s\n", methodID, API_METOHD[methodID]);
return -1;
}
else
{
}
} else if (Sys.PC == 0x0008) {
INT8U result = GetExRam(0xEFFD);
if (result == 0x01) {
return step;
}
return 0;
}
if (step >= (int64_t)MAX_BLOCK_RUN_STEP || step >= (int64_t)maxstep){
LogPrint("CONTRACT_TX", "failed step:%ld\n", step);
return -1; //force return
}
}
return 1;
}
bool CVm8051::run() {
INT8U code = 0;
// INT16U flag;
while (1) {
code = GetOpcode();
StepRun(code);
// UpDataDebugInfo();
//call func out of 8051
if (Sys.PC == 0x0012) {
//get what func will be called
INT16U method = ((INT16U) GetExRam(VM_FUN_CALL_ADDR) | ((INT16U) GetExRam(VM_FUN_CALL_ADDR+1) << 8));
// flag = method;
unsigned char *ipara = (unsigned char *) GetExRamAddr(VM_SHARE_ADDR); //input para
CVmRunEvn *pVmScript = NULL;
RET_DEFINE retdata = CallExternalFunc(method, ipara, pVmScript);
//memset(ipara, 0, MAX_SHARE_RAM);
memset(ipara, 0, 8);
if (std::get<0>(retdata)) {
auto tem = std::get<2>(retdata);
int pos = 0;
int totalsize = 0;
for (auto& it : *tem.get()) {
totalsize += it.size() + 2;
}
if (totalsize + 2 < MAX_SHARE_RAM) {
for (auto& it : *tem.get()) {
int size = it.size();
memcpy(&ipara[pos], &size, 2);
memcpy(&ipara[pos + 2], &it.at(0), size);
pos += size + 2;
}
}
}
}else if (Sys.PC == 0x0008) {
INT8U result=GetExRam(0xEFFD);
if(result == 0x01)
{
return 1;
}
return 0;
}
}
return 1;
}
void CVm8051::SetExRamData(INT16U addr, const vector<unsigned char> data) {
memcpy(&m_ExRam[addr], &data[0], data.size());
}
void CVm8051::StepRun(INT8U code) {
switch (code) {
case 0x00: {
Opcode_00_NOP();
break;
}
case 0x01: {
Opcode_01_AJMP_Addr11();
break;
}
case 0x02: {
Opcode_02_LJMP_Addr16();
break;
}
case 0x03: {
Opcode_03_RR_A();
break;
}
case 0x04: {
Opcode_04_INC_A();
break;
}
case 0x05: {
Opcode_05_INC_Direct();
break;
}
case 0x06: {
Opcode_06_INC_R0_1();
break;
}
case 0x07: {
Opcode_07_INC_R1_1();
break;
}
case 0x08: {
Opcode_08_INC_R0();
break;
}
case 0x09: {
Opcode_09_INC_R1();
break;
}
case 0x0A: {
Opcode_0A_INC_R2();
break;
}
case 0x0B: {
Opcode_0B_INC_R3();
break;
}
case 0x0C: {
Opcode_0C_INC_R4();
break;
}
case 0x0D: {
Opcode_0D_INC_R5();
break;
}
case 0x0E: {
Opcode_0E_INC_R6();
break;
}
case 0x0F: {
Opcode_0F_INC_R7();
break;
}
case 0x10: {
Opcode_10_JBC_Bit_Rel();
break;
}
case 0x11: {
Opcode_11_ACALL_Addr11();
break;
}
case 0x12: {
Opcode_12_LCALL_Addr16();
break;
}
case 0x13: {
Opcode_13_RRC_A();
break;
}
case 0x14: {
Opcode_14_DEC_A();
break;
}
case 0x15: {
Opcode_15_DEC_Direct();
break;
}
case 0x16: {
Opcode_16_DEC_R0_1();
break;
}
case 0x17: {
Opcode_17_DEC_R1_1();
break;
}
case 0x18: {
Opcode_18_DEC_R0();
break;
}
case 0x19: {
Opcode_19_DEC_R1();
break;
}
case 0x1A: {
Opcode_1A_DEC_R2();
break;
}
case 0x1B: {
Opcode_1B_DEC_R3();
break;
}
case 0x1C: {
Opcode_1C_DEC_R4();
break;
}
case 0x1D: {
Opcode_1D_DEC_R5();
break;
}
case 0x1E: {
Opcode_1E_DEC_R6();
break;
}
case 0x1F: {
Opcode_1F_DEC_R7();
break;
}
case 0x20: {
Opcode_20_JB_Bit_Rel();
break;
}
case 0x21: {
Opcode_21_AJMP_Addr11();
break;
}
case 0x22: {
Opcode_22_RET();
break;
}
case 0x23: {
Opcode_23_RL_A();
break;
}
case 0x24: {
Opcode_24_ADD_A_Data();
break;
}
case 0x25: {
Opcode_25_ADD_A_Direct();
break;
}
case 0x26: {
Opcode_26_ADD_A_R0_1();
break;
}
case 0x27: {
Opcode_27_ADD_A_R1_1();
break;
}
case 0x28: {
Opcode_28_ADD_A_R0();
break;
}
case 0x29: {
Opcode_29_ADD_A_R1();
break;
}
case 0x2A: {
Opcode_2A_ADD_A_R2();
break;
}
case 0x2B: {
Opcode_2B_ADD_A_R3();
break;
}
case 0x2C: {
Opcode_2C_ADD_A_R4();
break;
}
case 0x2D: {
Opcode_2D_ADD_A_R5();
break;
}
case 0x2E: {
Opcode_2E_ADD_A_R6();
break;
}
case 0x2F: {
Opcode_2F_ADD_A_R7();
break;
}
case 0x30: {
Opcode_30_JNB_Bit_Rel();
break;
}
case 0x31: {
Opcode_31_ACALL_Addr11();
break;
}
case 0x32: {
Opcode_32_RETI();
break;
}
case 0x33: {
Opcode_33_RLC_A();
break;
}
case 0x34: {
Opcode_34_ADDC_A_Data();
break;
}
case 0x35: {
Opcode_35_ADDC_A_Direct();
break;
}
case 0x36: {
Opcode_36_ADDC_A_R0_1();
break;
}
case 0x37: {
Opcode_37_ADDC_A_R1_1();
break;
}
case 0x38: {
Opcode_38_ADDC_A_R0();
break;
}
case 0x39: {
Opcode_39_ADDC_A_R1();
break;
}
case 0x3A: {
Opcode_3A_ADDC_A_R2();
break;
}
case 0x3B: {
Opcode_3B_ADDC_A_R3();
break;
}
case 0x3C: {
Opcode_3C_ADDC_A_R4();
break;
}
case 0x3D: {
Opcode_3D_ADDC_A_R5();
break;
}
case 0x3E: {
Opcode_3E_ADDC_A_R6();
break;
}
case 0x3F: {
Opcode_3F_ADDC_A_R7();
break;
}
case 0x40: {
Opcode_40_JC_Rel();
break;
}
case 0x41: {
Opcode_41_AJMP_Addr11();
break;
}
case 0x42: {
Opcode_42_ORL_Direct_A();
break;
}
case 0x43: {
Opcode_43_ORL_Direct_Data();
break;
}
case 0x44: {
Opcode_44_ORL_A_Data();
break;
}
case 0x45: {
Opcode_45_ORL_A_Direct();
break;
}
case 0x46: {
Opcode_46_ORL_A_R0_1();
break;
}
case 0x47: {
Opcode_47_ORL_A_R1_1();
break;
}
case 0x48: {
Opcode_48_ORL_A_R0();
break;
}
case 0x49: {
Opcode_49_ORL_A_R1();
break;
}
case 0x4A: {
Opcode_4A_ORL_A_R2();
break;
}
case 0x4B: {
Opcode_4B_ORL_A_R3();
break;
}
case 0x4C: {
Opcode_4C_ORL_A_R4();
break;
}
case 0x4D: {
Opcode_4D_ORL_A_R5();
break;
}
case 0x4E: {
Opcode_4E_ORL_A_R6();
break;
}
case 0x4F: {
Opcode_4F_ORL_A_R7();
break;
}
case 0x50: {
Opcode_50_JNC_Rel();
break;
}
case 0x51: {
Opcode_51_ACALL_Addr11();
break;
}
case 0x52: {
Opcode_52_ANL_Direct_A();
break;
}
case 0x53: {
Opcode_53_ANL_Direct_Data();
break;
}
case 0x54: {
Opcode_54_ANL_A_Data();
break;
}
case 0x55: {
Opcode_55_ANL_A_Direct();
break;
}
case 0x56: {
Opcode_56_ANL_A_R0_1();
break;
}
case 0x57: {
Opcode_57_ANL_A_R1_1();
break;
}
case 0x58: {
Opcode_58_ANL_A_R0();
break;
}
case 0x59: {
Opcode_59_ANL_A_R1();
break;
}
case 0x5A: {
Opcode_5A_ANL_A_R2();
break;
}
case 0x5B: {
Opcode_5B_ANL_A_R3();
break;
}
case 0x5C: {
Opcode_5C_ANL_A_R4();
break;
}
case 0x5D: {
Opcode_5D_ANL_A_R5();
break;
}
case 0x5E: {
Opcode_5E_ANL_A_R6();
break;
}
case 0x5F: {
Opcode_5F_ANL_A_R7();
break;
}
case 0x60: {
Opcode_60_JZ_Rel();
break;
}
case 0x61: {
Opcode_61_AJMP_Addr11();
break;
}
case 0x62: {
Opcode_62_XRL_Direct_A();
break;
}
case 0x63: {
Opcode_63_XRL_Direct_Data();
break;
}
case 0x64: {
Opcode_64_XRL_A_Data();
break;
}
case 0x65: {
Opcode_65_XRL_A_Direct();
break;
}
case 0x66: {
Opcode_66_XRL_A_R0_1();
break;
}
case 0x67: {
Opcode_67_XRL_A_R1_1();
break;
}
case 0x68: {
Opcode_68_XRL_A_R0();
break;
}
case 0x69: {
Opcode_69_XRL_A_R1();
break;
}
case 0x6A: {
Opcode_6A_XRL_A_R2();
break;
}
case 0x6B: {
Opcode_6B_XRL_A_R3();
break;
}
case 0x6C: {
Opcode_6C_XRL_A_R4();
break;
}
case 0x6D: {
Opcode_6D_XRL_A_R5();
break;
}
case 0x6E: {
Opcode_6E_XRL_A_R6();
break;
}
case 0x6F: {
Opcode_6F_XRL_A_R7();
break;
}
case 0x70: {
Opcode_70_JNZ_Rel();
break;
}
case 0x71: {
Opcode_71_ACALL_Addr11();
break;
}
case 0x72: {
Opcode_72_ORL_C_Direct();
break;
}
case 0x73: {
Opcode_73_JMP_A_DPTR();
break;
}
case 0x74: {
Opcode_74_MOV_A_Data();
break;
}
case 0x75: {
Opcode_75_MOV_Direct_Data();
break;
}
case 0x76: {
Opcode_76_MOV_R0_1_Data();
break;
}
case 0x77: {
Opcode_77_MOV_R1_1_Data();
break;
}
case 0x78: {
Opcode_78_MOV_R0_Data();
break;
}
case 0x79: {
Opcode_79_MOV_R1_Data();
break;
}
case 0x7A: {
Opcode_7A_MOV_R2_Data();
break;
}
case 0x7B: {
Opcode_7B_MOV_R3_Data();
break;
}
case 0x7C: {
Opcode_7C_MOV_R4_Data();
break;
}
case 0x7D: {
Opcode_7D_MOV_R5_Data();
break;
}
case 0x7E: {
Opcode_7E_MOV_R6_Data();
break;
}
case 0x7F: {
Opcode_7F_MOV_R7_Data();
break;
}
case 0x80: {
Opcode_80_SJMP_Rel();
break;
}
case 0x81: {
Opcode_81_AJMP_Addr11();
break;
}
case 0x82: {
Opcode_82_ANL_C_Bit();
break;
}
case 0x83: {
Opcode_83_MOVC_A_PC();
break;
}
case 0x84: {
Opcode_84_DIV_AB();
break;
}
case 0x85: {
Opcode_85_MOV_Direct_Direct();
break;
}
case 0x86: {
Opcode_86_MOV_Direct_R0_1();
break;
}
case 0x87: {
Opcode_87_MOV_Direct_R1_1();
break;
}
case 0x88: {
Opcode_88_MOV_Direct_R0();
break;
}
case 0x89: {
Opcode_89_MOV_Direct_R1();
break;
}
case 0x8A: {
Opcode_8A_MOV_Direct_R2();
break;
}
case 0x8B: {
Opcode_8B_MOV_Direct_R3();
break;
}
case 0x8C: {
Opcode_8C_MOV_Direct_R4();
break;
}
case 0x8D: {
Opcode_8D_MOV_Direct_R5();
break;
}
case 0x8E: {
Opcode_8E_MOV_Direct_R6();
break;
}
case 0x8F: {
Opcode_8F_MOV_Direct_R7();
break;
}
case 0x90: {
Opcode_90_MOV_DPTR_Data();
break;
}
case 0x91: {
Opcode_91_ACALL_Addr11();
break;
}
case 0x92: {
Opcode_92_MOV_Bit_C();
break;
}
case 0x93: {
Opcode_93_MOVC_A_DPTR();
break;
}
case 0x94: {
Opcode_94_SUBB_A_Data();
break;
}
case 0x95: {
Opcode_95_SUBB_A_Direct();
break;
}
case 0x96: {
Opcode_96_SUBB_A_R0_1();
break;
}
case 0x97: {
Opcode_97_SUBB_A_R1_1();
break;
}
case 0x98: {
Opcode_98_SUBB_A_R0();
break;
}
case 0x99: {
Opcode_99_SUBB_A_R1();
break;
}
case 0x9A: {
Opcode_9A_SUBB_A_R2();
break;
}
case 0x9B: {
Opcode_9B_SUBB_A_R3();
break;
}
case 0x9C: {
Opcode_9C_SUBB_A_R4();
break;
}
case 0x9D: {
Opcode_9D_SUBB_A_R5();
break;
}
case 0x9E: {
Opcode_9E_SUBB_A_R6();
break;
}
case 0x9F: {
Opcode_9F_SUBB_A_R7();
break;
}
case 0xA0: {
Opcode_A0_ORL_C_Bit();
break;
}
case 0xA1: {
Opcode_A1_AJMP_Addr11();
break;
}
case 0xA2: {
Opcode_A2_MOV_C_Bit();
break;
}
case 0xA3: {
Opcode_A3_INC_DPTR();
break;
}
case 0xA4: {
Opcode_A4_MUL_AB();
break;
}
case 0xA5: {
Opcode_A5();
break;
}
case 0xA6: {
Opcode_A6_MOV_R0_1_Direct();
break;
}
case 0xA7: {
Opcode_A7_MOV_R1_1_Direct();
break;
}
case 0xA8: {
Opcode_A8_MOV_R0_Direct();
break;
}
case 0xA9: {
Opcode_A9_MOV_R1_Direct();
break;
}
case 0xAA: {
Opcode_AA_MOV_R2_Direct();
break;
}
case 0xAB: {
Opcode_AB_MOV_R3_Direct();
break;
}
case 0xAC: {
Opcode_AC_MOV_R4_Direct();
break;
}
case 0xAD: {
Opcode_AD_MOV_R5_Direct();
break;
}
case 0xAE: {
Opcode_AE_MOV_R6_Direct();
break;
}
case 0xAF: {
Opcode_AF_MOV_R7_Direct();
break;
}
case 0xB0: {
Opcode_B0_ANL_C_Bit_1();
break;
}
case 0xB1: {
Opcode_B1_ACALL_Addr11();
break;
}
case 0xB2: {
Opcode_B2_CPL_Bit();
break;
}
case 0xB3: {
Opcode_B3_CPL_C();
break;
}
case 0xB4: {
Opcode_B4_CJNE_A_Data_Rel();
break;
}
case 0xB5: {
Opcode_B5_CJNE_A_Direct_Rel();
break;
}
case 0xB6: {
Opcode_B6_CJNE_R0_1_Data_Rel();
break;
}
case 0xB7: {
Opcode_B7_CJNE_R1_1_Data_Rel();
break;
}
case 0xB8: {
Opcode_B8_CJNE_R0_Data_Rel();
break;
}
case 0xB9: {
Opcode_B9_CJNE_R1_Data_Rel();
break;
}
case 0xBA: {
Opcode_BA_CJNE_R2_Data_Rel();
break;
}
case 0xBB: {
Opcode_BB_CJNE_R3_Data_Rel();
break;
}
case 0xBC: {
Opcode_BC_CJNE_R4_Data_Rel();
break;
}
case 0xBD: {
Opcode_BD_CJNE_R5_Data_Rel();
break;
}
case 0xBE: {
Opcode_BE_CJNE_R6_Data_Rel();
break;
}
case 0xBF: {
Opcode_BF_CJNE_R7_Data_Rel();
break;
}
case 0xC0: {
Opcode_C0_PUSH_Direct();
break;
}
case 0xC1: {
Opcode_C1_AJMP_Addr11();
break;
}
case 0xC2: {
Opcode_C2_CLR_Bit();
break;
}
case 0xC3: {
Opcode_C3_CLR_C();
break;
}
case 0xC4: {
Opcode_C4_SWAP_A();
break;
}
case 0xC5: {
Opcode_C5_XCH_A_Direct();
break;
}
case 0xC6: {
Opcode_C6_XCH_A_R0_1();
break;
}
case 0xC7: {
Opcode_C7_XCH_A_R1_1();
break;
}
case 0xC8: {
Opcode_C8_XCH_A_R0();
break;
}
case 0xC9: {
Opcode_C9_XCH_A_R1();
break;
}
case 0xCA: {
Opcode_CA_XCH_A_R2();
break;
}
case 0xCB: {
Opcode_CB_XCH_A_R3();
break;
}
case 0xCC: {
Opcode_CC_XCH_A_R4();
break;
}
case 0xCD: {
Opcode_CD_XCH_A_R5();
break;
}
case 0xCE: {
Opcode_CE_XCH_A_R6();
break;
}
case 0xCF: {
Opcode_CF_XCH_A_R7();
break;
}
case 0xD0: {
Opcode_D0_POP_Direct();
break;
}
case 0xD1: {
Opcode_D1_ACALL_Addr11();
break;
}
case 0xD2: {
Opcode_D2_SETB_Bit();
break;
}
case 0xD3: {
Opcode_D3_SETB_C();
break;
}
case 0xD4: {
Opcode_D4_DA_A();
break;
}
case 0xD5: {
Opcode_D5_DJNZ_Direct_Rel();
break;
}
case 0xD6: {
Opcode_D6_XCHD_A_R0_1();
break;
}
case 0xD7: {
Opcode_D7_XCHD_A_R1_1();
break;
}
case 0xD8: {
Opcode_D8_DJNZ_R0_Rel();
break;
}
case 0xD9: {
Opcode_D9_DJNZ_R1_Rel();
break;
}
case 0xDA: {
Opcode_DA_DJNZ_R2_Rel();
break;
}
case 0xDB: {
Opcode_DB_DJNZ_R3_Rel();
break;
}
case 0xDC: {
Opcode_DC_DJNZ_R4_Rel();
break;
}
case 0xDD: {
Opcode_DD_DJNZ_R5_Rel();
break;
}
case 0xDE: {
Opcode_DE_DJNZ_R6_Rel();
break;
}
case 0xDF: {
Opcode_DF_DJNZ_R7_Rel();
break;
}
case 0xE0: {
Opcode_E0_MOVX_A_DPTR();
break;
}
case 0xE1: {
Opcode_E1_AJMP_Addr11();
break;
}
case 0xE2: {
Opcode_E2_MOVX_A_R0_1();
break;
}
case 0xE3: {
Opcode_E3_MOVX_A_R1_1();
break;
}
case 0xE4: {
Opcode_E4_CLR_A();
break;
}
case 0xE5: {
Opcode_E5_MOV_A_Direct();
break;
}
case 0xE6: {
Opcode_E6_MOV_A_R0_1();
break;
}
case 0xE7: {
Opcode_E7_MOV_A_R1_1();
break;
}
case 0xE8: {
Opcode_E8_MOV_A_R0();
break;
}
case 0xE9: {
Opcode_E9_MOV_A_R1();
break;
}
case 0xEA: {
Opcode_EA_MOV_A_R2();
break;
}
case 0xEB: {
Opcode_EB_MOV_A_R3();
break;
}
case 0xEC: {
Opcode_EC_MOV_A_R4();
break;
}
case 0xED: {
Opcode_ED_MOV_A_R5();
break;
}
case 0xEE: {
Opcode_EE_MOV_A_R6();
break;
}
case 0xEF: {
Opcode_EF_MOV_A_R7();
break;
}
case 0xF0: {
Opcode_F0_MOVX_DPTR_A();
break;
}
case 0xF1: {
Opcode_F1_ACALL_Addr11();
break;
}
case 0xF2: {
Opcode_F2_MOVX_R0_1_A();
break;
}
case 0xF3: {
Opcode_F3_MOVX_R1_1_A();
break;
}
case 0xF4: {
Opcode_F4_CPL_A();
break;
}
case 0xF5: {
Opcode_F5_MOV_Direct_A();
break;
}
case 0xF6: {
Opcode_F6_MOV_R0_1_A();
break;
}
case 0xF7: {
Opcode_F7_MOV_R1_1_A();
break;
}
case 0xF8: {
Opcode_F8_MOV_R0_A();
break;
}
case 0xF9: {
Opcode_F9_MOV_R1_A();
break;
}
case 0xFA: {
Opcode_FA_MOV_R2_A();
break;
}
case 0xFB: {
Opcode_FB_MOV_R3_A();
break;
}
case 0xFC: {
Opcode_FC_MOV_R4_A();
break;
}
case 0xFD: {
Opcode_FD_MOV_R5_A();
break;
}
case 0xFE: {
Opcode_FE_MOV_R6_A();
break;
}
case 0xFF: {
Opcode_FF_MOV_R7_A();
break;
}
default:
// assert(0);
break;
}
}
bool CVm8051::GetBitFlag(INT8U addr) {
return (GetBitRamRef(addr) & (BIT0 << (addr % 8))) != 0;
}
void CVm8051::SetBitFlag(INT8U addr) {
GetBitRamRef(addr) |= (BIT0 << (addr % 8));
if (addr >= 0xe0 && addr <= 0xe7) {
Updata_A_P_Flag();
}
}
void CVm8051::ClrBitFlag(INT8U addr) {
GetBitRamRef(addr) &= (~(BIT0 << (addr % 8)));
if (addr >= 0xe0 && addr <= 0xe7)
{
Updata_A_P_Flag();
}
}
INT8U CVm8051::GetOpcode(void) const {
return m_ExeFile[Sys.PC];
}
INT8U& CVm8051::GetRamRef(INT8U addr) {
if (addr > 0x7F) {
return m_ChipSfr[addr];
} else {
return m_ChipRam[addr];
}
}
INT16U CVm8051::GetDebugOpcode(void) const {
INT16U temp = 0;
memcpy(&temp, &m_ExeFile[Sys.PC], 2);
return temp;
}
bool CVm8051::GetDebugPC(INT16U pc) const {
return (pc == Sys.PC);
}
void CVm8051::GetOpcodeData(void * const p, INT8U len) const {
memcpy(p, &m_ExeFile[Sys.PC + 1], len);
}
void CVm8051::AJMP(INT8U opCode, INT8U data) {
INT16U tmppc = Sys.PC + 2;
tmppc &= 0xF800;
tmppc |= ((((((INT16U) opCode) >> 5) & 0x7) << 8) | ((INT16U) data));
Sys.PC = tmppc;
}
void CVm8051::ACALL(INT8U opCode) {
INT8U data = Get1Opcode();
Sys.PC += 2;
Sys.sp = Sys.sp() + 1;
SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC & 0x00ff));
Sys.sp = Sys.sp() + 1;
SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC >> 8));
Sys.PC = ((Sys.PC & 0xF800) | (((((INT16U) opCode) >> 5) << 8) | (INT16U) data));
}
void CVm8051::UpDataDebugInfo(void) {
d_Rges.R0 = Rges.R0();
d_Rges.R1 = Rges.R1();
d_Rges.R2 = Rges.R2();
d_Rges.R3 = Rges.R3();
d_Rges.R4 = Rges.R4();
d_Rges.R5 = Rges.R5();
d_Rges.R6 = Rges.R6();
d_Rges.R7 = Rges.R7();
d_Sys.a = Sys.a();
d_Sys.b = Sys.b();
d_Sys.sp = Sys.sp();
d_Sys.dptr = Sys.dptr();
d_Sys.psw = Sys.psw();
d_Sys.PC = Sys.PC;
}
void * CVm8051::GetExRamAddr(INT16U addr) const {
// Assert(addr < sizeof(m_ExRam));
return (void *) &m_ExRam[addr];
}
INT8U CVm8051::GetExRam(INT16U addr) const {
// Assert(addr < sizeof(m_ExRam));
return m_ExRam[addr];
}
INT8U CVm8051::SetExRam(INT16U addr, INT8U data) {
// Assert(addr < sizeof(m_ExRam));
return m_ExRam[addr] = data;
}
void * CVm8051::GetPointRamAddr(INT16U addr) const {
// Assert(addr < sizeof(m_ChipRam));
return (void *) &m_ChipRam[addr];
}
INT8U CVm8051::GetRamDataAt(INT8U addr) {
return m_ChipRam[addr];
}
INT8U CVm8051::SetRamDataAt(INT8U addr, INT8U data) {
return m_ChipRam[addr] = data;
}
INT8U CVm8051::GetRamData(INT8U addr) {
return GetRamRef(addr);
}
INT8U CVm8051::SetRamData(INT8U addr, INT8U data) {
GetRamRef(addr) = data;
return data;
}
void* CVm8051::GetPointFileAddr(INT16U addr) const {
Assert(addr < sizeof(m_ExeFile));
return (void*) &m_ExeFile[addr];
}
void CVm8051::Opcode_02_LJMP_Addr16(void) {
INT8U temp[2];
INT16U data;
GetOpcodeData(temp, 2);
data = (((INT16U) (temp[0])) << 8);
Sys.PC = data | temp[1];
}
void CVm8051::Opcode_03_RR_A(void) {
INT8U temp = (Sys.a() & 0x1);
Sys.a = Sys.a() >> 1;
Sys.a = Sys.a() | (temp << 7);
++Sys.PC;
}
void CVm8051::Opcode_05_INC_Direct(void) {
INT8U temp = 0;
INT8U addr = Get1Opcode();
temp = GetRamData(addr);
++temp;
SetRamData(addr, temp);
Sys.PC = Sys.PC + 2;
}
void CVm8051::Opcode_06_INC_R0_1(void) {
INT8U data = 0;
INT8U addr = Rges.R0();
data = GetRamDataAt(addr);
++data;
SetRamDataAt(addr, data);
++Sys.PC;
}
void CVm8051::Opcode_07_INC_R1_1(void) {
INT8U data = 0;
INT8U addr = Rges.R1();
data = GetRamDataAt(addr);
++data;
SetRamDataAt(addr, data);
++Sys.PC;
}
void CVm8051::Opcode_10_JBC_Bit_Rel(void) {
INT8U temp[2];
char tem2;
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
// Assert(temp[0]<=0xF7);
// if (temp[0] <= 0x7F) {
if (GetBitFlag((temp[0]))) {
ClrBitFlag(temp[0]);
memcpy(&tem2, &temp[1], sizeof(temp[1]));
Sys.PC += tem2;
}
}
INT16U CVm8051::GetLcallAddr(void) {
INT16U addr = 0;
GetOpcodeData((INT8U*) &addr, 2);
Assert(GetOpcode() == 0x12);
return (addr >> 8) | (addr << 8);
}
void CVm8051::Opcode_12_LCALL_Addr16(void) {
// INT8U temp = 0;
INT16U addr = 0;
// void *p = NULL;
GetOpcodeData((INT8U*) &addr, 2);
Sys.PC += 3;
Sys.sp = Sys.sp() + 1;
SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC & 0x00ff));
Sys.sp = Sys.sp() + 1;
SetRamDataAt(Sys.sp(), (INT8U) (Sys.PC >> 8));
// GetOpcodeData(&Sys.PC,2);
Sys.PC = (addr >> 8) | (addr << 8);
}
void CVm8051::Opcode_13_RRC_A(void) {
INT8U temp = Sys.a() & BIT0;
Sys.a = ((Sys.a() >> 1) | (Sys.psw().cy << 7));
Sys.psw().cy = (temp == 0) ? 0 : 1;
++Sys.PC;
}
void CVm8051::Opcode_14_DEC_A(void) {
Sys.a = Sys.a() - 1;
++Sys.PC;
}
void CVm8051::Opcode_15_DEC_Direct(void) {
INT8U temp = 0;
INT8U addr = Get1Opcode();
temp = GetRamData(addr);
--temp;
SetRamData(addr, temp);
Sys.PC = Sys.PC + 2;
}
void CVm8051::Opcode_16_DEC_R0_1(void) {
INT8U temp = 0;
INT8U addr = Rges.R0();
temp = GetRamDataAt(addr);
--temp;
SetRamDataAt(addr, temp);
++Sys.PC;
}
void CVm8051::Opcode_17_DEC_R1_1(void) {
INT8U temp = 0;
INT8U addr = Rges.R1();
temp = GetRamDataAt(addr);
temp--;
SetRamDataAt(addr, temp);
++Sys.PC;
}
void CVm8051::Opcode_20_JB_Bit_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (GetBitFlag((temp[0]))) {
char tem2;
memcpy(&tem2, &temp[1], sizeof(temp[1]));
Sys.PC += tem2;
// Sys.PC = GetTargPC(temp[1]);
}
}
void CVm8051::Opcode_22_RET(void) {
INT8U temp = 0;
temp = GetRamDataAt(Sys.sp());
Sys.PC = (Sys.PC & 0x00FF) | (((INT16U) temp) << 8);
Sys.sp = Sys.sp() - 1;
temp = GetRamDataAt(Sys.sp());
Sys.PC = (Sys.PC & 0xFF00) | temp;
Sys.sp = Sys.sp() - 1;
}
void CVm8051::Opcode_23_RL_A(void) {
INT8U temp = Sys.a() & 0x80;
INT8U tem2 = Sys.a();
Sys.a = (INT8U) ((tem2 << 1) | (temp >> 7));
++Sys.PC;
}
void CVm8051::MD_ADDC(INT8U data) {
INT8U flagAC = Sys.psw().cy;
if (flagAC > 1) {
// assert(0);
flagAC = 1;
}
INT16U tep = (INT16U) Sys.a() + (INT16U) data + flagAC;
INT16U tep2 = ((INT16U) (Sys.a() & 0x7F) + (INT16U) (data & 0x7F)) + flagAC;
if ((Sys.a() & 0x0f) + (data & 0x0f) + flagAC > 0x0F) {
Sys.psw().ac = 1;
} else {
Sys.psw().ac = 0;
}
if (tep > 0xFF) {
Sys.psw().cy = 1;
} else {
Sys.psw().cy = 0;
}
flagAC = 0;
if (tep > 0xFF) {
flagAC++;
}
if (tep2 > 0x7F) {
flagAC++;
}
Sys.psw().ov = flagAC == 1 ? 1 : 0;
Sys.a = (INT8U) tep;
}
void CVm8051::MD_SUBB(INT8U data) {
INT16U tepa = Sys.a();
INT8U bcy = Sys.psw().cy;
// data += Sys.psw().cy;
if ((tepa & 0x0f) < (data & 0x0f) + Sys.psw().cy) {
Sys.psw().ac = 1;
} else {
Sys.psw().ac = 0;
}
if (tepa < data + bcy) {
Sys.psw().cy = 1;
} else {
Sys.psw().cy = 0;
}
INT8U flagac = 0;
if (tepa < data + bcy) {
flagac++;
}
if ((tepa & 0x7F) < (data & 0x7F) + bcy) {
flagac++;
}
Sys.psw().ov = flagac == 1 ? 1 : 0;
Sys.a = (INT8U) (tepa - data - bcy);
}
void CVm8051::MD_ADD(INT8U data) {
INT16U tep = (INT16U) Sys.a() + (INT16U) data;
INT16U tep2 = ((INT16U) (Sys.a() & 0x7F) + (INT16U) (data & 0x7F));
if ((Sys.a() & 0x0f) + (data & 0x0f) > 0x0F) {
Sys.psw().ac = 1;
} else {
Sys.psw().ac = 0;
}
if (tep > 0xFF) {
Sys.psw().cy = 1;
} else {
Sys.psw().cy = 0;
}
INT8U flagAC = 0;
if (tep > 0xFF) {
flagAC++;
}
if (tep2 > 0x7F) {
flagAC++;
}
Sys.psw().ov = flagAC == 1 ? 1 : 0;
Sys.a = (INT8U) tep;
}
void CVm8051::Opcode_30_JNB_Bit_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
// Assert(temp[0]<0xF7);
Sys.PC += 3;
if (!GetBitFlag((temp[0]))) {
char tem2;
memcpy(&tem2, &temp[1], sizeof(temp[1]));
Sys.PC += tem2;
// Sys.PC = GetTargPC(temp[1]);
}
}
void CVm8051::Opcode_32_RETI(void) {
INT8U temp = 0;
temp = GetRamData(Sys.sp());
Sys.PC = (Sys.PC & 0x00FF) | (((INT16U) temp) << 8);
Sys.sp = Sys.sp() - 1;
temp = GetRamData(Sys.sp());
Sys.PC = (Sys.PC & 0xFF00) | temp;
Sys.sp = Sys.sp() - 1;
++Sys.PC;
}
void CVm8051::Opcode_33_RLC_A(void) {
INT8U temp = Sys.a() & 0x80;
Sys.a = ((Sys.a() << 1) | Sys.psw().cy);
Sys.psw().cy = temp == 0 ? 0 : 1;
++Sys.PC;
}
void CVm8051::Opcode_40_JC_Rel(void) {
char tem2= Get1Opcode();
// GetOpcodeData(&tem2, 1);
Sys.PC += 2;
if (Sys.psw().cy) {
memcpy(&tem2, &tem2, sizeof(tem2));
Sys.PC += tem2;
// Sys.PC = GetTargPC(temp);
}
}
void CVm8051::Opcode_42_ORL_Direct_A(void) {
INT8U temp;
INT8U addr = Get1Opcode();
temp = GetRamData(addr);
temp |= Sys.a();
SetRamData(addr, temp);
Sys.PC += 2;
}
void CVm8051::Opcode_43_ORL_Direct_Data(void) {
INT8U temp[2] = { 0 };
INT8U data;
// void *p = NULL;
GetOpcodeData(&temp[0], 2); //direct ~{JG~}1~{8vWV=Z~}
data = GetRamData(temp[0]);
data |= temp[1];
// memcpy(p, &data, 1);
SetRamData(temp[0], data);
Sys.PC += 3;
}
void CVm8051::Updata_A_P_Flag(void) {
INT8U a = Sys.a();
a ^= a >> 4;
a ^= a >> 2;
a ^= a >> 1;
Sys.psw().p = (a & 1);
}
void CVm8051::Opcode_44_ORL_A_Data(void) {
INT8U temp = Get1Opcode();
Sys.a = Sys.a() | temp;
Sys.PC += 2;
}
void CVm8051::Opcode_45_ORL_A_Direct(void) {
INT8U data;
INT8U addr = Get1Opcode();
// GetOpcodeData(&addr, 1);
data = GetRamData(addr);
Sys.a = Sys.a() | data;
Sys.PC += 2;
}
void CVm8051::Opcode_50_JNC_Rel(void) {
char tem2 = Get1Opcode();
// GetOpcodeData(&tem2, 1);
Sys.PC += 2;
if (Sys.psw().cy == 0) {
Sys.PC += tem2;
}
}
void CVm8051::Opcode_52_ANL_Direct_A(void) {
INT8U temp;
INT8U addr =Get1Opcode();
// void *p = NULL;
GetOpcodeData(&addr, 1);
temp = GetRamData(addr);
temp &= Sys.a();
SetRamData(addr, temp);
Sys.PC += 2;
}
void CVm8051::Opcode_53_ANL_Direct_Data(void) {
INT8U temp[2] = { 0 };
INT8U data;
GetOpcodeData(&temp[0], 2);
data = GetRamData(temp[0]);
data &= temp[1];
SetRamData(temp[0], data);
Sys.PC += 3;
}
void CVm8051::Opcode_60_JZ_Rel(void) {
char temp= Get1Opcode();
// GetOpcodeData(&temp, 1);
Sys.PC += 2;
if (Sys.a() == 0) {
// Sys.PC = GetTargPC(temp);
Sys.PC += temp;
}
}
void CVm8051::Opcode_62_XRL_Direct_A(void) {
INT8U temp;
INT8U addr = Get1Opcode();
temp = GetRamData(addr);
temp ^= Sys.a();
SetRamData(addr, temp);
Sys.PC += 2;
}
void CVm8051::Opcode_63_XRL_Direct_Data(void) {
INT8U temp[2] = { 0 };
INT8U data;
GetOpcodeData(&temp[0], 2);
data = GetRamData(temp[0]);
data ^= temp[1];
SetRamData(temp[0], data);
Sys.PC += 3;
}
void CVm8051::Opcode_70_JNZ_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
if (Sys.a() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_75_MOV_Direct_Data(void) {
INT8U temp[2] = { 0 };
GetOpcodeData(&temp[0], 2);
SetRamData(temp[0], temp[1]);
Sys.PC += 3;
}
void CVm8051::Opcode_80_SJMP_Rel(void) {
char temp= Get1Opcode();
Sys.PC += 2;
Sys.PC += temp;
}
void CVm8051::Opcode_83_MOVC_A_PC(void) {
// INT8U temp;
INT16U addr;
// void*p = NULL;
++Sys.PC;
addr = (INT16U) (Sys.PC + Sys.a());
Sys.a = (Sys.PC > CVm8051::MAX_ROM - Sys.a()) ? (0x00) : (m_ExeFile[addr]);
}
void CVm8051::Opcode_84_DIV_AB(void) {
INT8U data1, data2;
data1 = Sys.a();
data2 = Sys.b();
if (data2 == 0) {
Sys.psw().ov = 1;
goto Ret;
}
Sys.a = data1 / data2;
Sys.b = data1 % data2;
Sys.psw().ov = 0;
Ret: Sys.psw().cy = 0;
++Sys.PC;
}
void CVm8051::Opcode_85_MOV_Direct_Direct(void) {
INT8U temp[2];
INT8U tem;
GetOpcodeData(&temp[0], 2);
tem = GetRamData(temp[0]);
SetRamData(temp[1], tem);
Sys.PC += 3;
}
void CVm8051::Opcode_90_MOV_DPTR_Data(void) {
INT16U temp;
GetOpcodeData(&temp, 2);
temp = (temp >> 8) | (temp << 8);
Sys.dptr = temp;
Sys.PC += 3;
}
void CVm8051::Opcode_92_MOV_Bit_C(void) {
INT8U temp = Get1Opcode();
if (Sys.psw().cy) {
SetBitFlag(temp);
} else {
ClrBitFlag(temp);
}
Sys.PC += 2;
}
void CVm8051::Opcode_93_MOVC_A_DPTR(void) {
INT8U temp;
void *p = NULL;
p = GetPointFileAddr((INT16U) (Sys.a() + Sys.dptr()));
memcpy(&temp, p, sizeof(temp));
Sys.a = (Sys.dptr() > CVm8051::MAX_ROM - Sys.a()) ? (0x00) : (temp);
++Sys.PC;
}
void CVm8051::Opcode_A4_MUL_AB(void) {
INT16U temp;
temp = (INT16U) Sys.a() * (INT16U) Sys.b();
Sys.psw().ov = (temp > 255) ? 1 : 0;
Sys.a = (INT8U) temp;
Sys.b = (INT8U) (temp >> 8);
++Sys.PC;
}
void CVm8051::Opcode_B2_CPL_Bit(void) {
INT8U temp=Get1Opcode();
if (GetBitFlag(temp)) {
ClrBitFlag(temp);
} else {
SetBitFlag(temp);
}
Sys.PC += 2;
}
void CVm8051::Opcode_B4_CJNE_A_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Sys.a() != temp[0]) {
char tem;
memcpy(&tem, &temp[1], 1);
Sys.PC += tem;
}
if ((Sys.a() < temp[0])) {
Sys.psw().cy = 1;
} else {
Sys.psw().cy = 0;
}
}
void CVm8051::Opcode_B5_CJNE_A_Direct_Rel(void) {
INT8U temp[2];
INT8U data;
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
data = GetRamData(temp[0]);
if (Sys.a() != data) {
char tem;
memcpy(&tem, &temp[1], 1);
Sys.PC += tem;
}
Sys.psw().cy = (Sys.a() < data) ? 1 : 0;
}
void CVm8051::Opcode_B6_CJNE_R0_1_Data_Rel(void) {
INT8U temp[2];
INT8U data;
GetOpcodeData(&temp[0], sizeof(temp));
data = GetRamDataAt(Rges.R0());
Sys.PC += 3;
if (data != temp[0]) {
char tem;
memcpy(&tem, &temp[1], 1);
Sys.PC += tem;
}
Sys.psw().cy = (data < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_B7_CJNE_R1_1_Data_Rel(void) {
INT8U temp[2];
INT8U data;
GetOpcodeData(&temp[0], sizeof(temp));
data = GetRamDataAt(Rges.R1());
Sys.PC += 3;
if (data != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (data < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_B8_CJNE_R0_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R0() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R0() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_B9_CJNE_R1_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R1() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R1() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_BA_CJNE_R2_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R2() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R2() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_BB_CJNE_R3_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R3() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R3() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_BC_CJNE_R4_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R4() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R4() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_BD_CJNE_R5_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R5() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R5() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_BE_CJNE_R6_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R6() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R6() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_BF_CJNE_R7_Data_Rel(void) {
INT8U temp[2];
GetOpcodeData(&temp[0], sizeof(temp));
Sys.PC += 3;
if (Rges.R7() != temp[0]) {
Sys.PC += (char)temp[1];
}
Sys.psw().cy = (Rges.R7() < temp[0]) ? 1 : 0;
}
void CVm8051::Opcode_C5_XCH_A_Direct(void) {
INT8U addr;
INT8U data;
INT8U TT;
GetOpcodeData(&addr, sizeof(addr));
data = GetRamData(addr);
TT = Sys.a();
Sys.a = data;
SetRamData(addr, TT);
Sys.PC += 2;
}
void CVm8051::Opcode_C6_XCH_A_R0_1(void) {
INT8U TT;
TT = Sys.a();
Sys.a = GetRamDataAt(Rges.R0());
SetRamDataAt(Rges.R0(), TT);
++Sys.PC;
}
void CVm8051::Opcode_C7_XCH_A_R1_1(void) {
INT8U TT;
TT = Sys.a();
Sys.a = GetRamDataAt(Rges.R1());
SetRamDataAt(Rges.R1(), TT);
++Sys.PC;
}
void CVm8051::Opcode_C8_XCH_A_R0(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R0();
Rges.R0 = temp;
++Sys.PC;
}
void CVm8051::Opcode_C9_XCH_A_R1(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R1();
Rges.R1 = temp;
++Sys.PC;
}
void CVm8051::Opcode_CA_XCH_A_R2(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R2();
Rges.R2 = temp;
++Sys.PC;
}
void CVm8051::Opcode_CB_XCH_A_R3(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R3();
Rges.R3 = temp;
++Sys.PC;
}
void CVm8051::Opcode_CC_XCH_A_R4(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R4();
Rges.R4 = temp;
++Sys.PC;
}
void CVm8051::Opcode_CD_XCH_A_R5(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R5();
Rges.R5 = temp;
++Sys.PC;
}
void CVm8051::Opcode_CE_XCH_A_R6(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R6();
Rges.R6 = temp;
++Sys.PC;
}
void CVm8051::Opcode_CF_XCH_A_R7(void) {
INT8U temp;
temp = Sys.a();
Sys.a = Rges.R7();
Rges.R7 = temp;
++Sys.PC;
}
void CVm8051::Opcode_D0_POP_Direct(void) {
SetRamData(Get1Opcode(), GetRamDataAt(Sys.sp()));
Sys.sp = Sys.sp() - 1;
Sys.PC += 2;
}
void CVm8051::Opcode_D4_DA_A(void) {
INT8U temp;
if (((Sys.a() & 0x0f) > 9) || (Sys.psw().ac == 1)) {
temp = ((Sys.a() & 0x0f) + 6) % 16;
Sys.a = Sys.a() & 0xF0;
Sys.a = Sys.a() | temp;
}
temp = ((Sys.a() & 0xF0) >> 4);
if ((temp > 9) || (Sys.psw().cy == 1)) {
temp = (temp + 6) % 16;
Sys.a = Sys.a() & 0x0F;
Sys.a = Sys.a() | (temp << 4);
}
++Sys.PC;
}
void CVm8051::Opcode_D5_DJNZ_Direct_Rel(void) {
INT8U temp[2];
INT8U data;
GetOpcodeData(&temp[0], sizeof(temp));
data = GetRamData(temp[0]);
data--;
SetRamData(temp[0], data);
Sys.PC += 3;
if (data != 0) {
char tem;
memcpy(&tem, &temp[1], 1);
Sys.PC += tem;
}
}
void CVm8051::Opcode_D6_XCHD_A_R0_1(void) {
INT8U temp = 0;
INT8U data = GetRamDataAt(Rges.R0());
temp = Sys.a() & 0x0F;
Sys.a = Sys.a() & 0xF0;
Sys.a = Sys.a() | (data & 0x0F);
data &= 0xF0;
data |= temp;
SetRamDataAt(Rges.R0(), data);
++Sys.PC;
}
void CVm8051::Opcode_D7_XCHD_A_R1_1(void) {
INT8U temp = 0;
INT8U data;
data = GetRamDataAt(Rges.R1());
temp = Sys.a() & 0x0F;
Sys.a = Sys.a() & 0xF0;
Sys.a = Sys.a() | (data & 0x0F);
data &= 0xF0;
data |= temp;
SetRamDataAt(Rges.R1(), data);
++Sys.PC;
}
void CVm8051::Opcode_D8_DJNZ_R0_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R0 = Rges.R0() - 1;
if (Rges.R0() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_D9_DJNZ_R1_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R1 = Rges.R1() - 1;
if (Rges.R1() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_DA_DJNZ_R2_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R2 = Rges.R2() - 1;
if (Rges.R2() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_DB_DJNZ_R3_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R3 = Rges.R3() - 1;
if (Rges.R3() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_DC_DJNZ_R4_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R4 = Rges.R4() - 1;
if (Rges.R4() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_DD_DJNZ_R5_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R5 = Rges.R5() - 1;
if (Rges.R5() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_DE_DJNZ_R6_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R6 = Rges.R6() - 1;
if (Rges.R6() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_DF_DJNZ_R7_Rel(void) {
char temp = Get1Opcode();
Sys.PC += 2;
Rges.R7 = Rges.R7() - 1;
if (Rges.R7() != 0) {
Sys.PC += temp;
}
}
void CVm8051::Opcode_E0_MOVX_A_DPTR(void) {
Sys.a = m_ExRam[Sys.dptr()];
++Sys.PC;
}
shared_ptr<vector<unsigned char>> CVm8051::GetRetData(void) const {
auto tem = std::make_shared<vector<unsigned char>>();
char buffer[1024] = { 0 };
memcpy(buffer, &m_ExRam[0xFC00], 1023);
tem.get()->assign(buffer, buffer + 1023);
return tem;
}
template<class T2>
T2& CUPReg<T2>::GetRegRe(void) {
assert(m_Addr != 255);
return *((T2*) (&pmcu->m_ChipRam[m_Addr]));
}
INT8U& CUPReg_a::GetRegRe(void) {
assert(m_Addr != 255);
return pmcu->m_ChipSfr[m_Addr];
}
INT8U& CUPSfr::GetRegRe(void) {
assert(m_Addr != 255);
return pmcu->m_ChipSfr[m_Addr];
}
INT16U& CUPSfr16::GetRegRe(void) {
assert(m_Addr != 255);
return *((INT16U*) &pmcu->m_ChipSfr[m_Addr]);
}
template<class T2>
T2 CUPReg<T2>::getValue() {
return GetRegRe();
}
void CUPReg_a::Updataflag() {
pmcu->Updata_A_P_Flag();
}
PSW& CUPPSW_8::operator()(void) {
return *((PSW*) &(GetRegRe()));
}
| 22.138304 | 117 | 0.639098 | koalajack |
c3debfa947362fdc46cb23f328eb5e9f0e5ce3cf | 3,561 | cpp | C++ | src/CoordinateAxes.cpp | sosswald/gpu-coverage | da36062272244573abd938996d8cb6ecd25a55e7 | [
"BSD-3-Clause"
] | 2 | 2018-09-17T15:21:06.000Z | 2020-03-27T11:57:04.000Z | src/CoordinateAxes.cpp | sosswald/gpu-coverage | da36062272244573abd938996d8cb6ecd25a55e7 | [
"BSD-3-Clause"
] | null | null | null | src/CoordinateAxes.cpp | sosswald/gpu-coverage | da36062272244573abd938996d8cb6ecd25a55e7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018, Stefan Osswald
* 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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <gpu_coverage/CoordinateAxes.h>
#include <gpu_coverage/Mesh.h>
#include GLEXT_INCLUDE
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS true
#endif
#include <glm/gtc/type_ptr.hpp>
namespace gpu_coverage {
CoordinateAxes::CoordinateAxes()
: modelMatrix(glm::mat4()) {
const float points[] = {
-1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, 1.0f
};
const float colors[] = {
1.0f, 1.0f, 1.0f,
1.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f
};
const unsigned int indices[] = { 0, 1, 2, 3, 4, 5 };
glGenBuffers(3, vbo);
enum {
POINTS = 0, COLORS = 1, INDICES = 2
};
vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo[POINTS]);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
glVertexAttribPointer(Mesh::VERTEX_BUFFER, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(Mesh::VERTEX_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER, vbo[COLORS]);
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
glVertexAttribPointer(Mesh::COLOR_BUFFER, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(Mesh::COLOR_BUFFER);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[INDICES]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vbo[INDICES]), indices, GL_STATIC_DRAW);
glVertexAttribPointer(Mesh::INDEX_BUFFER, 1, GL_UNSIGNED_INT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(Mesh::INDEX_BUFFER);
}
CoordinateAxes::~CoordinateAxes() {
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(3, vbo);
}
void CoordinateAxes::display() const {
glBindVertexArray(vao);
glDrawArrays(GL_LINES, 0, 6);
}
} /* namespace gpu_coverage */
| 35.969697 | 89 | 0.693906 | sosswald |
c3e22d21312e99e2f44ae8bab67b83bd52ad148d | 4,403 | cpp | C++ | plugin/plugin_guide/snippets/dicom_menus/milxQtDICOMPlugin.cpp | aneube/smili-spine | 3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b | [
"BSD-2-Clause"
] | 17 | 2015-03-09T19:22:07.000Z | 2021-05-24T20:25:08.000Z | plugin/plugin_guide/snippets/dicom_menus/milxQtDICOMPlugin.cpp | aneube/smili-spine | 3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b | [
"BSD-2-Clause"
] | 16 | 2015-08-20T03:30:15.000Z | 2019-10-22T12:21:14.000Z | plugin/plugin_guide/snippets/dicom_menus/milxQtDICOMPlugin.cpp | aneube/smili-spine | 3cd8f95077d4bc1f5ac6146bc5356c3131f22e4b | [
"BSD-2-Clause"
] | 11 | 2015-06-22T00:11:01.000Z | 2021-12-26T21:29:52.000Z | #include "milxQtDICOMPlugin.h"
#include <qplugin.h>
milxQtDICOMPlugin::milxQtDICOMPlugin(QObject *theParent) : milxQtPluginInterface(theParent)
{
///Up cast parent to milxQtMain
MainWindow = qobject_cast<milxQtMain *>(theParent);
//~ threaded = false;
//~ dockable = false;
//~ consoleWindow = false;
//~ extension = true;
pluginName = "DICOM";
//~ dataName = "";
createActions();
createMenu();
createConnections();
}
milxQtDICOMPlugin::~milxQtDICOMPlugin()
{
if(isRunning() && threaded)
quit();
cout << "DICOM Plugin Destroyed." << endl;
}
QString milxQtDICOMPlugin::name()
{
return pluginName;
}
QString milxQtDICOMPlugin::openFileSupport()
{
QString openPythonExt = "";
return openPythonExt;
}
QStringList milxQtDICOMPlugin::openExtensions()
{
QStringList exts;
return exts;
}
QStringList milxQtDICOMPlugin::saveExtensions()
{
QStringList exts;
return exts;
}
QString milxQtDICOMPlugin::saveFileSupport()
{
QString savePythonExt = "";
return savePythonExt;
}
void milxQtDICOMPlugin::SetInputCollection(vtkPolyDataCollection* collection, QStringList &filenames)
{
}
void milxQtDICOMPlugin::open(QString filename)
{
}
void milxQtDICOMPlugin::save(QString filename)
{
}
milxQtRenderWindow* milxQtDICOMPlugin::genericResult()
{
return NULL;
} //No image result
milxQtModel* milxQtDICOMPlugin::modelResult()
{
//~ denoiseModel = new milxQtDICOMModel;
return NULL;
//~ return denoiseModel;
} //No image result
milxQtImage* milxQtDICOMPlugin::imageResult()
{
return NULL;
} //No image result
QDockWidget* milxQtDICOMPlugin::dockWidget()
{
return NULL;
} //No Dock result
bool milxQtDICOMPlugin::isPluginWindow(QWidget *window)
{
//~ if(pluginWindow(window) == 0)
return false;
//~ else
//~ return true;
}
//~ milxQtDeNoiseModel* milxQtDeNoisePlugin::pluginWindow(QWidget *window)
//~ {
//~ if(window)
//~ return qobject_cast<milxQtDeNoiseModel *>(window);
//~ return 0;
//~ }
void milxQtDICOMPlugin::loadExtension()
{
//~ if(!MainWindow->isActiveModel())
//~ return;
//~ milxQtModel *currentWin = MainWindow->activeModel();
//~ milxQtDeNoiseModel *denoiseModel = new milxQtDeNoiseModel(MainWindow); //hierarchical deletion
//~ denoiseModel->setName(currentWin->getName());
//~ denoiseModel->SetInput(currentWin->GetOutput());
//~ denoiseModel->generateModel();
//~ MainWindow->display(denoiseModel);
}
//~ void milxQtDICOMPlugin::run()
//~ {
//~ QMutexLocker locker(&mutex); //Lock memory
//~ ///Execute own thread work here
//~ //exec();
//~ }
//~ void milxQtDICOMPlugin::createConnections()
//~ {
//~ //QObject::connect(denoiseAct, SIGNAL(triggered(bool)), denoiseModel, SLOT(denoise()));
//~ }
void milxQtDICOMPlugin::convert()
{
cout << "Converting DICOMs" << endl;
}
void milxQtDICOMPlugin::anonymize()
{
cout << "Anonymizing DICOMs" << endl;
}
void milxQtDICOMPlugin::createActions()
{
actionConvert = new QAction(MainWindow);
actionConvert->setText(QApplication::translate("DICOMPlugin", "Convert ...", 0, QApplication::UnicodeUTF8));
actionConvert->setShortcut(tr("Ctrl+Alt+c"));
actionAnonymize = new QAction(MainWindow);
actionAnonymize->setText(QApplication::translate("DICOMPlugin", "Anonymize ...", 0, QApplication::UnicodeUTF8));
actionAnonymize->setShortcut(tr("Ctrl+Alt+a"));
}
void milxQtDICOMPlugin::createMenu()
{
menuDICOM = new QMenu(MainWindow);
menuDICOM->setTitle(QApplication::translate("DICOMPlugin", "DICOM", 0, QApplication::UnicodeUTF8));
menuDICOM->addAction(actionConvert);
menuDICOM->addAction(actionAnonymize);
menuToAdd.append(menuDICOM);
}
void milxQtDICOMPlugin::createConnections()
{
// connect(MainWindow, SIGNAL(windowActivated(QWidget*)), this, SLOT(updateManager(QWidget*)));
connect(actionConvert, SIGNAL(activated()), this, SLOT(convert()));
connect(actionAnonymize, SIGNAL(activated()), this, SLOT(anonymize()));
// connect(btnAtlasName, SIGNAL(clicked()), this, SLOT(showAtlasFileDialog()));
// connect(btnSurfaceNames, SIGNAL(clicked()), this, SLOT(showSurfacesFileDialog()));
// connect(btnClearSurfaceNames, SIGNAL(clicked()), comboSurfaceNames, SLOT(clear()));
}
Q_EXPORT_PLUGIN2(DICOMPlugin, milxQtDICOMPluginFactory);
| 23.8 | 116 | 0.691801 | aneube |
c3e4981b41e0c9b7d965a3bbdabb4985ca86dbe3 | 548 | cpp | C++ | excercise_book/task_1_1/main.cpp | bartekpacia/cpp-training | ec0b6c3ca4d2590e05df647d597ced94fed922af | [
"MIT"
] | null | null | null | excercise_book/task_1_1/main.cpp | bartekpacia/cpp-training | ec0b6c3ca4d2590e05df647d597ced94fed922af | [
"MIT"
] | null | null | null | excercise_book/task_1_1/main.cpp | bartekpacia/cpp-training | ec0b6c3ca4d2590e05df647d597ced94fed922af | [
"MIT"
] | null | null | null | /**
* Task 1.1
* Write a program calculating area of the rectangle. The
* values of sides a and b are float, so is the area. Display
* the result with precision of two decimal places.
**/
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
float a, b, area;
cout << "Enter side a" << endl;
cin >> a;
cout << "Enter side b" << endl;
cin >> b;
cout << fixed;
cout << setprecision(2);
area = a * b;
cout << "Area of this rectangle is " << area << endl;
getchar();
return 0;
} | 19.571429 | 61 | 0.587591 | bartekpacia |
c3ef135143b457c16bc80960ba3b059435f2efb5 | 6,127 | cpp | C++ | src/burner/win32/memcard.cpp | tt-arcade/fba-pi | 10407847a98f0d315b05e44f0ecf01824f4558aa | [
"Apache-2.0"
] | null | null | null | src/burner/win32/memcard.cpp | tt-arcade/fba-pi | 10407847a98f0d315b05e44f0ecf01824f4558aa | [
"Apache-2.0"
] | null | null | null | src/burner/win32/memcard.cpp | tt-arcade/fba-pi | 10407847a98f0d315b05e44f0ecf01824f4558aa | [
"Apache-2.0"
] | null | null | null | // Memory card support module
#include "burner.h"
static TCHAR szMemoryCardFile[MAX_PATH];
int nMemoryCardStatus = 0;
int nMemoryCardSize;
static int nMinVersion;
static bool bMemCardFC1Format;
static int MakeOfn()
{
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hScrnWnd;
ofn.lpstrFile = szMemoryCardFile;
ofn.nMaxFile = sizeof(szMemoryCardFile);
ofn.lpstrInitialDir = _T(".");
ofn.Flags = OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
ofn.lpstrDefExt = _T("fc");
return 0;
}
static int MemCardRead(TCHAR* szFilename, unsigned char* pData, int nSize)
{
const char* szHeader = "FB1 FC1 "; // File + chunk identifier
char szReadHeader[8] = "";
bMemCardFC1Format = false;
FILE* fp = _tfopen(szFilename, _T("rb"));
if (fp == NULL) {
return 1;
}
fread(szReadHeader, 1, 8, fp); // Read identifiers
if (memcmp(szReadHeader, szHeader, 8) == 0) {
// FB Alpha memory card file
int nChunkSize = 0;
int nVersion = 0;
bMemCardFC1Format = true;
fread(&nChunkSize, 1, 4, fp); // Read chunk size
if (nSize < nChunkSize - 32) {
fclose(fp);
return 1;
}
fread(&nVersion, 1, 4, fp); // Read version
if (nVersion < nMinVersion) {
fclose(fp);
return 1;
}
fread(&nVersion, 1, 4, fp);
#if 0
if (nVersion < nBurnVer) {
fclose(fp);
return 1;
}
#endif
fseek(fp, 0x0C, SEEK_CUR); // Move file pointer to the start of the data block
fread(pData, 1, nChunkSize - 32, fp); // Read the data
} else {
// MAME or old FB Alpha memory card file
unsigned char* pTemp = (unsigned char*)malloc(nSize >> 1);
memset(pData, 0, nSize);
fseek(fp, 0x00, SEEK_SET);
if (pTemp) {
fread(pTemp, 1, nSize >> 1, fp);
for (int i = 1; i < nSize; i += 2) {
pData[i] = pTemp[i >> 1];
}
free(pTemp);
pTemp = NULL;
}
}
fclose(fp);
return 0;
}
static int MemCardWrite(TCHAR* szFilename, unsigned char* pData, int nSize)
{
FILE* fp = _tfopen(szFilename, _T("wb"));
if (fp == NULL) {
return 1;
}
if (bMemCardFC1Format) {
// FB Alpha memory card file
const char* szFileHeader = "FB1 "; // File identifier
const char* szChunkHeader = "FC1 "; // Chunk identifier
const int nZero = 0;
int nChunkSize = nSize + 32;
fwrite(szFileHeader, 1, 4, fp);
fwrite(szChunkHeader, 1, 4, fp);
fwrite(&nChunkSize, 1, 4, fp); // Chunk size
fwrite(&nBurnVer, 1, 4, fp); // Version of FBA this was saved from
fwrite(&nMinVersion, 1, 4, fp); // Min version of FBA data will work with
fwrite(&nZero, 1, 4, fp); // Reserved
fwrite(&nZero, 1, 4, fp); //
fwrite(&nZero, 1, 4, fp); //
fwrite(pData, 1, nSize, fp);
} else {
// MAME or old FB Alpha memory card file
unsigned char* pTemp = (unsigned char*)malloc(nSize >> 1);
if (pTemp) {
for (int i = 1; i < nSize; i += 2) {
pTemp[i >> 1] = pData[i];
}
fwrite(pTemp, 1, nSize >> 1, fp);
free(pTemp);
pTemp = NULL;
}
}
fclose(fp);
return 0;
}
static int __cdecl MemCardDoGetSize(struct BurnArea* pba)
{
nMemoryCardSize = pba->nLen;
return 0;
}
static int MemCardGetSize()
{
BurnAcb = MemCardDoGetSize;
BurnAreaScan(ACB_MEMCARD, &nMinVersion);
return 0;
}
int MemCardCreate()
{
TCHAR szFilter[1024];
int nRet;
_stprintf(szFilter, FBALoadStringEx(hAppInst, IDS_DISK_FILE_CARD, true), _T(APP_TITLE));
memcpy(szFilter + _tcslen(szFilter), _T(" (*.fc)\0*.fc\0\0"), 14 * sizeof(TCHAR));
_stprintf (szMemoryCardFile, _T("memorycard"));
MakeOfn();
ofn.lpstrTitle = FBALoadStringEx(hAppInst, IDS_MEMCARD_CREATE, true);
ofn.lpstrFilter = szFilter;
ofn.Flags |= OFN_OVERWRITEPROMPT;
int bOldPause = bRunPause;
bRunPause = 1;
nRet = GetSaveFileName(&ofn);
bRunPause = bOldPause;
if (nRet == 0) {
return 1;
}
{
unsigned char* pCard;
MemCardGetSize();
pCard = (unsigned char*)malloc(nMemoryCardSize);
memset(pCard, 0, nMemoryCardSize);
bMemCardFC1Format = true;
if (MemCardWrite(szMemoryCardFile, pCard, nMemoryCardSize)) {
return 1;
}
if (pCard) {
free(pCard);
pCard = NULL;
}
}
nMemoryCardStatus = 1;
MenuEnableItems();
return 0;
}
int MemCardSelect()
{
TCHAR szFilter[1024];
TCHAR* pszTemp = szFilter;
int nRet;
pszTemp += _stprintf(pszTemp, FBALoadStringEx(hAppInst, IDS_DISK_ALL_CARD, true));
memcpy(pszTemp, _T(" (*.fc, MEMCARD.\?\?\?)\0*.fc;MEMCARD.\?\?\?\0"), 38 * sizeof(TCHAR));
pszTemp += 38;
pszTemp += _stprintf(pszTemp, FBALoadStringEx(hAppInst, IDS_DISK_FILE_CARD, true), _T(APP_TITLE));
memcpy(pszTemp, _T(" (*.fc)\0*.fc\0"), 13 * sizeof(TCHAR));
pszTemp += 13;
pszTemp += _stprintf(pszTemp, FBALoadStringEx(hAppInst, IDS_DISK_FILE_CARD, true), _T("MAME"));
memcpy(pszTemp, _T(" (MEMCARD.\?\?\?)\0MEMCARD.\?\?\?\0\0"), 28 * sizeof(TCHAR));
MakeOfn();
ofn.lpstrTitle = FBALoadStringEx(hAppInst, IDS_MEMCARD_SELECT, true);
ofn.lpstrFilter = szFilter;
int bOldPause = bRunPause;
bRunPause = 1;
nRet = GetOpenFileName(&ofn);
bRunPause = bOldPause;
if (nRet == 0) {
return 1;
}
MemCardGetSize();
if (nMemoryCardSize <= 0) {
return 1;
}
nMemoryCardStatus = 1;
MenuEnableItems();
return 0;
}
static int __cdecl MemCardDoInsert(struct BurnArea* pba)
{
if (MemCardRead(szMemoryCardFile, (unsigned char*)pba->Data, pba->nLen)) {
return 1;
}
nMemoryCardStatus |= 2;
MenuEnableItems();
return 0;
}
int MemCardInsert()
{
if ((nMemoryCardStatus & 1) && (nMemoryCardStatus & 2) == 0) {
BurnAcb = MemCardDoInsert;
BurnAreaScan(ACB_WRITE | ACB_MEMCARD, &nMinVersion);
}
return 0;
}
static int __cdecl MemCardDoEject(struct BurnArea* pba)
{
if (MemCardWrite(szMemoryCardFile, (unsigned char*)pba->Data, pba->nLen) == 0) {
nMemoryCardStatus &= ~2;
MenuEnableItems();
return 0;
}
return 1;
}
int MemCardEject()
{
if ((nMemoryCardStatus & 1) && (nMemoryCardStatus & 2)) {
BurnAcb = MemCardDoEject;
nMinVersion = 0;
BurnAreaScan(ACB_READ | ACB_MEMCARD, &nMinVersion);
}
return 0;
}
int MemCardToggle()
{
if (nMemoryCardStatus & 1) {
if (nMemoryCardStatus & 2) {
return MemCardEject();
} else {
return MemCardInsert();
}
}
return 1;
}
| 19.764516 | 99 | 0.651053 | tt-arcade |
c3f115478d76be5a926b96e26b94ac3fae57330a | 1,027 | cpp | C++ | Dataset/Leetcode/train/13/208.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/208.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/13/208.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int XXX(string s) {
if(s.find("IV")!=s.npos)
s = s.replace(s.find("IV"),2,"a");
if (s.find("IX") != s.npos)
s = s.replace(s.find("IX"), 2, "b");
if (s.find("XL") != s.npos)
s = s.replace(s.find("XL"), 2, "c");
if (s.find("XC") != s.npos)
s = s.replace(s.find("XC"), 2, "d");
if (s.find("CD") != s.npos)
s = s.replace(s.find("CD"), 2, "e");
if (s.find("CM") != s.npos)
s = s.replace(s.find("CM"), 2, "f");
int ans = 0;
for (int i = 0; i < s.size(); i++) {
switch (s[i]) {
case 'I':
ans += 1;
break;
case 'V':
ans += 5;
break;
case 'X':
ans += 10;
break;
case 'L':
ans += 50;
break;
case 'C':
ans += 100;
break;
case 'D':
ans += 500;
break;
case 'M':
ans += 1000;
break;
case 'a':
ans += 4;
break;
case 'b':
ans += 9;
break;
case 'c':
ans += 40;
break;
case 'd':
ans += 90;
break;
case 'e':
ans += 400;
break;
case 'f':
ans += 900;
break;
}
}
return ans;
}
};
| 16.046875 | 38 | 0.447907 | kkcookies99 |
c3f73f9cba29aeb9b9bb27693805d0b332995276 | 2,933 | hpp | C++ | include/jbr/reg/var/perm/Rights.hpp | j-bruel/Register | 4fa991ed86fedb3883514031e51dc62057d0abd0 | [
"MIT"
] | null | null | null | include/jbr/reg/var/perm/Rights.hpp | j-bruel/Register | 4fa991ed86fedb3883514031e51dc62057d0abd0 | [
"MIT"
] | null | null | null | include/jbr/reg/var/perm/Rights.hpp | j-bruel/Register | 4fa991ed86fedb3883514031e51dc62057d0abd0 | [
"MIT"
] | 1 | 2019-05-06T14:12:44.000Z | 2019-05-06T14:12:44.000Z | //!
//! @file jbr/reg/var/perm/Rights.hpp
//! @author jbruel
//! @date 30/07/19
//!
#ifndef JBR_CREGISTER_REGISTER_VAR_PERM_RIGHTS_HPP
# define JBR_CREGISTER_REGISTER_VAR_PERM_RIGHTS_HPP
# include <jbr/reg/Permission.hpp>
//!
//! @namespace jbr::reg::var::perm
//!
namespace jbr::reg::var::perm
{
//!
//! @struct Rights
//! @brief All variables rights.
//!
struct Rights final : public jbr::reg::Permission
{
bool mUpdate; //!< Allow to update a variable.
bool mRename; //!< Allow to rename a variable.
bool mCopy; //!< Allow to copy a variable.
bool mRemove; //!< Allow to remove a variable.
//!
//! @brief Structure initializer. All rights are true by default.
//!
Rights() : jbr::reg::Permission(), mUpdate(true), mRename(true), mCopy(true), mRemove(true) {}
//!
//! @brief Structure initializer with custom rights initialization.
//! @param rd Reading rights.
//! @param wr Writing rights.
//! @param up Allow to update a variable.
//! @param rn Allow to rename a variable.
//! @param cp Allow to copy a variable.
//! @param rm Allow to remove a variable.
//!
explicit Rights(bool rd, bool wr, bool up, bool rn, bool cp, bool rm) : jbr::reg::Permission(rd, wr), mUpdate(up),
mRename(rn), mCopy(cp), mRemove(rm) {}
//!
//! @brief Equal operator overload.
//! @param rights New rights to overload.
//! @return New rights structure.
//!
Rights &operator=(const jbr::reg::var::perm::Rights &rights) noexcept
{
mRead = rights.mRead;
mWrite = rights.mWrite;
mUpdate = rights.mUpdate;
mRename = rights.mRename;
mCopy = rights.mCopy;
mRemove = rights.mRemove;
return (*this);
}
//!
//! @brief Equality overload operator.
//! @param rights Rights to check.
//! @return Status if rights are equals.
//!
inline bool operator==(const jbr::reg::var::perm::Rights &rights) noexcept { return (mRead == rights.mRead &&
mWrite == rights.mWrite &&
mUpdate == rights.mUpdate &&
mRename == rights.mRename &&
mCopy == rights.mCopy &&
mRemove == rights.mRemove); }
};
}
#endif //JBR_CREGISTER_REGISTER_VAR_PERM_RIGHTS_HPP
| 38.592105 | 122 | 0.475963 | j-bruel |
c3fa7a9f74907ae5ec230fd9742c729e637b4c31 | 446 | cpp | C++ | solutions/leetcode/944. Delete Columns to Make Sorted.cpp | MohanedAshraf/competitive-programming | 234dc6113b39462c64a2719cd1071f3d99655508 | [
"MIT"
] | 1 | 2021-08-12T14:53:37.000Z | 2021-08-12T14:53:37.000Z | solutions/leetcode/944. Delete Columns to Make Sorted.cpp | MohanedAshraf/competitive-programming | 234dc6113b39462c64a2719cd1071f3d99655508 | [
"MIT"
] | null | null | null | solutions/leetcode/944. Delete Columns to Make Sorted.cpp | MohanedAshraf/competitive-programming | 234dc6113b39462c64a2719cd1071f3d99655508 | [
"MIT"
] | null | null | null | static int __=[](){std::ios::sync_with_stdio(false);return 1000;}();
class Solution {
public:
int minDeletionSize(vector<string>& strs) {
int c = 0 , n = strs.size() , m = strs[0].size() ;
for(int i= 0 ; i<m ; i++)
for(int j = 0; j<n-1 ; j++ )
if(strs[j][i] > strs[j+1][i]){
c++;
break;
}
return c ;
}
};
| 24.777778 | 68 | 0.392377 | MohanedAshraf |
c3ff4561c82896407cd33ef4b603f6fbcf689245 | 601 | cc | C++ | pressureCtrlAlg/bagSimModel.cc | gerth2/piUserInterface | 9b79cbe71654c404894eac511e54581d4d9cf8ab | [
"MIT"
] | null | null | null | pressureCtrlAlg/bagSimModel.cc | gerth2/piUserInterface | 9b79cbe71654c404894eac511e54581d4d9cf8ab | [
"MIT"
] | null | null | null | pressureCtrlAlg/bagSimModel.cc | gerth2/piUserInterface | 9b79cbe71654c404894eac511e54581d4d9cf8ab | [
"MIT"
] | null | null | null | #include "bagSimModel.h"
#define Ts 0.01
#define PWM_TO_POS_SCALE 0.01
#define BAG_MAX_VOL 1.0
#define BAG_MIN_VOL 0.25
//Expected flow vs. Pressure
// PSI 2 5 10 15 20 25 30
// kPa 13.7 34.5 68.9 103 138 172 206
// Flow (CFM) 40.5 63.5 79.6 108 126 144 162
BagSimModel::BagSimModel(double Ts_in){
armPctCompression = 0;
}
double BagSimModel::update(double motorPWM){
armPctCompression += motorPWM * Ts * PWM_TO_POS_SCALE;
double bagVol = (BAG_MAX_VOL - BAG_MIN_VOL) * armPctCompression + BAG_MIN_VOL;
} | 22.259259 | 83 | 0.625624 | gerth2 |
7f010c257f9e8d50c312d8d5dd31661136ac1ee7 | 243 | cpp | C++ | Basic/Check Whether a Number is Even or Odd/SolutionByRegi.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 2 | 2019-09-21T21:18:13.000Z | 2019-09-28T14:26:56.000Z | Basic/Check Whether a Number is Even or Odd/SolutionByRegi.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 14 | 2019-09-23T07:25:27.000Z | 2019-09-30T09:35:01.000Z | Basic/Check Whether a Number is Even or Odd/SolutionByRegi.cpp | Mdanish777/Programmers-Community | b5ca9582fc1cd4337baa7077ff62130a1052583f | [
"MIT"
] | 13 | 2019-09-21T16:43:56.000Z | 2019-09-30T15:28:33.000Z | #include <iostream>
#include <string>
bool IsEven(int num)
{
return (num % 2 == 0);
}
int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << num << " is " << (IsEven(num) ? "Even" : "Odd") << "\n";
}
| 16.2 | 71 | 0.514403 | Mdanish777 |
7f016362cc0d9f086ec0a4838d2dbe0579de879f | 905 | cpp | C++ | Week13/natsia_and_good_arrays.cpp | princesinghtomar/Competitive-Programming | a0df818dfa56267fdde59bd1862d0b78f6e069c4 | [
"MIT"
] | 3 | 2020-11-11T13:45:40.000Z | 2021-07-20T11:53:34.000Z | Week13/natsia_and_good_arrays.cpp | princesinghtomar/Competitive-Programming | a0df818dfa56267fdde59bd1862d0b78f6e069c4 | [
"MIT"
] | 11 | 2020-10-03T14:26:35.000Z | 2021-10-30T15:26:40.000Z | Week13/natsia_and_good_arrays.cpp | princesinghtomar/Competitive-Programming | a0df818dfa56267fdde59bd1862d0b78f6e069c4 | [
"MIT"
] | 12 | 2020-05-12T08:39:54.000Z | 2021-10-30T14:56:27.000Z | #include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
int n;
cin >> n;
int sindex = 0,k=0;
long int arr[n];
long int brr[n][4];
for(int i=0;i<n;i++){
cin>>arr[i];
if(arr[i] < arr[sindex]){
sindex = i;
}
}
for(int i = 0;i < n; i++){
if(i == sindex){
continue;
}
brr[k][0] = sindex;
brr[k][1] = i;
brr[k][2] = arr[sindex];
brr[k][3] = arr[sindex] + abs(i-sindex);
k++;
}
cout<<k<<endl;
if(k>0){
for(int i=0;i<k;i++){
cout<<brr[i][0]+1 << " " << brr[i][1]+1 << " " << brr[i][2] << " " << brr[i][3] << endl;
}
}
}
} | 23.815789 | 104 | 0.345856 | princesinghtomar |
7f074d834191471a61d7643bb518b3420de42043 | 10,520 | cpp | C++ | qtdeclarative/src/quick/designer/qquickdesignercustomobjectdata.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtdeclarative/src/quick/designer/qquickdesignercustomobjectdata.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtdeclarative/src/quick/designer/qquickdesignercustomobjectdata.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickdesignersupportmetainfo_p.h"
#include "qquickdesignersupportproperties_p.h"
#include "qquickdesignercustomobjectdata_p.h"
#include <QGlobalStatic>
#include <QQmlContext>
#include <QQmlEngine>
#include <private/qqmlbinding_p.h>
QT_BEGIN_NAMESPACE
typedef QHash<QObject*, QQuickDesignerCustomObjectData*> CustomObjectDataHash;
Q_GLOBAL_STATIC(CustomObjectDataHash, s_designerObjectToDataHash)
struct HandleDestroyedFunctor {
QQuickDesignerCustomObjectData *data;
void operator()() { data->handleDestroyed(); }
};
QQuickDesignerCustomObjectData::QQuickDesignerCustomObjectData(QObject *object)
: m_object(object)
{
if (object) {
populateResetHashes();
s_designerObjectToDataHash()->insert(object, this);
HandleDestroyedFunctor functor;
functor.data = this;
QObject::connect(object, &QObject::destroyed, functor);
}
}
void QQuickDesignerCustomObjectData::registerData(QObject *object)
{
new QQuickDesignerCustomObjectData(object);
}
QQuickDesignerCustomObjectData *QQuickDesignerCustomObjectData::get(QObject *object)
{
return s_designerObjectToDataHash()->value(object);
}
QVariant QQuickDesignerCustomObjectData::getResetValue(QObject *object, const QQuickDesignerSupport::PropertyName &propertyName)
{
QQuickDesignerCustomObjectData* data = get(object);
if (data)
return data->getResetValue(propertyName);
return QVariant();
}
void QQuickDesignerCustomObjectData::doResetProperty(QObject *object, QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName)
{
QQuickDesignerCustomObjectData* data = get(object);
if (data)
data->doResetProperty(context, propertyName);
}
bool QQuickDesignerCustomObjectData::hasValidResetBinding(QObject *object, const QQuickDesignerSupport::PropertyName &propertyName)
{
QQuickDesignerCustomObjectData* data = get(object);
if (data)
return data->hasValidResetBinding(propertyName);
return false;
}
bool QQuickDesignerCustomObjectData::hasBindingForProperty(QObject *object,
QQmlContext *context,
const QQuickDesignerSupport::PropertyName &propertyName,
bool *hasChanged)
{
QQuickDesignerCustomObjectData* data = get(object);
if (data)
return data->hasBindingForProperty(context, propertyName, hasChanged);
return false;
}
void QQuickDesignerCustomObjectData::setPropertyBinding(QObject *object,
QQmlContext *context,
const QQuickDesignerSupport::PropertyName &propertyName,
const QString &expression)
{
QQuickDesignerCustomObjectData* data = get(object);
if (data)
data->setPropertyBinding(context, propertyName, expression);
}
void QQuickDesignerCustomObjectData::keepBindingFromGettingDeleted(QObject *object,
QQmlContext *context,
const QQuickDesignerSupport::PropertyName &propertyName)
{
QQuickDesignerCustomObjectData* data = get(object);
if (data)
data->keepBindingFromGettingDeleted(context, propertyName);
}
void QQuickDesignerCustomObjectData::populateResetHashes()
{
QQuickDesignerSupport::PropertyNameList propertyNameList =
QQuickDesignerSupportProperties::propertyNameListForWritableProperties(object());
Q_FOREACH (const QQuickDesignerSupport::PropertyName &propertyName, propertyNameList) {
QQmlProperty property(object(), QString::fromUtf8(propertyName), QQmlEngine::contextForObject(object()));
QQmlAbstractBinding::Ptr binding = QQmlAbstractBinding::Ptr(QQmlPropertyPrivate::binding(property));
if (binding) {
m_resetBindingHash.insert(propertyName, binding);
} else if (property.isWritable()) {
m_resetValueHash.insert(propertyName, property.read());
}
}
}
QObject *QQuickDesignerCustomObjectData::object() const
{
return m_object;
}
QVariant QQuickDesignerCustomObjectData::getResetValue(const QQuickDesignerSupport::PropertyName &propertyName) const
{
return m_resetValueHash.value(propertyName);
}
void QQuickDesignerCustomObjectData::doResetProperty(QQmlContext *context, const QQuickDesignerSupport::PropertyName &propertyName)
{
QQmlProperty property(object(), QString::fromUtf8(propertyName), context);
if (!property.isValid())
return;
QQmlAbstractBinding *binding = QQmlPropertyPrivate::binding(property);
if (binding && !(hasValidResetBinding(propertyName) && getResetBinding(propertyName) == binding)) {
binding->setEnabled(false, 0);
}
if (hasValidResetBinding(propertyName)) {
QQmlAbstractBinding *binding = getResetBinding(propertyName);
#if defined(QT_NO_DYNAMIC_CAST)
QQmlBinding *qmlBinding = static_cast<QQmlBinding*>(binding);
#else
QQmlBinding *qmlBinding = dynamic_cast<QQmlBinding*>(binding);
#endif
if (qmlBinding)
qmlBinding->setTarget(property);
QQmlPropertyPrivate::setBinding(binding, QQmlPropertyPrivate::None, QQmlPropertyPrivate::DontRemoveBinding);
if (qmlBinding)
qmlBinding->update();
} else if (property.isResettable()) {
property.reset();
} else if (property.propertyTypeCategory() == QQmlProperty::List) {
QQmlListReference list = qvariant_cast<QQmlListReference>(property.read());
if (!QQuickDesignerSupportProperties::hasFullImplementedListInterface(list)) {
qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!";
return;
}
list.clear();
} else if (property.isWritable()) {
if (property.read() == getResetValue(propertyName))
return;
property.write(getResetValue(propertyName));
}
}
bool QQuickDesignerCustomObjectData::hasValidResetBinding(const QQuickDesignerSupport::PropertyName &propertyName) const
{
return m_resetBindingHash.contains(propertyName) && m_resetBindingHash.value(propertyName).data();
}
QQmlAbstractBinding *QQuickDesignerCustomObjectData::getResetBinding(const QQuickDesignerSupport::PropertyName &propertyName) const
{
return m_resetBindingHash.value(propertyName).data();
}
bool QQuickDesignerCustomObjectData::hasBindingForProperty(QQmlContext *context,
const QQuickDesignerSupport::PropertyName &propertyName,
bool *hasChanged) const
{
if (QQuickDesignerSupportProperties::isPropertyBlackListed(propertyName))
return false;
QQmlProperty property(object(), QString::fromUtf8(propertyName), context);
bool hasBinding = QQmlPropertyPrivate::binding(property);
if (hasChanged) {
*hasChanged = hasBinding != m_hasBindingHash.value(propertyName, false);
if (*hasChanged)
m_hasBindingHash.insert(propertyName, hasBinding);
}
return QQmlPropertyPrivate::binding(property);
}
void QQuickDesignerCustomObjectData::setPropertyBinding(QQmlContext *context,
const QQuickDesignerSupport::PropertyName &propertyName,
const QString &expression)
{
QQmlProperty property(object(), QString::fromUtf8(propertyName), context);
if (!property.isValid())
return;
if (property.isProperty()) {
QQmlBinding *binding = new QQmlBinding(expression, object(), context);
binding->setTarget(property);
binding->setNotifyOnValueChanged(true);
QQmlPropertyPrivate::setBinding(binding, QQmlPropertyPrivate::None, QQmlPropertyPrivate::DontRemoveBinding);
//Refcounting is taking take care of deletion
binding->update();
if (binding->hasError()) {
if (property.property().userType() == QVariant::String)
property.write(QVariant(QLatin1Char('#') + expression + QLatin1Char('#')));
}
} else {
qWarning() << Q_FUNC_INFO << ": Cannot set binding for property" << propertyName << ": property is unknown for type";
}
}
void QQuickDesignerCustomObjectData::keepBindingFromGettingDeleted(QQmlContext *context,
const QQuickDesignerSupport::PropertyName &propertyName)
{
//Refcounting is taking care
Q_UNUSED(context)
Q_UNUSED(propertyName)
}
void QQuickDesignerCustomObjectData::handleDestroyed()
{
s_designerObjectToDataHash()->remove(m_object);
delete this;
}
QT_END_NAMESPACE
| 36.655052 | 164 | 0.684411 | wgnet |
7f0adede716cb763e559b3e8d4533efb7a003b74 | 524 | cpp | C++ | Payoffs.cpp | ThibaultLacharme/tddc_pde_solver | c735ff4aff8a9cba33ed86c59b1fcd569745b74f | [
"BSD-3-Clause"
] | null | null | null | Payoffs.cpp | ThibaultLacharme/tddc_pde_solver | c735ff4aff8a9cba33ed86c59b1fcd569745b74f | [
"BSD-3-Clause"
] | null | null | null | Payoffs.cpp | ThibaultLacharme/tddc_pde_solver | c735ff4aff8a9cba33ed86c59b1fcd569745b74f | [
"BSD-3-Clause"
] | null | null | null | #include "Payoffs.hpp"
#include <algorithm>
namespace dauphine
{
Payoffs::Payoffs()
{
}
// For other products add the corresponding function at maturity, if there are more arguments than the spot and strike adjust the function in Boundaries too
double Payoffs::call(double spot, double strike)
{
return std::max(spot - strike, 0.);
};
double Payoffs::put(double spot, double strike)
{
return std::max(strike - spot, 0.);
};
Payoffs::~Payoffs()
{
}
}
| 22.782609 | 160 | 0.627863 | ThibaultLacharme |
7f0baa544b7b060deb320c8cf061d5094f8be324 | 1,026 | cpp | C++ | src/tools/character_padding.cpp | bidfx/bidfx-api-cpp | 9f178178a90355f57477f27277f470c910263696 | [
"Apache-2.0"
] | 5 | 2020-06-13T08:26:53.000Z | 2022-02-25T19:32:55.000Z | src/tools/character_padding.cpp | bidfx/bidfx-api-cpp | 9f178178a90355f57477f27277f470c910263696 | [
"Apache-2.0"
] | 2 | 2020-03-08T16:07:46.000Z | 2020-04-15T08:26:08.000Z | src/tools/character_padding.cpp | bidfx/bidfx-api-cpp | 9f178178a90355f57477f27277f470c910263696 | [
"Apache-2.0"
] | 1 | 2020-06-13T10:52:46.000Z | 2020-06-13T10:52:46.000Z | /** Copyright 2019 BidFX
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 <sstream>
#include "character_padding.h"
namespace bidfx_public_api::tools
{
CharacterPadding::CharacterPadding(char pad_char, unsigned int len) : pad_char_{pad_char}, length_{len < 0 ? 0 : len}
{
std::stringstream ss;
for (int i = 0; i < length_; i++)
{
ss << pad_char_;
}
constructed_padding_ = ss.str();
}
std::string CharacterPadding::ToString()
{
return constructed_padding_;
}
} | 27 | 117 | 0.703704 | bidfx |
7f17e6c64789dd102403d3119f4f4374d892b6c0 | 250 | cpp | C++ | Programs/14 Recursion/basics/power.cpp | Lord-Lava/DSA-CPP-Apna-College | 077350c2aa900bb0cdb137ece2b95be58ccd76a8 | [
"MIT"
] | 5 | 2021-04-04T18:39:14.000Z | 2021-12-18T09:31:55.000Z | Programs/14 Recursion/basics/power.cpp | Lord-Lava/DSA-CPP-Apna-College | 077350c2aa900bb0cdb137ece2b95be58ccd76a8 | [
"MIT"
] | null | null | null | Programs/14 Recursion/basics/power.cpp | Lord-Lava/DSA-CPP-Apna-College | 077350c2aa900bb0cdb137ece2b95be58ccd76a8 | [
"MIT"
] | 1 | 2021-09-26T11:01:26.000Z | 2021-09-26T11:01:26.000Z | #include<iostream>
using namespace std;
int power(int n, int p){
if(p==0){
return 1;
}
int prevPower= power(n,p-1);
return n*prevPower;
}
int main(){
int n,p;
cin>>n>>p;
cout<<power(n,p)<<endl;
return 0;
} | 12.5 | 32 | 0.536 | Lord-Lava |
7f18fbfcc1328db12e9a61606cc699f7a6e45aa8 | 1,909 | cpp | C++ | DirectXGame/DirectXCore/Sprite.cpp | nguyenlamlll/DirectX-11-Game | 560ae6d9b44cef7882c5fc93192160fae7da791d | [
"MIT"
] | 2 | 2018-09-13T06:15:57.000Z | 2021-09-08T02:32:11.000Z | DirectXGame/DirectXCore/Sprite.cpp | nguyenlamlll/DirectX-11-Game | 560ae6d9b44cef7882c5fc93192160fae7da791d | [
"MIT"
] | 17 | 2018-09-11T09:37:22.000Z | 2018-12-04T07:56:49.000Z | DirectXGame/DirectXCore/Sprite.cpp | nguyenlamlll/DirectX-11-Game | 560ae6d9b44cef7882c5fc93192160fae7da791d | [
"MIT"
] | 1 | 2021-11-29T05:12:48.000Z | 2021-11-29T05:12:48.000Z | #include "stdafx.h"
#include "Sprite.h"
using Microsoft::WRL::ComPtr;
using namespace DirectXCore;
Sprite::Sprite()
{
}
Sprite::Sprite(DirectXCore::DeviceResources * _deviceResource, const wchar_t * _charPath, float _scale)
{
//pivot.x = float(spriteDesc.Width / 2);
pivot.x = 0;
//pivot.y = float(spriteDesc.Height / 2);
pivot.y = 0;
//transform = new Transform(Vector3(_deviceResource->GetOutputSize().right / 2, _deviceResource->GetOutputSize().bottom / 2, 0), Vector3(0, 0, 0), Vector3(1, 1, 1));
//spriterect = new RECT();
//transform->SetRotation(Vector3(0,0,0));
//transform->SetScale(SimpleMath::Vector3(_scale, _scale, 1));
//if (!GetComponent<Renderer>()) {
// AddComponent<Renderer>(new Renderer(_deviceResource, _charPath, this));
// SetSpriteRect(GetComponent<Renderer>()->GetRECT());
// spriterect = GetComponent<Renderer>()->GetRECT();
//}
//transform->SetScreenScale(SimpleMath::Vector3(spriterect->right, spriterect->bottom, 1));
}
Sprite::~Sprite()
{
}
void DirectXCore::Sprite::LoadTexture(const wchar_t * _charPath)
{
}
void Sprite::Update(float _deltaTime)
{
/*for (size_t i = 0; i < componentList->size(); i++)
{
componentList->at(i)->Update();
}
Collider *collider = GetComponent<Collider>();
if (collider)
{
collider->SetColliderScale(Vector3(transform->GetScale().x * (spriterect->right - spriterect->left), transform->GetScale().y * (spriterect->bottom - spriterect->top), 1));
collider->SetColliderPosition(transform->GetPosition());
}*/
}
void Sprite::Render()
{
/*for (size_t i = 0; i < componentList->size(); i++)
{
componentList->at(i)->Render();
}*/
}
void Sprite::SetSpriteRect(RECT * _newSpriteRect)
{
//GetComponent<Renderer>()->SetRECT(*_newSpriteRect);
spriterect->top = _newSpriteRect->top;
spriterect->bottom = _newSpriteRect->bottom;
spriterect->left = _newSpriteRect->left;
spriterect->right = _newSpriteRect->right;
}
| 26.887324 | 173 | 0.698271 | nguyenlamlll |
7f191646403c7c058cf767d25184395b8d0a7d88 | 6,270 | cpp | C++ | build/cpp/src/verb/core/SurfacePoint.cpp | harmanpa/verb | f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9 | [
"MIT"
] | null | null | null | build/cpp/src/verb/core/SurfacePoint.cpp | harmanpa/verb | f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9 | [
"MIT"
] | null | null | null | build/cpp/src/verb/core/SurfacePoint.cpp | harmanpa/verb | f18a6db8d9e47b65d7cbf2d954a9dc42f611abd9 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.1.4
#include <hxcpp.h>
#ifndef INCLUDED_verb_core_SurfacePoint
#include <verb/core/SurfacePoint.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_959611cb896c5e6e_146_new,"verb.core.SurfacePoint","new",0xb12daa55,"verb.core.SurfacePoint.new","verb/core/Intersections.hx",146,0x2e2a0454)
HX_LOCAL_STACK_FRAME(_hx_pos_959611cb896c5e6e_155_fromUv,"verb.core.SurfacePoint","fromUv",0x63cbab96,"verb.core.SurfacePoint.fromUv","verb/core/Intersections.hx",155,0x2e2a0454)
namespace verb{
namespace core{
void SurfacePoint_obj::__construct(::Array< Float > point,::Array< Float > normal,::Array< Float > uv,::hx::Null< int > __o_id,::hx::Null< bool > __o_degen){
int id = __o_id.Default(-1);
bool degen = __o_degen.Default(false);
HX_STACKFRAME(&_hx_pos_959611cb896c5e6e_146_new)
HXLINE( 147) this->uv = uv;
HXLINE( 148) this->point = point;
HXLINE( 149) this->normal = normal;
HXLINE( 150) this->id = id;
HXLINE( 151) this->degen = degen;
}
Dynamic SurfacePoint_obj::__CreateEmpty() { return new SurfacePoint_obj; }
void *SurfacePoint_obj::_hx_vtable = 0;
Dynamic SurfacePoint_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< SurfacePoint_obj > _hx_result = new SurfacePoint_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3],inArgs[4]);
return _hx_result;
}
bool SurfacePoint_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x16f19b2d;
}
::verb::core::SurfacePoint SurfacePoint_obj::fromUv(Float u,Float v){
HX_GC_STACKFRAME(&_hx_pos_959611cb896c5e6e_155_fromUv)
HXDLIN( 155) return ::verb::core::SurfacePoint_obj::__alloc( HX_CTX ,null(),null(),::Array_obj< Float >::__new(2)->init(0,u)->init(1,v),null(),null());
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(SurfacePoint_obj,fromUv,return )
SurfacePoint_obj::SurfacePoint_obj()
{
}
void SurfacePoint_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(SurfacePoint);
HX_MARK_MEMBER_NAME(uv,"uv");
HX_MARK_MEMBER_NAME(point,"point");
HX_MARK_MEMBER_NAME(normal,"normal");
HX_MARK_MEMBER_NAME(id,"id");
HX_MARK_MEMBER_NAME(degen,"degen");
HX_MARK_END_CLASS();
}
void SurfacePoint_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(uv,"uv");
HX_VISIT_MEMBER_NAME(point,"point");
HX_VISIT_MEMBER_NAME(normal,"normal");
HX_VISIT_MEMBER_NAME(id,"id");
HX_VISIT_MEMBER_NAME(degen,"degen");
}
::hx::Val SurfacePoint_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 2:
if (HX_FIELD_EQ(inName,"uv") ) { return ::hx::Val( uv ); }
if (HX_FIELD_EQ(inName,"id") ) { return ::hx::Val( id ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"point") ) { return ::hx::Val( point ); }
if (HX_FIELD_EQ(inName,"degen") ) { return ::hx::Val( degen ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"normal") ) { return ::hx::Val( normal ); }
}
return super::__Field(inName,inCallProp);
}
bool SurfacePoint_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 6:
if (HX_FIELD_EQ(inName,"fromUv") ) { outValue = fromUv_dyn(); return true; }
}
return false;
}
::hx::Val SurfacePoint_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 2:
if (HX_FIELD_EQ(inName,"uv") ) { uv=inValue.Cast< ::Array< Float > >(); return inValue; }
if (HX_FIELD_EQ(inName,"id") ) { id=inValue.Cast< int >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"point") ) { point=inValue.Cast< ::Array< Float > >(); return inValue; }
if (HX_FIELD_EQ(inName,"degen") ) { degen=inValue.Cast< bool >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"normal") ) { normal=inValue.Cast< ::Array< Float > >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void SurfacePoint_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("uv",61,66,00,00));
outFields->push(HX_("point",50,b4,8f,c6));
outFields->push(HX_("normal",27,72,69,30));
outFields->push(HX_("id",db,5b,00,00));
outFields->push(HX_("degen",af,0f,23,d7));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo SurfacePoint_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::Array< Float > */ ,(int)offsetof(SurfacePoint_obj,uv),HX_("uv",61,66,00,00)},
{::hx::fsObject /* ::Array< Float > */ ,(int)offsetof(SurfacePoint_obj,point),HX_("point",50,b4,8f,c6)},
{::hx::fsObject /* ::Array< Float > */ ,(int)offsetof(SurfacePoint_obj,normal),HX_("normal",27,72,69,30)},
{::hx::fsInt,(int)offsetof(SurfacePoint_obj,id),HX_("id",db,5b,00,00)},
{::hx::fsBool,(int)offsetof(SurfacePoint_obj,degen),HX_("degen",af,0f,23,d7)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *SurfacePoint_obj_sStaticStorageInfo = 0;
#endif
static ::String SurfacePoint_obj_sMemberFields[] = {
HX_("uv",61,66,00,00),
HX_("point",50,b4,8f,c6),
HX_("normal",27,72,69,30),
HX_("id",db,5b,00,00),
HX_("degen",af,0f,23,d7),
::String(null()) };
::hx::Class SurfacePoint_obj::__mClass;
static ::String SurfacePoint_obj_sStaticFields[] = {
HX_("fromUv",6b,9e,c6,b5),
::String(null())
};
void SurfacePoint_obj::__register()
{
SurfacePoint_obj _hx_dummy;
SurfacePoint_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("verb.core.SurfacePoint",e3,db,72,fc);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &SurfacePoint_obj::__GetStatic;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(SurfacePoint_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(SurfacePoint_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< SurfacePoint_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = SurfacePoint_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = SurfacePoint_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace verb
} // end namespace core
| 35.423729 | 178 | 0.713397 | harmanpa |
7f1be9275d460561032e326da3d1e606d6dc1290 | 967 | cpp | C++ | src/Calibrate.cpp | kontramind/zivid-python | b18582c0cdef261d42fb737c7eee71e350048569 | [
"BSD-3-Clause"
] | null | null | null | src/Calibrate.cpp | kontramind/zivid-python | b18582c0cdef261d42fb737c7eee71e350048569 | [
"BSD-3-Clause"
] | null | null | null | src/Calibrate.cpp | kontramind/zivid-python | b18582c0cdef261d42fb737c7eee71e350048569 | [
"BSD-3-Clause"
] | null | null | null | #include <Zivid/HandEye/Calibrate.h>
#include <ZividPython/Calibrate.h>
#include <ZividPython/CalibrationResidual.h>
#include <ZividPython/Matrix.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
namespace ZividPython
{
void wrapClass(pybind11::class_<Zivid::HandEye::CalibrationOutput> pyClass)
{
pyClass.def("valid", &Zivid::HandEye::CalibrationOutput::valid)
.def("handEyeTransform",
[](const Zivid::HandEye::CalibrationOutput &calibrationOutput) {
return Conversion::toPy(calibrationOutput.handEyeTransform());
})
.def("perPoseCalibrationResiduals", &Zivid::HandEye::CalibrationOutput::perPoseCalibrationResiduals);
}
void wrapClass(pybind11::class_<Zivid::HandEye::CalibrationInput> pyClass)
{
pyClass.def(py::init<Zivid::HandEye::Pose, Zivid::HandEye::DetectionResult>());
}
} // namespace ZividPython
| 33.344828 | 113 | 0.68666 | kontramind |
7f1e039ff387c51c40d914d25c573aef36a51a2b | 24,259 | cpp | C++ | Source/AllProjects/CQCIGKit/CQCIGKit_DriverClient.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/CQCIGKit/CQCIGKit_DriverClient.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/CQCIGKit/CQCIGKit_DriverClient.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCIGKit_DriverClient.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 11/16/2001
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// Implements the standard CQC client side driver window, from which all
// client drivers derive.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCIGKit_.hpp"
// ----------------------------------------------------------------------------
// Do our RTTI macros
// ----------------------------------------------------------------------------
RTTIDecls(TCQCDriverClient,TGenericWnd)
// ---------------------------------------------------------------------------
// CLASS: TCQCDriverClient
// PREFIX: wnd
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TCQCDriverClient: Constructors and Destructor
// ---------------------------------------------------------------------------
TCQCDriverClient::TCQCDriverClient( const TCQCDriverObjCfg& cqcdcThis
, const TString& strDriverClass
, const tCQCKit::EActLevels eActivityLevel
, const TCQCUserCtx& cuctxToUse) :
TGenericWnd()
, m_bCleanupDone(kCIDLib::False)
, m_bFirstTimer(kCIDLib::True)
, m_c4PollChanges(0)
, m_cuctxToUse(cuctxToUse)
, m_eActivityLevel(eActivityLevel)
, m_eConnState(tCQCGKit::EConnStates::SrvOffline)
, m_ePrevState(tCQCGKit::EConnStates::SrvOffline)
, m_cqcdcThis(cqcdcThis)
, m_thrPoll
(
facCIDLib().strNextThreadName(strDriverClass + TString(L"Poll"))
, TMemberFunc<TCQCDriverClient>(this, &TCQCDriverClient::ePollThread)
)
, m_tmidUpdate(kCIDCtrls::tmidInvalid)
{
}
TCQCDriverClient::~TCQCDriverClient()
{
}
// ---------------------------------------------------------------------------
// TCQCDriverClient: Public, non-virtual methods
// ---------------------------------------------------------------------------
const TCQCDriverObjCfg& TCQCDriverClient::cqcdcThis() const
{
return m_cqcdcThis;
}
const TCQCUserCtx& TCQCDriverClient::cuctxToUse() const
{
return m_cuctxToUse;
}
tCIDLib::TVoid
TCQCDriverClient::CreateClDrvWnd(const TWindow& wndParent
, const TArea& areaInit
, const tCIDCtrls::TWndId widToUse)
{
//
// And now call down to create the window. We are initially invisible and our parent
// will show us once he's got us sized/positioned appropriately.
//
TWindow::CreateWnd
(
wndParent.hwndSafe()
, kCIDCtrls::pszCustClass
, L""
, areaInit
, tCIDCtrls::EWndStyles::ClippingChild
, tCIDCtrls::EExWndStyles::ControlParent
, widToUse
);
}
tCQCGKit::EConnStates TCQCDriverClient::eConnState() const
{
return m_eConnState;
}
// Just a convenience wrapper that we pass on to the user context
tCQCKit::EUserRoles TCQCDriverClient::eUserRole() const
{
return m_cuctxToUse.eUserRole();
}
tCQCKit::TCQCSrvProxy& TCQCDriverClient::orbcServer()
{
return m_orbcServer;
}
TMutex* TCQCDriverClient::pmtxSync() const
{
return &m_mtxSync;
}
const TCQCSecToken& TCQCDriverClient::sectUser() const
{
return m_cuctxToUse.sectUser();
}
const TString& TCQCDriverClient::strMoniker() const
{
return m_cqcdcThis.strMoniker();
}
// The client program will call this after the windows are all created and ready
tCIDLib::TVoid TCQCDriverClient::StartDriver()
{
// If we have already been run and stopped, then that's an error
if (m_bCleanupDone)
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kIGKitErrs::errcDrv_AlreadyStopped
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
, m_cqcdcThis.strMoniker()
);
}
// Start the poll thread
m_thrPoll.Start();
//
// Start the update timer. Initially we set a kind of long time, to
// give the client time to come up and get displayed. The first time
// the timer gets called, he will reset the period to the appropriate
// period.
//
// <TBD> Later on, we can use the m_eActivityLevel setting to adjust
// these to optimize overhead to match the rate that the device's data
// is likely to change.
//
m_tmidUpdate = tmidStartTimer(3000);
}
//
// The client program will call this top stop the driver (before it destroys our
// parent window of course!)
//
tCIDLib::TVoid TCQCDriverClient::StopDriver()
{
// Stop our update time if running
try
{
if (m_tmidUpdate != kCIDCtrls::tmidInvalid)
{
StopTimer(m_tmidUpdate);
m_tmidUpdate = kCIDCtrls::tmidInvalid;
}
}
catch(TError& errToCatch)
{
if (facCQCGKit().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_StopTimer
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
catch(...)
{
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_StopTimer
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
// Stop the poll thread
try
{
if (m_thrPoll.bIsRunning())
{
m_thrPoll.ReqShutdownSync(10000);
m_thrPoll.eWaitForDeath(5000);
}
}
catch(TError& errToCatch)
{
if (facCQCGKit().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_StopClientDrvPollThr
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
catch(...)
{
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_StopClientDrvPollThr
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
// Let the derived class do its cleanup
try
{
if (!m_bCleanupDone)
{
m_bCleanupDone = kCIDLib::True;
DoCleanup();
}
}
catch(TError& errToCatch)
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
// Drop the server admin client proxy, if we have one
try
{
m_orbcServer.DropRef();
}
catch(TError& errToCatch)
{
if (facCQCGKit().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_CleanupProxy
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
catch(...)
{
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_CleanupProxy
, tCIDLib::ESeverities::Status
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
}
// ---------------------------------------------------------------------------
// TCQCDriverClient: Protected, inherited methods
// ---------------------------------------------------------------------------
// Do it all in the paint, where we are clipped to our children
tCIDLib::TBoolean TCQCDriverClient::bEraseBgn(TGraphDrawDev&)
{
return kCIDLib::True;
}
tCIDLib::TBoolean TCQCDriverClient::bPaint(TGraphDrawDev& gdevToUse, const TArea& areaUpdate)
{
gdevToUse.Fill(areaUpdate, rgbBgnFill());
return kCIDLib::True;
}
tCIDLib::TVoid TCQCDriverClient::Destroyed()
{
// Just in case...
StopDriver();
TParent::Destroyed();
}
tCIDLib::TVoid TCQCDriverClient::Timer(const tCIDCtrls::TTimerId tmidToDo)
{
// If the first timer, reset the period now
if (m_bFirstTimer)
{
m_bFirstTimer = kCIDLib::False;
ResetTimer(m_tmidUpdate, 1000);
}
//
// We have to lock out the poll thread during this. Use the form that let's us
// conditionally lock. If the poll thread should hang up for some reason, we
// don't want to lock up the interface. We use a short timeout so that, if the
// poll thread is straining because the remote servers are down, we won't make
// the interface overly spongy.
//
TLocker lockrSync(&m_mtxSync, kCIDLib::False);
if (!lockrSync.bLock(1))
return;
try
{
//
// If we have no changes, then just return, cause there is nothing to do.
// Else, reset the counter and let the derived class update itself with this
// new data.
//
if (!m_c4PollChanges)
return;
m_c4PollChanges = 0;
//
// See if the connection state has changed from the last one the bgn thread
// left us.
//
if (m_eConnState != m_ePrevState)
{
//
// Remember the previous state, then get it into sync with the current state.
// We want to do this before we make any call, in case it throws.
//
const tCQCGKit::EConnStates eOldState = m_ePrevState;
m_ePrevState = m_eConnState;
//
// If we have connected or disconnected, then let the derived class know so
// that he can update current status display stuff.
//
if ((eOldState != tCQCGKit::EConnStates::Connected)
&& (m_eConnState == tCQCGKit::EConnStates::Connected))
{
// Tell the parent tab window that we are not in error state
TTabWindow* pwndPar = dynamic_cast<TTabWindow*>(pwndParent());
if (pwndPar)
pwndPar->SetState(tCIDCtrls::ETabStates::Normal, kCIDLib::True);
Connected();
}
else if ((eOldState == tCQCGKit::EConnStates::Connected)
&& (m_eConnState != tCQCGKit::EConnStates::Connected))
{
// Tell the parent tab window that we are in error state
TTabWindow* pwndPar = dynamic_cast<TTabWindow*>(pwndParent());
if (pwndPar)
pwndPar->SetState(tCIDCtrls::ETabStates::Errors, kCIDLib::True);
LostConnection();
}
}
else if (m_eConnState == tCQCGKit::EConnStates::Connected)
{
//
// Its just a normal scenario. We are connected so let the driver display
// new data if it has any, left for it by the polling thread.
//
UpdateDisplayData();
}
}
catch(TError& errToCatch)
{
//
// Eat it, since there isn't much we can do, but log a message if
// debugging is on.
//
#if CID_DEBUG_ON
if (facCQCGKit().bShouldLog(errToCatch))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
#endif
}
catch(...)
{
//
// Eat it, since there isn't much we can do, but log a message if
// debugging is on.
//
#if CID_DEBUG_ON
#endif
}
}
// ---------------------------------------------------------------------------
// Private, non-virtual methods
// ---------------------------------------------------------------------------
//
// This method is called from the poll thread when its time to do another poll cycle.
// We just break it out in order to keep that method from getting messy and bloated.
//
tCIDLib::TVoid TCQCDriverClient::DoPollCycle()
{
// Lock during this
TLocker lockrSync(&m_mtxSync);
//
// Ok, we get called here from the poll thread (and once from the main thread on
// startup to kickstart things.) We are responsible for either getting ourself up
// to the 'connected' state, or if already there for polling data and backing our
// state off if something goes awry.
//
try
{
//
// We'll start with being completely disconnected from the server, in which case
// we need to try to get a client proxy. If this fails, it'll throw and we'll
// catch below and stay off line. If it works ok, then update to assuming the
// device is offline, and indicate that state changes have happened.
//
if (m_eConnState == tCQCGKit::EConnStates::SrvOffline)
{
// Drop any old reference if we have one
if (m_orbcServer.pobjData())
m_orbcServer.DropRef();
//
// Try to get a new client proxy. If it works, then move our state up.
// Catch exceptions since we are going to get them if the server isn't up,
// and we just want to eat those and stay offline.
//
try
{
m_orbcServer = facCQCKit().orbcCQCSrvAdminProxy(m_cqcdcThis.strMoniker());
m_eConnState = tCQCGKit::EConnStates::DevOffline;
m_c4PollChanges++;
}
catch(TError& errToCatch)
{
// If it anything besides the driver not being loaded, rethrow
if (!errToCatch.bCheckEvent(facCQCKit().strName()
, kKitErrs::errcRem_DrvNotFound))
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
}
}
//
// Ok, we are now connected to the server, but it might not be connected to
// its device. So if we last saw it offline, let's ask it for status. If it
// now shows connected, we get tell the driver to do one time on connect
// stuff, and move to connected state. We bump our changes counter to make
// sure the GUI thread updates in responses.
//
if (m_eConnState == tCQCGKit::EConnStates::DevOffline)
{
tCIDLib::TCard4 c4ThreadId;
tCQCKit::EDrvStates eState;
tCQCKit::EVerboseLvls eVerbose;
m_orbcServer->QueryDriverState
(
m_cqcdcThis.strMoniker(), eState, eVerbose, c4ThreadId
);
if (eState == tCQCKit::EDrvStates::Connected)
{
//
// Ask the derived class to get any 'one time' info that it gets from
// it's server driver upon connect. If the driver class doesn't throw
// an error, we'll update our status.
//
if (bGetConnectData(m_orbcServer))
{
m_eConnState = tCQCGKit::EConnStates::Connected;
m_c4PollChanges++;
}
}
}
//
// And if we are current fully connected, we just want to ask the derived class
// to poll for data. Its return value tells us if new data has showed up, or if
// he cannot talk to his device or server, in which case we update the status
// accordingly.
//
if (m_eConnState == tCQCGKit::EConnStates::Connected)
{
if (bDoPoll(m_orbcServer))
m_c4PollChanges++;
}
}
catch(const TError& errToCatch)
{
if (!m_orbcServer.pobjData() || m_orbcServer->bCheckForLostConnection())
{
// We lost connection to the server
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
m_orbcServer.DropRef();
}
else if (errToCatch.bCheckEvent(facCQCKit().strName(), kKitErrs::errcDrv_NotOnline)
|| errToCatch.bCheckEvent(facCQCKit().strName(), kKitErrs::errcDrv_NotFound))
{
if (m_eConnState != tCQCGKit::EConnStates::DevOffline)
{
// The device isn't there for some reason
m_eConnState = tCQCGKit::EConnStates::DevOffline;
m_c4PollChanges++;
}
}
else if (errToCatch.bCheckEvent(facCIDOrbUC().strName()
, kOrbUCErrs::errcSrv_NSNotFound))
{
// We couldn't find the server in the name server
if (m_eConnState != tCQCGKit::EConnStates::SrvOffline)
{
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
}
else
{
// Not something obvious, so log it if logging warnings
if (facCQCGKit().bLogWarnings() && !errToCatch.bLogged())
TModule::LogEventObj(errToCatch);
if (m_eConnState == tCQCGKit::EConnStates::Connected)
{
// We think we are connected, so try to make a call to the driver
try
{
tCIDLib::TCard4 c4Tmp;
m_orbcServer->c4QueryDriverId(m_cqcdcThis.strMoniker(), c4Tmp);
//
// It worked, so just assume it was some dumb error in the
// driver's GUI code.
//
}
catch(const TError& errToCatch)
{
//
// If it's not found, then we just lost the device,
// else assume we lost the server.
//
if (errToCatch.eClass() == tCIDLib::EErrClasses::NotFound)
m_eConnState = tCQCGKit::EConnStates::DevOffline;
else
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
catch(...)
{
// Assume we lost the connection
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
}
else if (m_eConnState != tCQCGKit::EConnStates::SrvOffline)
{
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
}
}
catch(...)
{
//
// We don't have an exception to go by, so we have to just manually
// try the link and see if this happened becasue we lost the
// connection or not. We'll just try to get the driver id, which
// is a simple call that will check for out driver being there.
//
// If we aren't connected, just assume the worst case and say the
// server is offline and force us to completely reconnect.
//
if (m_eConnState == tCQCGKit::EConnStates::Connected)
{
try
{
tCIDLib::TCard4 c4Tmp;
m_orbcServer->c4QueryDriverId(m_cqcdcThis.strMoniker(), c4Tmp);
//
// It worked, so just assume it was some dumb error in the
// driver's GUI code.
//
}
catch(const TError& errToCatch)
{
//
// If it's not found, then we just lost the device,
// else assume we lost the server.
//
if (errToCatch.eClass() == tCIDLib::EErrClasses::NotFound)
m_eConnState = tCQCGKit::EConnStates::DevOffline;
else
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
catch(...)
{
// Assume we lost the connection
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
}
else if (m_eConnState != tCQCGKit::EConnStates::SrvOffline)
{
m_eConnState = tCQCGKit::EConnStates::SrvOffline;
m_c4PollChanges++;
}
}
}
//
// This is the polling thread. This is started up when the window is created,
// and runs until the window is closed. It keeps up with our current connect
// state and does what is necessary to run the show wrt to staying connected
// to the server and polling it for new data.
//
tCIDLib::EExitCodes
TCQCDriverClient::ePollThread(TThread& thrThis, tCIDLib::TVoid*)
{
// Let the thread that started us go now
thrThis.Sync();
//
// To avoid setting a try block on every round, we use a double loop.
// That lets us catch exceptions and restart.
//
tCIDLib::TBoolean bExit = kCIDLib::False;
while (!bExit)
{
try
{
while (!bExit)
{
if (m_eConnState == tCQCGKit::EConnStates::Connected)
{
if (!thrThis.bSleep(2000))
{
bExit = kCIDLib::True;
continue;
}
}
else
{
if (!thrThis.bSleep(4000))
{
bExit = kCIDLib::True;
continue;
}
}
//
// Call our method that does a standard poll cycle. According
// to our current connect status, this guy does what is
// necessary to keep things moving along and will update our
// state accordingly.
//
DoPollCycle();
}
}
catch(TError& errToCatch)
{
if (facCQCGKit().bLogWarnings())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
}
catch(...)
{
if (facCQCGKit().bLogFailures())
{
facCQCGKit().LogMsg
(
CID_FILE
, CID_LINE
, kGKitMsgs::midStatus_PollThreadExcept
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, m_cqcdcThis.strMoniker()
);
}
}
}
return tCIDLib::EExitCodes::Normal;
}
| 30.668774 | 93 | 0.513294 | MarkStega |
7f205320f9c7145eca5fbd3fc58c41693d413567 | 20,948 | cpp | C++ | libraries/plugins/chain/chain_plugin_full.cpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 8 | 2018-07-25T20:42:43.000Z | 2019-03-11T03:14:09.000Z | libraries/plugins/chain/chain_plugin_full.cpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 13 | 2018-07-25T17:41:28.000Z | 2019-01-25T13:38:11.000Z | libraries/plugins/chain/chain_plugin_full.cpp | SophiaTX/SophiaTx-Blockchain | c964691c020962ad1aba8263c0d8a78a9fa27e45 | [
"MIT"
] | 11 | 2018-07-25T14:34:13.000Z | 2019-05-03T13:29:37.000Z | #include <sophiatx/chain/database/database_exceptions.hpp>
#include <sophiatx/chain/genesis_state.hpp>
#include <sophiatx/plugins/chain/chain_plugin_full.hpp>
#include <sophiatx/chain/database/database.hpp>
#include <sophiatx/utilities/benchmark_dumper.hpp>
#include <sophiatx/chain/get_config.hpp>
#include <sophiatx/egenesis/egenesis.hpp>
#include <fc/string_utils.hpp>
#include <fc/io/fstream.hpp>
#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/bind.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/thread/future.hpp>
#include <thread>
#include <memory>
#include <iostream>
namespace sophiatx { namespace plugins { namespace chain {
using namespace sophiatx;
using fc::flat_map;
using sophiatx::chain::block_id_type;
namespace asio = boost::asio;
chain_plugin_full::chain_plugin_full() : write_queue( 64 ) {
db_ = std::make_shared<database>();
}
chain_plugin_full::~chain_plugin_full() { stop_write_processing(); }
struct write_request_visitor
{
write_request_visitor() {}
std::shared_ptr<database> db;
uint32_t skip = 0;
std::optional< fc::exception >* except;
typedef bool result_type;
bool operator()( const signed_block* block )
{
bool result = false;
try
{
result = db->push_block( *block, skip );
}
catch( fc::exception& e )
{
*except = e;
}
catch( ... )
{
*except = fc::unhandled_exception( FC_LOG_MESSAGE( warn, "Unexpected exception while pushing block." ),
std::current_exception() );
}
return result;
}
bool operator()( const signed_transaction* trx )
{
bool result = false;
try
{
db->push_transaction( *trx );
result = true;
}
catch( fc::exception& e )
{
*except = e;
}
catch( ... )
{
*except = fc::unhandled_exception( FC_LOG_MESSAGE( warn, "Unexpected exception while pushing block." ),
std::current_exception() );
}
return result;
}
bool operator()( generate_block_request* req )
{
bool result = false;
try{
req->block = db->generate_block(
req->when,
req->witness_owner,
req->block_signing_private_key,
req->skip
);
result = true;
}catch( fc::exception& e ){
*except = e;
}
catch( ... )
{
*except = fc::unhandled_exception( FC_LOG_MESSAGE( warn, "Unexpected exception while pushing block." ),
std::current_exception() );
}
return result;
}
};
struct request_promise_visitor
{
request_promise_visitor(){}
typedef void result_type;
template< typename T >
void operator()( T* t )
{
t->set_value();
}
};
void chain_plugin_full::start_write_processing()
{
write_processor_thread = std::make_shared< std::thread >( [&](){
bool is_syncing = true;
write_context* cxt;
fc::time_point_sec start = fc::time_point::now();
write_request_visitor req_visitor;
req_visitor.db = std::static_pointer_cast<database>(db_);
request_promise_visitor prom_visitor;
/* This loop monitors the write request queue and performs writes to the database. These
* can be blocks or pending transactions. Because the caller needs to know the success of
* the write and any exceptions that are thrown, a write context is passed in the queue
* to the processing thread which it will use to store the results of the write. It is the
* caller's responsibility to ensure the pointer to the write context remains valid until
* the contained promise is complete.
*
* The loop has two modes, sync mode and live mode. In sync mode we want to process writes
* as quickly as possible with minimal overhead. The outer loop busy waits on the queue
* and the inner loop drains the queue as quickly as possible. We exit sync mode when the
* head block is within 1 minute of system time.
*
* Live mode needs to balance between processing pending writes and allowing readers access
* to the database. It will batch writes together as much as possible to minimize lock
* overhead but will willingly give up the write lock after 500ms. The thread then sleeps for
* 10ms. This allows time for readers to access the database as well as more writes to come
* in. When the node is live the rate at which writes come in is slower and busy waiting is
* not an optimal use of system resources when we could give CPU time to read threads.
*/
while( running )
{
if( !is_syncing )
start = fc::time_point::now();
if( write_queue.pop( cxt ) )
{
db_->with_write_lock( [&](){
while( true )
{
req_visitor.skip = cxt->skip;
req_visitor.except = &(cxt->except);
cxt->success = cxt->req_ptr.visit( req_visitor );
cxt->prom_ptr.visit( prom_visitor );
if( is_syncing && start - db_->head_block_time() < fc::minutes(1) )
{
start = fc::time_point::now();
is_syncing = false;
}
if( !is_syncing && write_lock_hold_time >= 0 && fc::time_point::now() - start > fc::milliseconds( write_lock_hold_time ) )
{
break;
}
if( !write_queue.pop( cxt ) )
{
break;
}
}
});
}
if( !is_syncing ) {
boost::this_thread::sleep_for(boost::chrono::milliseconds(10));
} else
boost::this_thread::sleep_for(boost::chrono::milliseconds(1));
}
});
}
void chain_plugin_full::stop_write_processing()
{
running = false;
if( write_processor_thread )
write_processor_thread->join();
write_processor_thread.reset();
}
void chain_plugin_full::set_program_options(options_description& cli, options_description& cfg)
{
cfg.add_options()
("genesis-json", bpo::value<bfs::path>(), "the location of the genesis file in JSON format")
("shared-file-size", bpo::value<string>()->default_value("24G"), "Size of the shared memory file. Default: 24G. If running a full node, increase this value to 200G.")
("shared-file-full-threshold", bpo::value<uint16_t>()->default_value(0),
"A 2 precision percentage (0-10000) that defines the threshold for when to autoscale the shared memory file. Setting this to 0 disables autoscaling. Recommended value for consensus node is 9500 (95%). Full node is 9900 (99%)" )
("shared-file-scale-rate", bpo::value<uint16_t>()->default_value(0),
"A 2 precision percentage (0-10000) that defines how quickly to scale the shared memory file. When autoscaling occurs the file's size will be increased by this percent. Setting this to 0 disables autoscaling. Recommended value is between 1000-2000 (10-20%)" )
("checkpoint,c", bpo::value<vector<string>>()->composing(), "Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints.")
("flush-state-interval", bpo::value<uint32_t>(),
"flush shared memory changes to disk every N blocks")
;
cli.add_options()
("replay-blockchain", bpo::bool_switch()->default_value(false), "clear chain database and replay all blocks" )
("resync-blockchain", bpo::bool_switch()->default_value(false), "clear chain database and block log" )
("stop-replay-at-block", bpo::value<uint32_t>(), "Stop and exit after reaching given block number")
("set-benchmark-interval", bpo::value<uint32_t>(), "Print time and memory usage every given number of blocks")
("dump-memory-details", bpo::bool_switch()->default_value(false), "Dump database objects memory usage info. Use set-benchmark-interval to set dump interval.")
("check-locks", bpo::bool_switch()->default_value(false), "Check correctness of chainbase locking" )
("validate-database-invariants", bpo::bool_switch()->default_value(false), "Validate all supply invariants check out" )
("initminer-mining-pubkey", bpo::value<std::string>(), "initminer public key for mining. Used only for private nets.")
("initminer-account-pubkey", bpo::value<std::string>(), "initminer public key for account operations. Used only for private nets.")
;
}
void chain_plugin_full::plugin_initialize(const variables_map& options) {
shared_memory_size = fc::parse_size( options.at( "shared-file-size" ).as< string >() );
if( options.count( "shared-file-full-threshold" ) )
shared_file_full_threshold = options.at( "shared-file-full-threshold" ).as< uint16_t >();
if( options.count( "shared-file-scale-rate" ) )
shared_file_scale_rate = options.at( "shared-file-scale-rate" ).as< uint16_t >();
bool private_net = false;
if (options.count("initminer-mining-pubkey") ) {
private_net = true;
}
auto initial_state = [&] {
if( (private_net && options.count("initminer-account-pubkey")) ||
(private_net && options.count("genesis-json") == 0 ) ){
genesis_state_type genesis;
genesis.genesis_time = time_point_sec::from_iso_string("2018-01-01T08:00:00");
genesis.initial_balace = 0;
genesis.initial_public_key = options.count("initminer-account-pubkey") ?
public_key_type(options.at( "initminer-account-pubkey" ).as< std::string >()) :
public_key_type(options.at( "initminer-mining-pubkey" ).as< std::string >());
genesis.initial_public_mining_key = public_key_type(options.at( "initminer-mining-pubkey" ).as< std::string >());
genesis.is_private_net = true;
fc::sha256::encoder enc;
fc::raw::pack( enc, genesis );
genesis.initial_chain_id = enc.result();
return genesis;
}
if( options.count("genesis-json") )
{
std::string genesis_str;
fc::read_file_contents( options.at("genesis-json").as<boost::filesystem::path>(), genesis_str );
genesis_state_type genesis = fc::json::from_string( genesis_str ).as<genesis_state_type>();
genesis.initial_chain_id = fc::sha256::hash( genesis_str);
genesis.is_private_net = private_net;
return genesis;
}
else
{
std::string egenesis_json;
sophiatx::egenesis::compute_egenesis_json( egenesis_json );
FC_ASSERT( !egenesis_json.empty() );
FC_ASSERT( sophiatx::egenesis::get_egenesis_json_hash() == fc::sha256::hash( egenesis_json ) );
auto genesis = fc::json::from_string( egenesis_json ).as<genesis_state_type>();
genesis.initial_chain_id = fc::sha256::hash( egenesis_json );
return genesis;
}
};
genesis = initial_state();
chain::sophiatx_config::init(genesis);
replay = options.at( "replay-blockchain").as<bool>();
resync = options.at( "resync-blockchain").as<bool>();
stop_replay_at =
options.count( "stop-replay-at-block" ) ? options.at( "stop-replay-at-block" ).as<uint32_t>() : 0;
benchmark_interval =
options.count( "set-benchmark-interval" ) ? options.at( "set-benchmark-interval" ).as<uint32_t>() : 0;
check_locks = options.at( "check-locks" ).as< bool >();
validate_invariants = options.at( "validate-database-invariants" ).as<bool>();
dump_memory_details = options.at( "dump-memory-details" ).as<bool>();
if( options.count( "flush-state-interval" ) )
flush_interval = options.at( "flush-state-interval" ).as<uint32_t>();
else
flush_interval = 10000;
if(options.count("checkpoint"))
{
auto cps = options.at("checkpoint").as<vector<string>>();
loaded_checkpoints.reserve(cps.size());
for(const auto& cp : cps)
{
auto item = fc::json::from_string(cp).as<std::pair<uint32_t,block_id_type>>();
loaded_checkpoints[item.first] = item.second;
}
}
}
#define BENCHMARK_FILE_NAME "replay_benchmark.json"
void chain_plugin_full::plugin_startup()
{
ilog( "Starting chain with shared_file_size: ${n} bytes", ("n", shared_memory_size) );
chain_id_type chain_id = genesis.compute_chain_id();
shared_memory_dir = app().data_dir() / chain_id.str() / "blockchain";
// correct directories, TODO can be removed after next HF2
if( ! genesis.is_private_net && bfs::exists( app().data_dir() / "blockchain" ) ){
bfs::create_directories ( shared_memory_dir );
bfs::rename( app().data_dir() / "blockchain", shared_memory_dir );
}
ilog("Starting node with chain id ${i}", ("i", chain_id));
start_write_processing();
if(resync)
{
wlog("resync requested: deleting block log and shared memory");
db_->wipe( shared_memory_dir, true );
}
db_->set_flush_interval( flush_interval );
db_->add_checkpoints( loaded_checkpoints );
db_->set_require_locking( check_locks );
bool dump_memory_details_ = dump_memory_details;
sophiatx::utilities::benchmark_dumper dumper;
const auto& abstract_index_cntr = db_->get_abstract_index_cntr();
typedef sophiatx::utilities::benchmark_dumper::index_memory_details_cntr_t index_memory_details_cntr_t;
auto get_indexes_memory_details = [dump_memory_details_, &abstract_index_cntr]
(index_memory_details_cntr_t& index_memory_details_cntr, bool onlyStaticInfo)
{
if (!dump_memory_details_)
return;
for (auto idx : abstract_index_cntr)
{
auto info = idx->get_statistics(onlyStaticInfo);
index_memory_details_cntr.emplace_back(std::move(info._value_type_name), info._item_count,
info._item_sizeof, info._item_additional_allocation, info._additional_container_allocation);
}
};
database::open_args db_open_args;
db_open_args.shared_mem_dir = shared_memory_dir;
db_open_args.shared_file_size = shared_memory_size;
db_open_args.shared_file_full_threshold = shared_file_full_threshold;
db_open_args.shared_file_scale_rate = shared_file_scale_rate;
db_open_args.do_validate_invariants = validate_invariants;
db_open_args.stop_replay_at = stop_replay_at;
auto benchmark_lambda = [&dumper, &get_indexes_memory_details, dump_memory_details_] ( uint32_t current_block_number,
const chainbase::database::abstract_index_cntr_t& abstract_index_cntr )
{
if( current_block_number == 0 ) // initial call
{
typedef sophiatx::utilities::benchmark_dumper::database_object_sizeof_cntr_t database_object_sizeof_cntr_t;
auto get_database_objects_sizeofs = [dump_memory_details_, &abstract_index_cntr]
(database_object_sizeof_cntr_t& database_object_sizeof_cntr)
{
if (!dump_memory_details_)
return;
for (auto idx : abstract_index_cntr)
{
auto info = idx->get_statistics(true);
database_object_sizeof_cntr.emplace_back(std::move(info._value_type_name), info._item_sizeof);
}
};
dumper.initialize(get_database_objects_sizeofs, BENCHMARK_FILE_NAME);
return;
}
const sophiatx::utilities::benchmark_dumper::measurement& measure =
dumper.measure(current_block_number, get_indexes_memory_details);
ilog( "Performance report at block ${n}. Elapsed time: ${rt} ms (real), ${ct} ms (cpu). Memory usage: ${cm} (current), ${pm} (peak) kilobytes.",
("n", current_block_number)
("rt", measure.real_ms)
("ct", measure.cpu_ms)
("cm", measure.current_mem)
("pm", measure.peak_mem) );
};
if(replay)
{
ilog("Replaying blockchain on user request.");
uint32_t last_block_number = 0;
db_open_args.benchmark = sophiatx::chain::database::TBenchmark(benchmark_interval, benchmark_lambda);
last_block_number = db_->reindex( db_open_args, genesis);
if( benchmark_interval > 0 )
{
const sophiatx::utilities::benchmark_dumper::measurement& total_data = dumper.dump(true, get_indexes_memory_details);
ilog( "Performance report (total). Blocks: ${b}. Elapsed time: ${rt} ms (real), ${ct} ms (cpu). Memory usage: ${cm} (current), ${pm} (peak) kilobytes.",
("b", total_data.block_number)
("rt", total_data.real_ms)
("ct", total_data.cpu_ms)
("cm", total_data.current_mem)
("pm", total_data.peak_mem) );
}
if( stop_replay_at > 0 && stop_replay_at == last_block_number )
{
ilog("Stopped blockchain replaying on user request. Last applied block number: ${n}.", ("n", last_block_number));
appbase::app().quit();
return;
}
}
else
{
db_open_args.benchmark = sophiatx::chain::database::TBenchmark(dump_memory_details_, benchmark_lambda);
try
{
ilog("Opening shared memory from ${path}", ("path",shared_memory_dir.generic_string()));
db_->open( db_open_args, genesis);
if( dump_memory_details_ )
dumper.dump( true, get_indexes_memory_details );
}
catch( const fc::exception& e )
{
wlog("Error opening database, attempting to replay blockchain. Error: ${e}", ("e", e));
try
{
db_->reindex( db_open_args, genesis);
}
catch( sophiatx::chain::block_log_exception& )
{
wlog( "Error opening block log. Having to resync from network..." );
db_->open( db_open_args, genesis);
}
}
}
ilog( "Started on blockchain with ${n} blocks", ("n", db_->head_block_num()) );
on_sync();
}
void chain_plugin_full::plugin_shutdown()
{
ilog("closing chain database");
stop_write_processing();
db_->close();
ilog("database closed successfully");
}
bool chain_plugin_full::accept_block( const sophiatx::chain::signed_block& block, bool currently_syncing, uint32_t skip )
{
if (currently_syncing && block.block_num() % 10000 == 0) {
ilog("Syncing Blockchain --- Got block: #${n} time: ${t} producer: ${p}",
("t", block.timestamp)
("n", block.block_num())
("p", block.witness) );
}
check_time_in_block( block );
boost::promise< void > prom;
write_context cxt;
cxt.req_ptr = █
cxt.skip = currently_syncing? skip | database::skip_validate_invariants : skip;
cxt.prom_ptr = &prom;
write_queue.push( &cxt );
prom.get_future().get();
if( cxt.except ) throw *(cxt.except);
return cxt.success;
}
void chain_plugin_full::accept_transaction( const sophiatx::chain::signed_transaction& trx )
{
boost::promise< void > prom;
write_context cxt;
cxt.req_ptr = &trx;
cxt.prom_ptr = &prom;
write_queue.push( &cxt );
prom.get_future().get();
if( cxt.except ) throw *(cxt.except);
return;
}
void chain_plugin_full::check_time_in_block( const sophiatx::chain::signed_block& block )
{
time_point_sec now = fc::time_point::now();
uint64_t max_accept_time = now.sec_since_epoch();
max_accept_time += allow_future_time;
FC_ASSERT( block.timestamp.sec_since_epoch() <= max_accept_time );
}
sophiatx::chain::signed_block chain_plugin_full::generate_block( const fc::time_point_sec& when, const account_name_type& witness_owner,
const fc::ecc::private_key& block_signing_private_key, uint32_t skip )
{
generate_block_request req( when, witness_owner, block_signing_private_key, skip );
boost::promise< void > prom;
write_context cxt;
cxt.req_ptr = &req;
cxt.prom_ptr = &prom;
write_queue.push( &cxt );
prom.get_future().get();
if( cxt.except ) throw *(cxt.except);
FC_ASSERT( cxt.success, "Block could not be generated" );
return req.block;
}
int16_t chain_plugin_full::set_write_lock_hold_time( int16_t new_time )
{
FC_ASSERT( get_state() == appbase::abstract_plugin::state::initialized,
"Can only change write_lock_hold_time while chain_plugin_full is initialized." );
int16_t old_time = write_lock_hold_time;
write_lock_hold_time = new_time;
return old_time;
}
} } } // namespace sophiatx::plugis::chain::chain_apis
| 36.880282 | 271 | 0.634142 | SophiaTX |
7f2672a9bfddd5ff0a2e8882dce80949e5b10ef8 | 3,419 | cc | C++ | Unittests/DictTest.cc | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | 5 | 2020-06-30T05:06:40.000Z | 2021-05-24T08:38:33.000Z | Unittests/DictTest.cc | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | null | null | null | Unittests/DictTest.cc | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | 2 | 2015-10-01T18:28:20.000Z | 2020-09-09T16:25:27.000Z | #include "Python.h"
#include "gtest/gtest.h"
class DictWatcherTest : public testing::Test {
protected:
DictWatcherTest()
{
Py_NoSiteFlag = true;
Py_Initialize();
this->globals_ = PyDict_New();
this->builtins_ = PyDict_New();
}
~DictWatcherTest()
{
Py_DECREF(this->globals_);
Py_DECREF(this->builtins_);
Py_Finalize();
}
// Satisfying all the inputs to PyCode_New() is hard, so we fake it.
// You will need to PyMem_DEL the result manually.
PyCodeObject *FakeCodeObject()
{
PyCodeObject *code = PyMem_NEW(PyCodeObject, 1);
assert(code != NULL);
// We only initialize the fields related to dict watchers.
code->co_assumed_globals = NULL;
code->co_assumed_builtins = NULL;
code->co_use_llvm = 0;
code->co_fatalbailcount = 0;
return code;
}
PyObject *globals_;
PyObject *builtins_;
};
TEST_F(DictWatcherTest, AddWatcher)
{
PyCodeObject *code = this->FakeCodeObject();
_PyDict_AddWatcher(this->globals_, code);
PyDictObject *dict = (PyDictObject *)this->globals_;
EXPECT_EQ(dict->ma_watchers_used, 1);
EXPECT_EQ(dict->ma_watchers_allocated, 64);
// Drop the watcher to prevent the dict's dealloc from referencing freed
// memory.
_PyDict_DropWatcher(this->globals_, code);
PyMem_DEL(code);
}
// _PyDict_DropWatcher() used to leave holes in the watcher array. This test
// verifies that DropWatcher() compacts the array.
TEST_F(DictWatcherTest, DropWatcherAddWatcherSequence)
{
PyCodeObject *code1 = this->FakeCodeObject();
PyCodeObject *code2 = this->FakeCodeObject();
_PyDict_AddWatcher(this->globals_, code1);
_PyDict_AddWatcher(this->globals_, code2);
_PyDict_DropWatcher(this->globals_, code1);
PyDictObject *dict = (PyDictObject *)this->globals_;
EXPECT_EQ(dict->ma_watchers_used, 1);
EXPECT_EQ(dict->ma_watchers[0], code2);
_PyDict_DropWatcher(this->globals_, code2);
PyMem_DEL(code1);
PyMem_DEL(code2);
}
TEST_F(DictWatcherTest, DictDealloc)
{
PyObject *globals = PyDict_New();
PyObject *builtins = PyDict_New();
PyCodeObject *code1 = this->FakeCodeObject();
code1->co_use_llvm = 1;
EXPECT_EQ(_PyCode_WatchGlobals(code1, globals, builtins), 0);
Py_DECREF(globals);
EXPECT_EQ(code1->co_use_llvm, 0);
EXPECT_EQ(code1->co_assumed_globals, (PyObject *)NULL);
EXPECT_EQ(code1->co_assumed_builtins, (PyObject *)NULL);
PyDictObject *dict = (PyDictObject *)builtins;
EXPECT_EQ(dict->ma_watchers_used, 0);
Py_DECREF(builtins);
PyMem_DEL(code1);
}
TEST_F(DictWatcherTest, NotifyWatcher)
{
PyCodeObject *code1 = this->FakeCodeObject();
code1->co_use_llvm = 1;
EXPECT_EQ(_PyCode_WatchGlobals(code1, this->globals_, this->builtins_), 0);
EXPECT_EQ(code1->co_use_llvm, 1);
// This should notify the watchers.
PyDict_SetItemString(this->globals_, "hello", Py_None);
EXPECT_EQ(code1->co_use_llvm, 0);
PyDictObject *globals_dict = (PyDictObject *)this->globals_;
EXPECT_EQ(globals_dict->ma_watchers_used, 0);
PyDictObject *builtins_dict = (PyDictObject *)this->builtins_;
EXPECT_EQ(builtins_dict->ma_watchers_used, 0);
EXPECT_EQ(code1->co_assumed_builtins, (PyObject *)NULL);
EXPECT_EQ(code1->co_assumed_globals, (PyObject *)NULL);
PyMem_DEL(code1);
}
| 29.222222 | 79 | 0.687335 | ianloic |
7f26a584009c9e5e484626852f8a51d27adebacd | 958 | cpp | C++ | C++/problem0922.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | C++/problem0922.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | C++/problem0922.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <windows.h>
#include <string>
#include <numeric>
using namespace std;
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& A) {
int j = 1;
for (int i = 0; i < A.size(); i += 2)
{
if (A[i]%2 == 1)
{
while (A[j]%2 == 1)
{
j += 2;
}
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
return A;
}
};
int main()
{
vector<int> A {4,2,5,7};
Solution solu;
vector<int> ans = solu.sortArrayByParityII(A);
vector<int>::iterator it;
for (it = ans.begin(); it < ans.end(); ++it)
{
cout << *it << '\t';
}
cout << endl;
return 0;
}
| 19.16 | 53 | 0.44572 | 1050669722 |
7f2b8949ecb55a42e2a90caccb8bb55269b7af1e | 2,486 | cpp | C++ | test/channel/main_channel_udp1.cpp | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 39 | 2015-12-09T09:28:46.000Z | 2021-11-16T12:57:25.000Z | test/channel/main_channel_udp1.cpp | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 1 | 2020-10-17T02:23:42.000Z | 2020-10-17T02:23:42.000Z | test/channel/main_channel_udp1.cpp | oudream/ccxx | 7746ef93b48bf44157048a43c4878152fe6a4d2b | [
"MIT"
] | 8 | 2018-05-29T12:48:13.000Z | 2022-02-27T01:45:57.000Z | /*
cxtest_channel_udp1 -lip 10.32.50.57 -lport 5555 -rip 10.32.50.57 -rport 5556
cxtest_channel_udp1 -lip 10.32.50.57 -lport 5556 -rip 10.32.50.57 -rport 5555
/**/
#include <ccxx/ccxx.h>
using namespace std;
class UdpSubject : public CxIChannelSubject
{
public:
UdpSubject(){
mRecvTotalTimes = 0;
mRecvTotalLen = 0;
}
~UdpSubject(){
}
int mRecvTotalTimes;
int mRecvTotalLen;
protected:
void channel_receivedData(const uchar* pData, int iLength, void * oSource)
{
mRecvTotalTimes++;
mRecvTotalLen += iLength;
cout << "Recv " << iLength << " Byte, mRecvTotalTimes " << mRecvTotalTimes << " Byte, mRecvTotalLen " << mRecvTotalLen << endl;
}
};
CxChannelUdp f_mUdp;
UdpSubject f_mUdpSubject;
#define GM_TEST_UDP_DATA_LEN 14000
int mSendTotalTimes = 0;
int mSendTotalLen = 0;
void fn_timer_timeout1(int iInterval)
{
cout << CxTime::currentSystemTimeString() << endl;
if (!f_mUdp.isOpen())
{
cout << "Udp Client Is Not Open!";
return;
}
char data[GM_TEST_UDP_DATA_LEN];
f_mUdp.sendData(data, GM_TEST_UDP_DATA_LEN);
int iResult = f_mUdp.sendData(data, sizeof(data));
mSendTotalTimes ++;
mSendTotalLen += iResult;
cout << "Udp Client sendData Result=" << iResult << " Byte, mSendTotalTimes " << mSendTotalTimes << " Byte, mSendTotalLen " << mSendTotalLen << endl;
}
int main(int argc, const char * argv[])
{
cout << "Udp Client Test Begin: " << endl;
CxApplication::init(argc, argv);
string sLocalIp = CxAppEnv::findArgument("lip");
if (! CxString::isValidIp(sLocalIp)) sLocalIp = "127.0.0.1";
int iLocalPort = CxString::toInt32(CxAppEnv::findArgument("lport"));
if (! CxString::isValidPort(iLocalPort)) iLocalPort = 5555;
string sRemoteIp = CxAppEnv::findArgument("rip");
if (! CxString::isValidIp(sRemoteIp)) sRemoteIp = "127.0.0.1";
int iRemotePort = CxString::toInt32(CxAppEnv::findArgument("rport"));
if (! CxString::isValidPort(iRemotePort)) iRemotePort = 5556;
f_mUdp.addObserver(&f_mUdpSubject);
f_mUdp.setLocalIp(sLocalIp);
f_mUdp.setLocalPort(iLocalPort);
f_mUdp.setRemoteIp(sRemoteIp);
f_mUdp.setRemotePort(iRemotePort);
f_mUdp.open();
cout << "Udp Client Open. port=" << iLocalPort << ", status=" << f_mUdp.isOpen()<< endl;
CxThread::sleep(5000);
CxTimerManager::startTimer(fn_timer_timeout1, 100);
return CxApplication::exec();
}
| 28.906977 | 153 | 0.662912 | oudream |
7f2ce710398c6aa5fc53cac0665671b65a6e8174 | 1,648 | cc | C++ | src/Gateway.cc | Swair/Function-Distributed-Network | 55c2c9caa2b6de6c06c99009b2063703601e7956 | [
"Apache-2.0"
] | null | null | null | src/Gateway.cc | Swair/Function-Distributed-Network | 55c2c9caa2b6de6c06c99009b2063703601e7956 | [
"Apache-2.0"
] | null | null | null | src/Gateway.cc | Swair/Function-Distributed-Network | 55c2c9caa2b6de6c06c99009b2063703601e7956 | [
"Apache-2.0"
] | null | null | null | #include "Gateway.h"
Gateway& Gateway::getInstance()
{
static Gateway gw;
return gw;
}
Gateway::Gateway()
{}
Gateway::~Gateway()
{}
void Gateway::reg(const std::string& method, std::function<void(std::string&, const std::string&)> func)
{
routeTable_[method] = func;
}
void Gateway::route(std::string& response, const std::string& request)
{
std::string failCode;
//log_write("%s\n", request.c_str());
std::string uri;
if(0 == getContent(uri, request, "POST", 1, " HTTP"))
{
failCode = R"({"code":400, "msg":"fail in get uri"})";
throw ExceptionPanic(failCode);
}
int ix = uri.rfind("/");
if(ix > 0)
{
std::string method = uri.substr(ix + 1);
//log_write("Gateway::route, %s\n", method.c_str());
try
{
auto f = routeTable_[method];
f(response, request);
}
catch(nlohmann::detail::exception& e)
{
std::string msg = e.what();
failCode = R"({"code":430, "msg":")" + msg + R"("})";
throw ExceptionPanic(failCode);
}
catch(std::exception& e)
{
failCode = R"({"code":431, "msg":"fail in route, check the web api"})";
throw ExceptionPanic(failCode);
}
catch(ExceptionPanic& e)
{
std::string msg = e.what();
failCode = R"({"code":432, "msg":")" + msg + R"("})";
throw ExceptionPanic(failCode);
}
catch(...)
{
failCode = R"({"code":433, "msg":"fail in route"})";
throw ExceptionPanic(failCode);
}
}
}
| 24.969697 | 105 | 0.508495 | Swair |
b526587f2318c6c9d871d46e423e6b483563a1b5 | 326 | cpp | C++ | Dataset/Leetcode/test/110/451.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/110/451.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/test/110/451.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
bool flag=true;
bool XXX(TreeNode* root) {
int l=dfs(root);
return flag;
}
int dfs(TreeNode* root){
if(root==NULL) return 0;
int l=dfs(root->left);
int r=dfs(root->right);
if(abs(l-r)>1) flag=false;
return max(l,r)+1;
}
};
| 19.176471 | 35 | 0.509202 | kkcookies99 |
b5290f40d62908ad95681d974cbce979eb8641f5 | 252 | cpp | C++ | Game/Client/WXClient/Network/PacketHandler/GCMySelfEquipmentListHandler.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/Client/WXClient/Network/PacketHandler/GCDetailEquipmentListHandler.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/Client/WXClient/Network/PacketHandler/GCDetailEquipmentListHandler.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | #include "StdAfx.h"
#include "GCDetailEquipmentList.h"
uint GCDetailEquipmentListHandler :: Execute( GCDetailEquipmentList* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
return PACKET_EXE_CONTINUE ;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR ;
}
| 16.8 | 96 | 0.801587 | hackerlank |
b529f379479b6a73c191611f277d3980470cabd8 | 1,091 | cpp | C++ | usaco_practice/bronze/bronze_A/A4_array_two/Roll_cake.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | usaco_practice/bronze/bronze_A/A4_array_two/Roll_cake.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | usaco_practice/bronze/bronze_A/A4_array_two/Roll_cake.cpp | juneharold/USACO | a96b54f68e7247c61044f3c0d9e7260952c508e2 | [
"MIT"
] | null | null | null | // 롤 케이크
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
int L, N;
cin >> L;
cin >> N;
int ranges[2000] = {};
for (int i=0; i<2*N; i++)
{
cin >> ranges[i];
}
// number of cake
int max_expected=0;
int max_received=0;
// number of person
int num_ex=-1;
int num_re=-1;
int status[1000]={};
for (int j=0; j<N; j++)
{
int start=ranges[2*j], end=ranges[2*j+1];
// finding expectations
int range = end-start+1;
if (range>max_expected)
{
max_expected=range;
num_ex=j+1;
}
// looping through the range
int cake_received=0;
for (int c=start; c<=end; c++)
{
if (status[c]==0)
{
cake_received += 1;
status[c]=1;
}
}
if (cake_received>max_received)
{
max_received=cake_received;
num_re=j+1;
}
}
cout << num_ex << endl;
cout << num_re << endl;
}
| 20.584906 | 49 | 0.463795 | juneharold |
b52d3581cedf7fffe7a94047630d9129e71c264c | 137 | hh | C++ | Include/Luce/AI/Configuration.hh | kmc7468/luce | 6f71407f250dbc0428ceba33aeef345cc601db34 | [
"MIT"
] | 23 | 2017-02-09T11:48:01.000Z | 2017-04-08T10:19:21.000Z | Include/Luce/AI/Configuration.hh | kmc7468/luce | 6f71407f250dbc0428ceba33aeef345cc601db34 | [
"MIT"
] | null | null | null | Include/Luce/AI/Configuration.hh | kmc7468/luce | 6f71407f250dbc0428ceba33aeef345cc601db34 | [
"MIT"
] | null | null | null | #ifndef LUCE_HEADER_AI_CONFIGURATION_HH
#define LUCE_HEADER_AI_CONFIGURATION_HH
#include <Luce/AI/Configuration/ComputeByCpu.hh>
#endif | 22.833333 | 48 | 0.868613 | kmc7468 |
b52e9446ef1467cbc1e66fbabf752e1a26e6ef91 | 4,119 | cpp | C++ | Tests/BasicsTest/TestAVX2.cpp | mfkiwl/RayRenderer-dp4a | b57696b23c795f0ca1199e8f009b7a12b88da13a | [
"MIT"
] | 18 | 2018-10-22T10:30:20.000Z | 2021-12-10T06:29:39.000Z | Tests/BasicsTest/TestAVX2.cpp | mfkiwl/RayRenderer-dp4a | b57696b23c795f0ca1199e8f009b7a12b88da13a | [
"MIT"
] | null | null | null | Tests/BasicsTest/TestAVX2.cpp | mfkiwl/RayRenderer-dp4a | b57696b23c795f0ca1199e8f009b7a12b88da13a | [
"MIT"
] | 4 | 2019-06-04T14:04:43.000Z | 2021-07-16T01:41:48.000Z | #include "pch.h"
#if COMMON_COMPILER_GCC
# pragma GCC push_options
# pragma GCC target("avx2")
#elif COMMON_COMPILER_CLANG
# pragma clang attribute push (__attribute__((target("avx2"))), apply_to=function)
#endif
namespace avx2
{
using namespace common;
#define COMMON_SIMD_LV 200
#include "common/simd/SIMD.hpp"
#if COMMON_SIMD_LV_ >= 200
# include "common/simd/SIMD128.hpp"
# include "common/simd/SIMD256.hpp"
using namespace common::simd;
# include "SIMDBaseTest.h"
# include "ShuffleTest.h"
RegisterSIMDBaseTest(I64x4, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, Neg, Abs, Min, Max, SLL, SRL, SRA, And, Or, Xor, AndNot, Not);
RegisterSIMDBaseTest(U64x4, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDBaseTest(I32x8, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulX, Neg, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDBaseTest(U32x8, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulX, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDBaseTest(I16x16, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Neg, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDBaseTest(U16x16, 200, SWE, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDBaseTest(I8x32, 200, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Neg, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDBaseTest(U8x32, 200, SEL, Add, Sub, SatAdd, SatSub, MulLo, MulHi, MulX, Abs, Min, Max, SLL, SRL, SRA);
RegisterSIMDCastTest(F32x8, 200, F64x4);
RegisterSIMDCastTest(F64x4, 200, F32x8);
RegisterSIMDCastTest(I64x4, 200, I8x32, I16x16, I32x8 );
RegisterSIMDCastTest(U64x4, 200, U8x32, U16x16, U32x8 );
RegisterSIMDCastTest(I32x8, 200, I8x32, I16x16, I64x4, U64x4, F32x8, F64x4);
RegisterSIMDCastTest(U32x8, 200, U8x32, U16x16, I64x4, U64x4, F32x8, F64x4);
RegisterSIMDCastTest(I16x16, 200, I8x32, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4);
RegisterSIMDCastTest(U16x16, 200, U8x32, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4);
RegisterSIMDCastTest(I8x32, 200, I16x16, U16x16, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4);
RegisterSIMDCastTest(U8x32, 200, I16x16, U16x16, I32x8, U32x8, I64x4, U64x4, F32x8, F64x4);
RegisterSIMDCastModeTest(F32x8, 200, RangeSaturate, I16x16, U16x16, I8x32, U8x32);
RegisterSIMDCastModeTest(I32x8, 200, RangeSaturate, I16x16, U16x16);
RegisterSIMDCastModeTest(U32x8, 200, RangeSaturate, U16x16);
RegisterSIMDCastModeTest(I16x16, 200, RangeSaturate, I8x32, U8x32);
RegisterSIMDCastModeTest(U16x16, 200, RangeSaturate, U8x32);
RegisterSIMDCmpTest(200, I64x4, U64x4, I32x8, U32x8, I16x16, U16x16, I8x32, U8x32)
RegisterSIMDZipTest(200, F64x4, F32x8, I64x4, U64x4, I32x8, U32x8, I16x16, U16x16, I8x32, U8x32)
RegisterSIMDZipLaneTest(200, F64x4, F32x8, I64x4, U64x4, I32x8, U32x8, I16x16, U16x16, I8x32, U8x32)
RegisterSIMDTest(F64x4, 200, shuftest::ShuffleTest<F64x4>);
RegisterSIMDTest(I64x4, 200, shuftest::ShuffleTest<I64x4>);
RegisterSIMDTest(F64x2, 200, shuftest::ShuffleTest<F64x2>);
RegisterSIMDTest(I64x2, 200, shuftest::ShuffleTest<I64x2>);
RegisterSIMDTest(F32x4, 200, shuftest::ShuffleTest<F32x4>);
RegisterSIMDTest(I32x4, 200, shuftest::ShuffleTest<I32x4>);
RegisterSIMDTest(F64x4, 200, shuftest::ShuffleVarTest<F64x4>);
RegisterSIMDTest(I64x4, 200, shuftest::ShuffleVarTest<I64x4>);
RegisterSIMDTest(F32x8, 200, shuftest::ShuffleVarTest<F32x8>);
RegisterSIMDTest(I32x8, 200, shuftest::ShuffleVarTest<I32x8>);
RegisterSIMDTest(F64x2, 200, shuftest::ShuffleVarTest<F64x2>);
RegisterSIMDTest(I64x2, 200, shuftest::ShuffleVarTest<I64x2>);
RegisterSIMDTest(F32x4, 200, shuftest::ShuffleVarTest<F32x4>);
RegisterSIMDTest(I32x4, 200, shuftest::ShuffleVarTest<I32x4>);
#endif
}
#if COMMON_COMPILER_GCC
# pragma GCC pop_options
#elif COMMON_COMPILER_CLANG
# pragma clang attribute pop
#endif
| 48.458824 | 152 | 0.70017 | mfkiwl |
b531574b7fbbf60c47356dc23f1ef5ad56585873 | 5,537 | cpp | C++ | src/TowerEntity.cpp | Smokey1105/Strife.SingleplayerDemo | 586865f66e7b08a6e16385fe400c3dd2fe886489 | [
"NCSA"
] | null | null | null | src/TowerEntity.cpp | Smokey1105/Strife.SingleplayerDemo | 586865f66e7b08a6e16385fe400c3dd2fe886489 | [
"NCSA"
] | null | null | null | src/TowerEntity.cpp | Smokey1105/Strife.SingleplayerDemo | 586865f66e7b08a6e16385fe400c3dd2fe886489 | [
"NCSA"
] | null | null | null | #include "TowerEntity.hpp"
#include "Engine.hpp"
#include "PlayerEntity.hpp"
#include "FireballEntity.hpp"
#include "CastleEntity.hpp"
#include "ObstacleComponent.hpp"
#include "Components/RigidBodyComponent.hpp"
#include "Components/SpriteComponent.hpp"
#include "Physics/PathFinding.hpp"
#include "Net/ReplicationManager.hpp"
void TowerEntity::DoSerialize(EntitySerializer& serializer)
{
}
void TowerEntity::OnAdded()
{
spriteComponent = AddComponent<SpriteComponent>("towerSprite");
spriteComponent->scale = Vector2(5.0f);
Vector2 size{ 11 * 5, 32 * 5 };
SetDimensions(size);
obstacle = AddComponent<ObstacleComponent>();
auto rigidBody = AddComponent<RigidBodyComponent>(b2_staticBody);
rigidBody->CreateBoxCollider(size);
auto health = AddComponent<HealthBarComponent>();
health->offsetFromCenter = -size.YVector() / 2 - Vector2(0, 5);
health->maxHealth = 500;
health->health = 500;
team = AddComponent<TeamComponent>();
auto offset = size / 2 + Vector2(40, 40);
_light = AddComponent<LightComponent<PointLight>>();
_light->position = Center();
_light->intensity = 0.5;
_light->maxDistance = 500;
_light->maxDistance = 500;
region = rigidBody->CreateCircleCollider(reach, true);
}
void TowerEntity::Update(float deltaTime)
{
_light->color = playerId == 0
? Color::Green()
: Color::White();
if (_currentTarget.IsValid())
{
_fireballTimeout -= deltaTime;
}
OnUpdateState();
}
void TowerEntity::OnDestroyed()
{
for (auto base : scene->GetEntitiesOfType<CastleEntity>())
{
if (base->team->teamId == team->teamId)
{
base->SendEvent(TowerDestroyedEvent());
}
}
}
void TowerEntity::ReceiveEvent(const IEntityEvent& ev)
{
if (ev.Is<OutOfHealthEvent>())
{
Destroy();
}
else if (auto damageDealtEvent = ev.Is<DamageDealtEvent>())
{
Entity* currentTarget = nullptr;
if (_currentTarget.TryGetValue(currentTarget))
{
if (currentTarget != damageDealtEvent->dealer)
{
ChangeState(
{ TowerEntityAiState::AttackSelectedTarget,
EntityReference<Entity>(damageDealtEvent->dealer) });
}
}
}
else if (auto contactBeginEvent = ev.Is<ContactBeginEvent>())
{
if (contactBeginEvent->OtherIs<FireballEntity>())
{
return;
}
if (contactBeginEvent->self.GetFixture() == region && !contactBeginEvent->other.IsTrigger())
{
_targets.PushBackUniqueIfRoom(contactBeginEvent->other.OwningEntity());
}
}
else if (auto contactEndEvent = ev.Is<ContactEndEvent>())
{
auto other = contactEndEvent->other;
if (contactEndEvent->self.GetFixture() == region && !other.IsTrigger())
{
_targets.RemoveSingle(other.OwningEntity());
}
}
}
void TowerEntity::ChangeState(TowerEntityState state)
{
OnExitState();
OnEnterState(state);
_state = state;
}
void TowerEntity::OnEnterState(TowerEntityState& newState)
{
switch (newState.state)
{
case TowerEntityAiState::DoNothing:
case TowerEntityAiState::SearchForTarget:
break;
case TowerEntityAiState::AttackSelectedTarget:
{
_currentTarget = newState.newTarget;
}
break;
}
}
void TowerEntity::OnUpdateState()
{
switch (_state.state)
{
case TowerEntityAiState::DoNothing:
ChangeState({ TowerEntityAiState::SearchForTarget });
break;
case TowerEntityAiState::SearchForTarget:
{
float closestTargetDistance = reach * 2;
Entity* closestTarget = nullptr;
for (auto& target : _targets)
{
if (target == nullptr || target->isDestroyed)
{
continue;
}
TeamComponent* teamComponent;
if (target->TryGetComponent(teamComponent)) {
if (teamComponent->teamId == team->teamId)
{
continue;
}
if ((target->Center() - Center()).Length() <= closestTargetDistance)
{
closestTarget = target;
}
}
}
if (closestTarget != nullptr)
{
ChangeState({ TowerEntityAiState::AttackSelectedTarget, EntityReference<Entity>(closestTarget) });
}
}
break;
case TowerEntityAiState::AttackSelectedTarget:
{
Entity* target = _currentTarget.GetValueOrNull();
if (target == nullptr || (target->Center() - Center()).Length() >= reach)
{
_currentTarget.Invalidate();
ChangeState({ TowerEntityAiState::SearchForTarget });
}
else if (_fireballTimeout <= 0)
{
_fireballTimeout = FireballTimeoutLength;
ShootFireball(target);
}
}
break;
}
}
void TowerEntity::OnExitState()
{
switch (_state.state)
{
case TowerEntityAiState::DoNothing:
case TowerEntityAiState::SearchForTarget:
break;
case TowerEntityAiState::AttackSelectedTarget:
{
_currentTarget.Invalidate();
}
break;
}
}
void TowerEntity::ShootFireball(Entity* target)
{
auto direction = (target->Center() - Center()).Normalize();
auto fireball = scene->CreateEntity<FireballEntity>(Center(), direction * 400);
fireball->playerId = playerId;
} | 25.753488 | 110 | 0.609536 | Smokey1105 |
b5367526a850ce69445f5e2e3ae88b3cc0395ba2 | 444 | cpp | C++ | partners_api/ads/google_ads.cpp | vicpopov/omim | 664b458998fb0f2405f68ae830c2798e027b2dcc | [
"Apache-2.0"
] | 4,879 | 2015-09-30T10:56:36.000Z | 2022-03-31T18:43:03.000Z | partners_api/ads/google_ads.cpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 7,549 | 2015-09-30T10:52:53.000Z | 2022-03-31T22:04:22.000Z | partners_api/ads/google_ads.cpp | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 1,493 | 2015-09-30T10:43:06.000Z | 2022-03-21T09:16:49.000Z | #include "partners_api/ads/google_ads.hpp"
namespace
{
#if defined(OMIM_OS_IPHONE)
auto const kSearchbannerId = "mobile-app-mapsme";
#elif defined(OMIM_OS_ANDROID)
auto const kSearchbannerId = "mobile-app-mapsme";
#else
auto const kSearchbannerId = "dummy";
#endif
} // namespace
namespace ads
{
std::string Google::GetBanner() const
{
return kSearchbannerId;
}
bool Google::HasBanner() const
{
return true;
}
} // namespace ads
| 17.076923 | 51 | 0.734234 | vicpopov |
b5400e1794ee4d2bbfcf0b5fba231f428da08d3b | 4,401 | cpp | C++ | ilwiscoreui/models/workspacemodel.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | ilwiscoreui/models/workspacemodel.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | ilwiscoreui/models/workspacemodel.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | #include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include "kernel.h"
#include "ilwiscontext.h"
#include "workspacemodel.h"
WorkSpaceModel::WorkSpaceModel(const QString &name, QObject *parent) :
CatalogModel( Ilwis::Resource("ilwis://internalcatalog/workspaces/" + name,itWORKSPACE),parent)
{
}
WorkSpaceModel::~WorkSpaceModel()
{
}
void WorkSpaceModel::addItems(const QString& ids)
{
auto putInConfig = [&](quint64 id, int count) {
QString basekey = "users/" + Ilwis::context()->currentUser() + "/workspace-" + name();
Ilwis::Resource res = Ilwis::mastercatalog()->id2Resource(id);
if ( res.isValid()){
QString key;
if ( res.ilwisType() & itOPERATIONMETADATA){
key = QString("%1/operation-%2").arg(basekey).arg(count);
Ilwis::context()->configurationRef().addValue(QString("%1/operation-count").arg(basekey),QString::number(count + 1));
}
else{
key = QString("%1/data-%2").arg(basekey).arg(count);
Ilwis::context()->configurationRef().addValue(QString("%1/data-count").arg(basekey),QString::number(count + 1));
}
Ilwis::context()->configurationRef().addValue(key + "/url", res.url().toString());
Ilwis::context()->configurationRef().addValue(key + "/type", QString::number(res.ilwisType()));
}
};
QSqlQuery stmt(Ilwis::kernel()->database());
int count = 0;
if (_view.fixedItemCount() == 0) {
QString query = QString("Insert into workspaces (workspaceid) values(%1)").arg(_view.id());
if(!stmt.exec(query))
return;
}
// we dont want to add ids that are already in the list so we collect all ids that we have laready added
std::set<QString> presentids;
for(auto item : _operations){
presentids.insert(item->id());
}
for(auto item : _data){
presentids.insert(item->id());
}
QStringList idlist = ids.split("|");
for(auto id : idlist){
if ( presentids.find(id) != presentids.end())
continue;
quint64 idn = id.toULongLong();
putInConfig(idn, count);
_view.addFixedItem(idn);
++count;
QString query = QString("Select workspaceid from workspace where workspaceid=%1 and itemid=%2").arg(_view.id()).arg(idn);
if (stmt.exec(query)) { // already there
if ( stmt.next()) {
continue;
}else{
query = QString("Insert into workspace (workspaceid, itemid) values(%1,%2)").arg(_view.id()).arg(idn);
if(!stmt.exec(query))
return;
}
}
}
QString availableWorkspaces = Ilwis::ilwisconfig("users/" + Ilwis::context()->currentUser() + "/workspaces",QString(""));
if ( availableWorkspaces.indexOf(name()) == -1){
if ( availableWorkspaces.size() > 0){
availableWorkspaces += "|";
}
availableWorkspaces += name();
Ilwis::context()->configurationRef().addValue("users/" + Ilwis::context()->currentUser() + "/workspaces",availableWorkspaces);
}
refresh(true);
emit dataChanged();
}
void WorkSpaceModel::removeItems(const QString& ids)
{
QStringList idlist = ids.split("|");
for(auto id : idlist){
_view.removeFixedItem(id.toULongLong());
}
}
bool WorkSpaceModel::isDefault() const
{
return resource().url().toString() == Ilwis::Catalog::DEFAULT_WORKSPACE;
}
void WorkSpaceModel::gatherItems() {
bool needRefresh = _refresh;
CatalogModel::gatherItems();
if ( needRefresh){
_operations.clear();
_data.clear();
for(auto iter=_currentItems.begin(); iter != _currentItems.end(); ++iter){
if ( (*iter)->type() & itOPERATIONMETADATA){
_operations.push_back(new OperationModel((*iter)->resource(),this));
}else if ( hasType((*iter)->type(), itILWISOBJECT)){
_data.push_back(*iter);
}
}
}
refresh(false);
}
QQmlListProperty<OperationModel> WorkSpaceModel::operations()
{
refresh(true);
gatherItems();
return QQmlListProperty<OperationModel>(this, _operations);
}
QQmlListProperty<ResourceModel> WorkSpaceModel::data()
{
refresh(true);
gatherItems();
return QQmlListProperty<ResourceModel>(this, _data);
}
| 32.843284 | 134 | 0.601 | ridoo |
b540a7da19f87979c62edb01e97ca03fe259f786 | 4,445 | cc | C++ | gnuradio-3.7.13.4/gr-blocks/lib/udp_sink_impl.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gr-blocks/lib/udp_sink_impl.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gr-blocks/lib/udp_sink_impl.cc | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | /* -*- c++ -*- */
/*
* Copyright 2007-2010,2013 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* GNU Radio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "udp_sink_impl.h"
#include <gnuradio/io_signature.h>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/format.hpp>
#include <gnuradio/thread/thread.h>
#include <stdexcept>
#include <stdio.h>
#include <string.h>
namespace gr {
namespace blocks {
udp_sink::sptr
udp_sink::make(size_t itemsize,
const std::string &host, int port,
int payload_size, bool eof)
{
return gnuradio::get_initial_sptr
(new udp_sink_impl(itemsize, host, port,
payload_size, eof));
}
udp_sink_impl::udp_sink_impl(size_t itemsize,
const std::string &host, int port,
int payload_size, bool eof)
: sync_block("udp_sink",
io_signature::make(1, 1, itemsize),
io_signature::make(0, 0, 0)),
d_itemsize(itemsize), d_payload_size(payload_size), d_eof(eof),
d_connected(false)
{
// Get the destination address
connect(host, port);
}
// public constructor that returns a shared_ptr
udp_sink_impl::~udp_sink_impl()
{
if(d_connected)
disconnect();
}
void
udp_sink_impl::connect(const std::string &host, int port)
{
if(d_connected)
disconnect();
std::string s_port = (boost::format("%d")%port).str();
if(host.size() > 0) {
boost::asio::ip::udp::resolver resolver(d_io_service);
boost::asio::ip::udp::resolver::query query(host, s_port,
boost::asio::ip::resolver_query_base::passive);
d_endpoint = *resolver.resolve(query);
d_socket = new boost::asio::ip::udp::socket(d_io_service);
d_socket->open(d_endpoint.protocol());
boost::asio::socket_base::reuse_address roption(true);
d_socket->set_option(roption);
d_connected = true;
}
}
void
udp_sink_impl::disconnect()
{
if(!d_connected)
return;
gr::thread::scoped_lock guard(d_mutex); // protect d_socket from work()
// Send a few zero-length packets to signal receiver we are done
boost::array<char, 0> send_buf;
if(d_eof) {
int i;
for(i = 0; i < 3; i++)
d_socket->send_to(boost::asio::buffer(send_buf), d_endpoint);
}
d_socket->close();
delete d_socket;
d_connected = false;
}
int
udp_sink_impl::work (int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const char *in = (const char *) input_items[0];
ssize_t r=0, bytes_sent=0, bytes_to_send=0;
ssize_t total_size = noutput_items*d_itemsize;
gr::thread::scoped_lock guard(d_mutex); // protect d_socket
while(bytes_sent < total_size) {
bytes_to_send = std::min((ssize_t)d_payload_size, (total_size-bytes_sent));
if(d_connected) {
try {
r = d_socket->send_to(boost::asio::buffer((void*)(in+bytes_sent), bytes_to_send),
d_endpoint);
}
catch(std::exception& e) {
GR_LOG_ERROR(d_logger, boost::format("send error: %s") % e.what());
return -1;
}
}
else
r = bytes_to_send; // discarded for lack of connection
bytes_sent += r;
}
return noutput_items;
}
} /* namespace blocks */
} /* namespace gr */
| 29.633333 | 99 | 0.59775 | v1259397 |
b540c007a1b8eae68ab5d008e6367ee34bc0f2f1 | 874 | cpp | C++ | tests/test_postgres.cpp | shakfu/prolog | 9d6621e3e723b0bd899bd963fe4a4125cf57671c | [
"Unlicense"
] | null | null | null | tests/test_postgres.cpp | shakfu/prolog | 9d6621e3e723b0bd899bd963fe4a4125cf57671c | [
"Unlicense"
] | null | null | null | tests/test_postgres.cpp | shakfu/prolog | 9d6621e3e723b0bd899bd963fe4a4125cf57671c | [
"Unlicense"
] | null | null | null | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <iostream>
#include <pqxx/pqxx>
#include "doctest.h"
int test_db()
{
// Connect to the database.
pqxx::connection c{"postgresql://sa@localhost/sa"};
std::cout << "Connected to " << c.dbname() << '\n';
// Start a transaction.
pqxx::work W{c};
// Perform a query and retrieve all results.
pqxx::result R{W.exec("SELECT name FROM employee")};
// Iterate over results.
std::cout << "Found " << R.size() << "employees:\n";
for (auto row: R)
std::cout << row[0].c_str() << '\n';
// Perform a query and check that it returns no result.
std::cout << "Doubling all employees' salaries...\n";
W.exec0("UPDATE employee SET salary = salary*2");
// Commit the transaction.
std::cout << "Making changes definite: ";
W.commit();
std::cout << "OK.\n";
}
| 25.705882 | 59 | 0.606407 | shakfu |
b5411852752a697187ec98f85ca8f93b27502af6 | 297 | cpp | C++ | Demos3/BasicDemoConsole/main.cpp | jackoalan/bullet3 | 4276b2f06aa652a00b798666ae68013fc6c950e3 | [
"Zlib"
] | 5 | 2015-07-28T09:07:57.000Z | 2020-09-24T16:49:45.000Z | Demos3/BasicDemoConsole/main.cpp | jackoalan/bullet3 | 4276b2f06aa652a00b798666ae68013fc6c950e3 | [
"Zlib"
] | null | null | null | Demos3/BasicDemoConsole/main.cpp | jackoalan/bullet3 | 4276b2f06aa652a00b798666ae68013fc6c950e3 | [
"Zlib"
] | null | null | null |
#include <stdio.h>
#include "../../Demos/BasicDemo/BasicDemoPhysicsSetup.h"
int main(int argc, char* argv[])
{
BasicDemoPhysicsSetup physicsSetup;
GraphicsPhysicsBridge br;
physicsSetup.initPhysics(br);
physicsSetup.stepSimulation(1./60.);
physicsSetup.exitPhysics();
printf("hello\n");
} | 21.214286 | 56 | 0.750842 | jackoalan |
b542c209363518732ebf5fa53cb22732a7b7bb82 | 521 | cpp | C++ | oop/hw4/main.cpp | vMihtarska/fmi | 3a3413ff410648ea9dcc00ba394dc216b1ba5df3 | [
"MIT"
] | null | null | null | oop/hw4/main.cpp | vMihtarska/fmi | 3a3413ff410648ea9dcc00ba394dc216b1ba5df3 | [
"MIT"
] | null | null | null | oop/hw4/main.cpp | vMihtarska/fmi | 3a3413ff410648ea9dcc00ba394dc216b1ba5df3 | [
"MIT"
] | 1 | 2016-01-20T19:02:10.000Z | 2016-01-20T19:02:10.000Z | #include <iostream>
#include "Employee.h"
#include "Specialist.h"
int main()
{
Employee g;
g.SetName("VASI");
g.SetAddress("JK ZAPAD");
g.SetEGN("9508110056");
g.SetDepartment("IT");
g.SetSalary(100);
g.Print();
Employee c(g);
c.Print();
Employee m;
m = g;
m.Print();
Specialist x;
x.SetName("VASI");
x.SetAddress("JK ZAPAD");
x.SetEGN("9508110056");
x.SetDepartment("IT");
x.SetSalary(100);
x.SetDescription("PENCHO");
x.Print();
Specialist l(x);
l.Print();
Specialist y;
y = l;
y.Print();
} | 14.885714 | 28 | 0.635317 | vMihtarska |
b5471770a3d009f4980cce0666488fe6b57f0b3d | 1,080 | hpp | C++ | include/gui/slider.hpp | MartinKondor/Rule | 1e5b7f611a2252112d091f27952fa5180e5fad19 | [
"BSD-3-Clause"
] | null | null | null | include/gui/slider.hpp | MartinKondor/Rule | 1e5b7f611a2252112d091f27952fa5180e5fad19 | [
"BSD-3-Clause"
] | null | null | null | include/gui/slider.hpp | MartinKondor/Rule | 1e5b7f611a2252112d091f27952fa5180e5fad19 | [
"BSD-3-Clause"
] | null | null | null | #ifndef SLIDER_HPP
#define SLIDER_HPP
#include <SFML/Graphics.hpp>
#include "config.hpp"
#include "utils.hpp"
extern Config CONFIG;
class Slider
{
/**
A Slider.
Example usage:
```
Slider slider(100, 100, gameFont);
slider.create(20, 450);
slider.setSliderValue(235);
...
slider.draw(window);
...
```
*/
public:
unsigned int xPos;
unsigned int yPos;
unsigned int minValue;
unsigned int maxValue;
unsigned int axisWidth;
unsigned int axisHeight;
unsigned int sliderWidth;
unsigned int sliderHeight;
float sliderValue;
sf::RectangleShape slider;
sf::RectangleShape axis;
sf::Text text;
Slider();
Slider(const unsigned int xPos, const unsigned int yPos, const unsigned int min, const unsigned int max);
sf::Text returnText(const unsigned int x, const unsigned int y, const std::string z);
void setSliderValue(const float newValue);
void setSliderPercentValue(const float newPercentValue);
void display(sf::RenderWindow &window);
};
#endif // SLIDER_HPP
| 20.377358 | 109 | 0.675926 | MartinKondor |
b551b82b7cfd1c3bd1322d08423e3d745eff3f89 | 1,284 | hpp | C++ | libraries/chain/include/graphene/chain/is_authorized_asset.hpp | EDCBlockchain/blockchain | 41c74b981658d79d770b075191cfb14faeb84dab | [
"MIT"
] | 12 | 2019-10-31T13:24:21.000Z | 2021-12-29T22:02:22.000Z | libraries/chain/include/graphene/chain/is_authorized_asset.hpp | DONOVA28/blockchain | 41c74b981658d79d770b075191cfb14faeb84dab | [
"MIT"
] | null | null | null | libraries/chain/include/graphene/chain/is_authorized_asset.hpp | DONOVA28/blockchain | 41c74b981658d79d770b075191cfb14faeb84dab | [
"MIT"
] | 11 | 2019-07-24T12:46:29.000Z | 2021-11-27T04:41:48.000Z | // see LICENSE.txt
#pragma once
#include <map>
#include <typeindex>
#include <typeinfo>
namespace graphene { namespace chain {
class account_object;
class asset_object;
class database;
namespace detail {
bool _is_authorized_asset(const database& d, const account_object& acct, const asset_object& asset_obj);
} // ns detail
enum directionality_type
{
receiver = 0x2,
payer = 0x4,
};
inline bool not_restricted_account(const database& d, const account_object& acct, uint8_t type)
{
const auto& idx = d.get_index_type<restricted_account_index>().indices().get<by_acc_id>();
auto itr = idx.find(acct.id);
if (itr == idx.end()) {
return true;
}
if (itr->restriction_type && (type & *itr->restriction_type)) {
return false;
}
return true;
}
/**
* @return true if the account is whitelisted and not blacklisted to transact in the provided asset; false
* otherwise.
*/
inline bool is_authorized_asset(const database& d, const account_object& acct, const asset_object& asset_obj)
{
bool fast_check = !(asset_obj.options.flags & white_list);
fast_check &= !(acct.allowed_assets.valid());
if( fast_check )
return true;
bool slow_check = detail::_is_authorized_asset( d, acct, asset_obj );
return slow_check;
}
} }
| 21.04918 | 109 | 0.707165 | EDCBlockchain |
b551f72109fe10ceb9b8a4495fa3bdc20b116af0 | 181 | cpp | C++ | apps/src/videostitch-studio-gui/src/videostitcher/globalpostprodcontroller.cpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | apps/src/videostitch-studio-gui/src/videostitcher/globalpostprodcontroller.cpp | doymcc/stitchEm | 20693a55fa522d7a196b92635e7a82df9917c2e2 | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | apps/src/videostitch-studio-gui/src/videostitcher/globalpostprodcontroller.cpp | doymcc/stitchEm | 20693a55fa522d7a196b92635e7a82df9917c2e2 | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | // Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#include "globalpostprodcontroller.hpp"
template class GlobalControllerImpl<PostProdStitcherController>;
| 25.857143 | 64 | 0.812155 | tlalexander |
b5540a76ef968039f9bb0b1b4f004503836c27c4 | 1,127 | hpp | C++ | main_server/src/entities/parking_slot/parking_slot.hpp | GrassoMichele/uPark | d96310c165c3efa9b0251c51ababe06639c4570a | [
"MIT"
] | null | null | null | main_server/src/entities/parking_slot/parking_slot.hpp | GrassoMichele/uPark | d96310c165c3efa9b0251c51ababe06639c4570a | [
"MIT"
] | null | null | null | main_server/src/entities/parking_slot/parking_slot.hpp | GrassoMichele/uPark | d96310c165c3efa9b0251c51ababe06639c4570a | [
"MIT"
] | null | null | null | #ifndef PARKING_SLOT
#define PARKING_SLOT
#include <iostream>
class ParkingSlot{
private:
int id;
int number;
int id_parking_lot;
int id_vehicle_type;
bool reserved_disability;
public:
ParkingSlot();
ParkingSlot(int id);
ParkingSlot(int id, int number, int id_parking_lot, int id_vehicle_type, bool reserved_disability);
void setId(int);
// void setNumber(int);
// void setIdParkingLot(int);
void setIdVehicleType(int);
void setReservedDisability(bool);
int getId() const;
int getNumber() const;
int getIdParkingLot() const;
int getIdVehicleType() const;
bool getReservedDisability() const;
friend bool operator== (const ParkingSlot&, const ParkingSlot&);
friend std::ostream& operator<<(std::ostream& os, const ParkingSlot&);
};
// class ParkingSlotException : public std::exception {
// std::string _message;
// public:
// ParkingSlotException(const std::string & message);
// const char * what() const throw();
// };
#endif
| 26.209302 | 107 | 0.628217 | GrassoMichele |
b557c25ffa9d5306eaaaeb39bee702d02cacda66 | 6,834 | hpp | C++ | include/pkmn/types/class_with_attributes.hpp | ncorgan/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 4 | 2017-06-10T13:21:44.000Z | 2019-10-30T21:20:19.000Z | include/pkmn/types/class_with_attributes.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 12 | 2017-04-05T11:13:34.000Z | 2018-06-03T14:31:03.000Z | include/pkmn/types/class_with_attributes.hpp | PMArkive/libpkmn | c683bf8b85b03eef74a132b5cfdce9be0969d523 | [
"MIT"
] | 2 | 2019-01-22T21:02:31.000Z | 2019-10-30T21:20:20.000Z | /*
* Copyright (c) 2017-2018 Nicholas Corgan (n.corgan@gmail.com)
*
* Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
* or copy at http://opensource.org/licenses/MIT)
*/
#ifndef PKMN_CLASS_WITH_ATTRIBUTES_HPP
#define PKMN_CLASS_WITH_ATTRIBUTES_HPP
#include <pkmn/types/attribute_engine.hpp>
namespace pkmn {
/*!
* @brief A base class that gives derived classes the ability to get and
* set numeric, string, and boolean attributes.
*
* Note that some attributes are read-only.
*/
class class_with_attributes
{
public:
#ifndef __DOXYGEN__
class_with_attributes() {}
~class_with_attributes () {}
#endif
/*!
* @brief Query the numeric attribute with the given name.
*
* \param attribute_name The name of the attribute to query
* \throws std::invalid_argument If the given attribute name doesn't exist
*/
inline int get_numeric_attribute(
const std::string& attribute_name
)
{
return _numeric_attribute_engine.get_attribute(attribute_name);
}
/*!
* @brief Sets the numeric attribute with the given name to the given
* value.
*
* Along with the errors listed below, the attribute setter can throw
* any of its own errors based on value range, etc.
*
* \param attribute_name The name of the attribute whose value to set
* \param value The new value for the attribute
* \throws std::invalid_argument If the given attribute name doesn't exist
* \throws std::invalid_argument If the given attribute is valid but read-only
*/
inline void set_numeric_attribute(
const std::string& attribute_name,
int value
)
{
_numeric_attribute_engine.set_attribute(attribute_name, value);
}
/*!
* @brief Returns the full list of numeric attributes.
*
* All attributes can be read, so all values returned from this
* function are valid inputs for get_numeric_attribute(). Some
* attributes are read-only and are thus invalid inputs for
* set_numeric_attribute().
*/
inline std::vector<std::string> get_numeric_attribute_names()
{
return _numeric_attribute_engine.get_attribute_names();
}
/*!
* @brief Query the string attribute with the given name.
*
* \param attribute_name The name of the attribute to query
* \throws std::invalid_argument If the given attribute name doesn't exist
*/
inline std::string get_string_attribute(
const std::string& attribute_name
)
{
return _string_attribute_engine.get_attribute(attribute_name);
}
/*!
* @brief Sets the string attribute with the given name to the given
* value.
*
* Along with the errors listed below, the attribute setter can throw
* any of its own errors based on value range, etc.
*
* \param attribute_name The name of the attribute whose value to set
* \param value The new value for the attribute
* \throws std::invalid_argument If the given attribute name doesn't exist
* \throws std::invalid_argument If the given attribute is valid but read-only
*/
inline void set_string_attribute(
const std::string& attribute_name,
const std::string& value
)
{
_string_attribute_engine.set_attribute(attribute_name, value);
}
/*!
* @brief Returns the full list of string attributes.
*
* All attributes can be read, so all values returned from this
* function are valid inputs for get_string_attribute(). Some
* attributes are read-only and are thus invalid inputs for
* set_string_attribute().
*/
inline std::vector<std::string> get_string_attribute_names()
{
return _string_attribute_engine.get_attribute_names();
}
/*!
* @brief Query the boolean attribute with the given name.
*
* \param attribute_name The name of the attribute to query
* \throws std::invalid_argument If the given attribute name doesn't exist
*/
inline bool get_boolean_attribute(
const std::string& attribute_name
)
{
return _boolean_attribute_engine.get_attribute(attribute_name);
}
/*!
* @brief Sets the boolean attribute with the given name to the given
* value.
*
* Along with the errors listed below, the attribute setter can throw
* any of its own errors based on value range, etc.
*
* \param attribute_name The name of the attribute whose value to set
* \param value The new value for the attribute
* \throws std::invalid_argument If the given attribute name doesn't exist
* \throws std::invalid_argument If the given attribute is valid but read-only
*/
inline void set_boolean_attribute(
const std::string& attribute_name,
bool value
)
{
_boolean_attribute_engine.set_attribute(attribute_name, value);
}
/*!
* @brief Returns the full list of boolean attributes.
*
* All attributes can be read, so all values returned from this
* function are valid inputs for get_boolean_attribute(). Some
* attributes are read-only and are thus invalid inputs for
* set_boolean_attribute().
*/
inline std::vector<std::string> get_boolean_attribute_names()
{
return _boolean_attribute_engine.get_attribute_names();
}
protected:
pkmn::attribute_engine<int> _numeric_attribute_engine;
pkmn::attribute_engine<std::string> _string_attribute_engine;
pkmn::attribute_engine<bool> _boolean_attribute_engine;
};
}
#endif /* PKMN_CLASS_WITH_ATTRIBUTES_HPP */
| 39.275862 | 90 | 0.567603 | ncorgan |
b55996a5dcbe09175c97dccc3a46f70f57def379 | 1,491 | cpp | C++ | cpp/test/test_prefix128.cpp | 0xflotus/ipaddress | 0d53ff453ec901e408ef28435802318282e43ccc | [
"MIT"
] | 11 | 2017-09-28T09:14:28.000Z | 2021-11-01T07:24:41.000Z | cpp/test/test_prefix128.cpp | 0xflotus/ipaddress | 0d53ff453ec901e408ef28435802318282e43ccc | [
"MIT"
] | 1 | 2016-08-31T06:55:54.000Z | 2016-08-31T06:55:54.000Z | cpp/test/test_prefix128.cpp | 0xflotus/ipaddress | 0d53ff453ec901e408ef28435802318282e43ccc | [
"MIT"
] | 4 | 2016-08-31T06:45:32.000Z | 2021-05-13T10:31:03.000Z |
#include <cascara/cascara.hpp>
using namespace cascara;
#include "../src/prefix128.hpp"
#include "../src/crunchy.hpp"
using namespace ipaddress;
class Prefix128Test {
public:
std::vector<std::pair<size_t, Crunchy>> u128_hash;
};
Prefix128Test setup() {
Prefix128Test p128t;
p128t.u128_hash.push_back({32, Crunchy::parse("340282366841710300949110269838224261120").unwrap()});
p128t.u128_hash.push_back({64, Crunchy::parse("340282366920938463444927863358058659840").unwrap()});
p128t.u128_hash.push_back({96, Crunchy::parse("340282366920938463463374607427473244160").unwrap()});
p128t.u128_hash.push_back({126, Crunchy::parse("340282366920938463463374607431768211452").unwrap()});
return p128t;
}
int main() {
describe("prefix128", []() {
it("test_initialize", []() {
assert.isTrue(Prefix128::create(129).isErr());
assert.isTrue(Prefix128::create(64).isOk());
});
it("test_method_bits", []() {
auto prefix = Prefix128::create(64).unwrap();
std::stringstream str;
for (auto i = 0; i < 64; ++i) {
str << "1";
}
for (auto i = 0; i < 64; ++i) {
str << "0";
}
assert.equal(str.str(), prefix.bits());
});
it("test_method_to_u32", []() {
for (auto hash : setup().u128_hash) {
assert.isTrue(hash.second.eq(Prefix128::create(hash.first)->netmask()));
}
});
});
return exit();
}
| 29.235294 | 109 | 0.60161 | 0xflotus |
b559f6970bb54e4e750405f64b34fb16553d1021 | 8,652 | cpp | C++ | Socket/IncomingMessageHandler.cpp | Kaptnik/CIS-687-RemoteTestHarness | 3a1466d4b71cef7bee2791020a2902d3e658fb64 | [
"MIT"
] | null | null | null | Socket/IncomingMessageHandler.cpp | Kaptnik/CIS-687-RemoteTestHarness | 3a1466d4b71cef7bee2791020a2902d3e658fb64 | [
"MIT"
] | null | null | null | Socket/IncomingMessageHandler.cpp | Kaptnik/CIS-687-RemoteTestHarness | 3a1466d4b71cef7bee2791020a2902d3e658fb64 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////
// IncomingMessageHandler.cpp - A class that handles incoming messages //
// ver 1.0 //
// Karthik Umashankar, CSE687 - Object Oriented Design, Summer 2018 //
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "IncomingMessageHandler.h"
#include "..\Utilities\Credentials.h"
#include "..\Utilities\Converter.h"
#include "..\Utilities\Directory.h"
#include "..\Utilities\File.h"
#include "..\Utilities\Logger.h"
#include <objbase.h>
#include <fstream>
using namespace Sockets;
const int BLOCK_SIZE = 102400;
// Set the test request queue
void IncomingMessageHandler::SetTestRequestQueue(BlockingQueue<Message>* queuePointer)
{
_testRequestQPtr = queuePointer;
}
// Set the ready worker queue
void IncomingMessageHandler::SetReadyWorkerQueue(BlockingQueue<Sockets::Message>* queuePointer)
{
_readyWorkerQPtr = queuePointer;
}
// Set the sender queue
void IncomingMessageHandler::SetSendMessageQueue(BlockingQueue<Sockets::Message>* queuePointer)
{
_sendMessageQPtr = queuePointer;
}
void IncomingMessageHandler::SetRecvMessageQueue(BlockingQueue<Sockets::Message>* queuePointer)
{
_recvMessageQPtr = queuePointer;
}
void IncomingMessageHandler::SetContext(Sockets::CONTEXT context)
{
_context = context;
}
// Read a message from a socket as a string
std::string IncomingMessageHandler::ReadMessage()
{
std::string temp, message;
char* buffer = new char[BLOCK_SIZE];
size_t blockSize;
if (_socketPointer->IsValidState())
{
blockSize = _socketPointer->ReceiveStream(BLOCK_SIZE, buffer);
if (blockSize > 0)
{
temp = buffer;
message += temp.substr(0, blockSize);
}
}
delete(buffer);
return message;
}
// Receive a file if send on the socket
bool IncomingMessageHandler::ReceiveFile(Message message)
{
size_t filesize = message.GetContentLength();
if (filesize == 0)
return false;
std::string downloadLocation;
downloadLocation = message.GetFilename();
// If acting as the server, prefix the repository
if (_context == Sockets::CONTEXT::SERVER)
{
if (downloadLocation.substr(0, 12) == "TestResults_")
downloadLocation = "TESTRESULTS/" + downloadLocation;
else
downloadLocation = "REPOSITORY/" + downloadLocation;
}
std::ofstream outstream(downloadLocation, std::ios::binary);
if (!outstream.good())
{
return false;
}
std::string body = message.GetBody();
std::string decodedBody = Utilities::Convert::Base64Decode(body);
outstream.write(decodedBody.c_str(), decodedBody.length());
outstream.flush();
outstream.close();
return true;
}
Message* IncomingMessageHandler::BuildResponse(Message& incomingMessage)
{
Message *response = new Message();
response->SetSource(incomingMessage.GetDestination());
response->SetDestination(incomingMessage.GetSource());
return response;
}
// Overloading the () operator to make this a functor
void IncomingMessageHandler::operator()(Socket socket)
{
std::string logMessage;
_socketPointer = &socket;
while (_socketPointer->IsValidState())
{
// Read a message from the socket
std::string messageString = ReadMessage();
if (messageString.length() == 0 || messageString.length() >= BLOCK_SIZE)
break;
// Deserialize it to a message object
Message *message = new Message(messageString);
std::string body = message->GetBody();
body.erase(std::remove(body.begin(), body.end(), '\n'), body.end());
message->SetBody(body);
// If message type is to get a file, respond with one.
if (message->GetType() == MessageType::FILE_GET)
{
std::string filepath = "REPOSITORY" + message->GetBody();
std::string fileContents = Utilities::File::GetFileContents(filepath);
Message* file = BuildResponse(*message);
file->SetType(MessageType::FILE_POST);
file->SetBody(fileContents);
file->SetContentLength(fileContents.length());
file->SetFilename(message->GetFilename());
logMessage = "Sending file " + filepath + " to " + message->GetSource().AsString();
Utilities::Logger::Log(logMessage.c_str());
_sendMessageQPtr->EnQueue(*file);
continue;
}
// If it's a mkdir request, create a directory
else if (message->GetType() == MessageType::FILE_MKDIR)
{
std::string directory = "REPOSITORY" + message->GetBody();
CreateDirectory(directory.c_str(), NULL);
continue;
}
// If it's a posted file, download it
else if (message->GetType() == MessageType::FILE_POST)
{
logMessage = "Received a file (" + message->GetFilename() + ") with MessageID (" + message->GetMessageId() + ") from " + message->GetSource().AsString();
Utilities::Logger::Log(logMessage.c_str());
ReceiveFile(*message);
continue;
}
// If it's a request to list a directory
else if (message->GetType() == MessageType::FILE_LIST)
{
if (_context == Sockets::CONTEXT::SERVER)
{
std::string directory = "REPOSITORY" + message->GetBody();
Message* list = BuildResponse(*message);
list->SetType(MessageType::FILE_LIST);
list->SetBody(Utilities::Convert::ListToString(Utilities::Directory::GetFileSystemEntries(directory), ","));
list->SetContentLength(0);
_sendMessageQPtr->EnQueue(*list);
continue;
}
}
// If it's a test request, queue it up in the
// TestRequestQ, and send an acknowledgement back
// to the client
else if (message->GetType() == MessageType::TEST_REQUEST)
{
if (message->GetSource().GetUriHost() == "")
break;
logMessage = "Received a test request (" + message->GetMessageId() + ") from " + message->GetSource().AsString();
Utilities::Logger::Log(logMessage.c_str());
_testRequestQPtr->EnQueue(*message);
Message *ack = BuildResponse(*message);
ack->SetType(MessageType::TEST_ACKNOWLEDGE);
ack->SetBody(message->GetMessageId());
logMessage = "Sending acknowledgement of test request to " + message->GetSource().AsString();
Utilities::Logger::Log(logMessage.c_str());
_sendMessageQPtr->EnQueue(*ack);
continue;
}
// If it's a worker signaling they're ready,
// Queue them up in the ReadyWorkerQ
else if (message->GetType() == MessageType::SIGNAL_READY)
{
logMessage = "Worker process on " + message->GetSource().AsString() + " is ready";
Utilities::Logger::Log(logMessage.c_str());
_readyWorkerQPtr->EnQueue(*message);
continue;
}
// If it's a SHUTDOWN message from self, stop
else if (message->GetType() == MessageType::SIGNAL_SHUTDOWN)
break;
else if (message->GetType() == MessageType::USER_AUTHENTICATE)
{
if (_context == Sockets::CONTEXT::SERVER)
{
std::vector<std::string> credentials = Utilities::Convert::StringToList(message->GetBody());
std::string username, password;
for (std::string kvp : credentials)
{
size_t index = kvp.find_first_of(':');
if (index == kvp.length())
continue;
std::string key = kvp.substr(0, index), value = kvp.substr(index + 1, kvp.length() - index);
if (key == "username")
username = value;
if (key == "password")
password = value;
}
Utilities::User *user = Utilities::Credentials::Login("authentication.txt", username, password);
Message *response = BuildResponse(*message);
response->SetType(MessageType::USER_AUTHENTICATE);
if (user != nullptr)
{
std::string body = "authenticated:1,fullname:" + user->Fullname;
if (user->IsAdmin)
body += ",isadmin:1";
response->SetBody(body);
}
_sendMessageQPtr->EnQueue(*response);
continue;
}
}
else if (message->GetType() == MessageType::USER_REGISTER)
{
Utilities::User user;
for (std::string kvp : Utilities::Convert::StringToList(message->GetBody()))
{
size_t index = kvp.find_first_of(':');
if (index == kvp.length())
continue;
std::string key = kvp.substr(0, index), value = kvp.substr(index + 1, kvp.length() - index);
if (key == "username")
user.Username = value;
else if (key == "password")
user.Password = value;
else if (key == "isadmin")
{
if (value == "0")
user.IsAdmin = false;
else
user.IsAdmin = true;
}
else if (key == "fullname")
user.Fullname = value;
}
Utilities::Credentials::RegisterUser("authentication.txt", user);
continue;
}
if (_context != Sockets::CONTEXT::SERVER)
_recvMessageQPtr->EnQueue(*message);
}
} | 32.526316 | 157 | 0.654877 | Kaptnik |
b55bbe41b23916a348b6e2d5146b9e5a83197e9d | 8,360 | cpp | C++ | Engine/Source/Runtime/ApplicationCore/Private/Mac/MacConsoleOutputDevice.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Runtime/ApplicationCore/Private/Mac/MacConsoleOutputDevice.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Runtime/ApplicationCore/Private/Mac/MacConsoleOutputDevice.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "MacConsoleOutputDevice.h"
#include "Misc/App.h"
#include "Misc/CoreDelegates.h"
#include "Misc/ConfigCacheIni.h"
#include "MacApplication.h"
#include "MacPlatformApplicationMisc.h"
#include "Misc/OutputDeviceHelper.h"
#include "Misc/ScopeLock.h"
#include "CocoaThread.h"
#include "HAL/PlatformApplicationMisc.h"
FMacConsoleOutputDevice::FMacConsoleOutputDevice()
: ConsoleHandle(NULL)
, TextView(NULL)
, ScrollView(NULL)
, TextViewTextColor(NULL)
, OutstandingTasks(0)
{
}
FMacConsoleOutputDevice::~FMacConsoleOutputDevice()
{
DestroyConsole();
}
void FMacConsoleOutputDevice::SaveToINI()
{
if (GConfig && IniFilename.Len())
{
NSRect Frame = [ConsoleHandle frame];
GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleWidth"), Frame.size.width, IniFilename);
GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleHeight"), Frame.size.height, IniFilename);
GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleX"), Frame.origin.x, IniFilename);
GConfig->SetInt(TEXT("DebugMac"), TEXT("ConsoleY"), Frame.origin.y, IniFilename);
}
}
void FMacConsoleOutputDevice::CreateConsole()
{
if (ConsoleHandle || GIsBuildMachine)
{
return;
}
SCOPED_AUTORELEASE_POOL;
int32 ConsoleWidth = 800;
int32 ConsoleHeight = 600;
int32 ConsolePosX = 0;
int32 ConsolePosY = 0;
bool bHasX = false;
bool bHasY = false;
if(GConfig)
{
GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleWidth"), ConsoleWidth, GGameIni);
GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleHeight"), ConsoleHeight, GGameIni);
bHasX = GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleX"), ConsolePosX, GGameIni);
bHasY = GConfig->GetInt(TEXT("DebugMac"), TEXT("ConsoleY"), ConsolePosY, GGameIni);
}
MainThreadCall(^{
ConsoleHandle = [[FMacConsoleWindow alloc] initWithContentRect: NSMakeRect(ConsolePosX, ConsolePosY, ConsoleWidth, ConsoleHeight)
styleMask: (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask)
backing: NSBackingStoreBuffered
defer: NO];
[ConsoleHandle setDelegate:ConsoleHandle];
ScrollView = [[NSScrollView alloc] initWithFrame:[[ConsoleHandle contentView] frame]];
NSSize ContentSize = [ScrollView contentSize];
[ScrollView setBorderType:NSNoBorder];
[ScrollView setHasVerticalScroller:YES];
[ScrollView setHasHorizontalScroller:NO];
[ScrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
TextView = [[NSTextView alloc] initWithFrame:NSMakeRect( 0, 0, ContentSize.width, ContentSize.height )];
[TextView setMinSize:NSMakeSize( 0.0, ContentSize.height ) ];
[TextView setMaxSize:NSMakeSize( FLT_MAX, FLT_MAX )];
[TextView setVerticallyResizable:YES];
[TextView setHorizontallyResizable:NO];
[TextView setAutoresizingMask:NSViewWidthSizable];
[TextView setBackgroundColor: [NSColor blackColor]];
[[TextView textContainer] setContainerSize:NSMakeSize( ContentSize.width, FLT_MAX )];
[[TextView textContainer] setWidthTracksTextView:YES];
[ScrollView setDocumentView:TextView];
[ConsoleHandle setContentView:ScrollView];
if (!bHasX || !bHasY)
{
[ConsoleHandle center];
}
[ConsoleHandle setOpaque:YES];
[ConsoleHandle makeKeyAndOrderFront:nil];
if(!MacApplication)
{
do
{
FMacPlatformApplicationMisc::PumpMessages( true );
} while(ConsoleHandle && ![ConsoleHandle isVisible]);
}
SetDefaultTextColor();
}, UE4NilEventMode, true);
}
void FMacConsoleOutputDevice::DestroyConsole()
{
if (ConsoleHandle)
{
do
{
FMacPlatformApplicationMisc::PumpMessages( true );
} while(OutstandingTasks);
SaveToINI();
MainThreadCall(^{
SCOPED_AUTORELEASE_POOL;
if( TextViewTextColor )
[TextViewTextColor release];
[ConsoleHandle close];
ConsoleHandle = NULL;
TextViewTextColor = NULL;
}, UE4NilEventMode, true);
}
}
void FMacConsoleOutputDevice::Show( bool ShowWindow )
{
if( ShowWindow )
{
CreateConsole();
}
else
{
DestroyConsole();
}
}
bool FMacConsoleOutputDevice::IsShown()
{
return ConsoleHandle != NULL;
}
void FMacConsoleOutputDevice::Serialize( const TCHAR* Data, ELogVerbosity::Type Verbosity, const class FName& Category )
{
if( ConsoleHandle )
{
FScopeLock ScopeLock( &CriticalSection );
static bool Entry=0;
if( !GIsCriticalError || Entry )
{
// here we can change the color of the text to display, it's in the format:
// ForegroundRed | ForegroundGreen | ForegroundBlue | ForegroundBright | BackgroundRed | BackgroundGreen | BackgroundBlue | BackgroundBright
// where each value is either 0 or 1 (can leave off trailing 0's), so
// blue on bright yellow is "00101101" and red on black is "1"
// An empty string reverts to the normal gray on black
if (Verbosity == ELogVerbosity::SetColor)
{
if (FCString::Stricmp(Data, TEXT("")) == 0)
{
SetDefaultTextColor();
}
else
{
SCOPED_AUTORELEASE_POOL;
// turn the string into a bunch of 0's and 1's
TCHAR String[9];
FMemory::Memset(String, 0, sizeof(TCHAR) * ARRAY_COUNT(String));
FCString::Strncpy(String, Data, ARRAY_COUNT(String));
for (TCHAR* S = String; *S; S++)
{
*S -= '0';
}
NSMutableArray* Colors = [[NSMutableArray alloc] init];
NSMutableArray* AttributeKeys = [[NSMutableArray alloc] init];
// Get FOREGROUND_INTENSITY and calculate final color
CGFloat Intensity = String[3] ? 1.0 : 0.5;
[Colors addObject:[NSColor colorWithSRGBRed:(String[0] ? 1.0 * Intensity : 0.0) green:(String[1] ? 1.0 * Intensity : 0.0) blue:(String[2] ? 1.0 * Intensity : 0.0) alpha:1.0]];
// Get BACKGROUND_INTENSITY and calculate final color
Intensity = String[7] ? 1.0 : 0.5;
[Colors addObject:[NSColor colorWithSRGBRed:(String[4] ? 1.0 * Intensity : 0.0) green:(String[5] ? 1.0 * Intensity : 0.0) blue:(String[6] ? 1.0 * Intensity : 0.0) alpha:1.0]];
[AttributeKeys addObject:NSForegroundColorAttributeName];
[AttributeKeys addObject:NSBackgroundColorAttributeName];
OutstandingTasks++;
MainThreadCall(^{
if( TextViewTextColor )
[TextViewTextColor release];
TextViewTextColor = [[NSDictionary alloc] initWithObjects:Colors forKeys:AttributeKeys];
[Colors release];
[AttributeKeys release];
OutstandingTasks--;
}, NSDefaultRunLoopMode, false);
}
}
else
{
SCOPED_AUTORELEASE_POOL;
TCHAR OutputString[MAX_SPRINTF]=TEXT(""); //@warning: this is safe as FCString::Sprintf only use 1024 characters max
FCString::Sprintf(OutputString,TEXT("%s%s"),*FOutputDeviceHelper::FormatLogLine(Verbosity, Category, Data, GPrintLogTimes),LINE_TERMINATOR);
CFStringRef CocoaText = FPlatformString::TCHARToCFString(OutputString);
OutstandingTasks++;
MainThreadCall(^{
NSAttributedString *AttributedString = [[NSAttributedString alloc] initWithString:(NSString*)CocoaText attributes:TextViewTextColor];
[[TextView textStorage] appendAttributedString:AttributedString];
[TextView scrollRangeToVisible:NSMakeRange([[TextView string] length], 0)];
[AttributedString release];
CFRelease(CocoaText);
OutstandingTasks--;
}, NSDefaultRunLoopMode, false);
if(!MacApplication)
{
FMacPlatformApplicationMisc::PumpMessages( true );
}
}
}
else
{
Entry=1;
try
{
// Ignore errors to prevent infinite-recursive exception reporting.
Serialize( Data, Verbosity, Category );
}
catch( ... )
{}
Entry=0;
}
}
}
void FMacConsoleOutputDevice::SetDefaultTextColor()
{
SCOPED_AUTORELEASE_POOL;
FScopeLock ScopeLock( &CriticalSection );
NSMutableArray* Colors = [[NSMutableArray alloc] init];
NSMutableArray* AttributeKeys = [[NSMutableArray alloc] init];
[Colors addObject:[NSColor grayColor]];
[Colors addObject:[NSColor blackColor]];
[AttributeKeys addObject:NSForegroundColorAttributeName];
[AttributeKeys addObject:NSBackgroundColorAttributeName];
OutstandingTasks++;
MainThreadCall(^{
if( TextViewTextColor )
[TextViewTextColor release];
TextViewTextColor = [[NSDictionary alloc] initWithObjects:Colors forKeys:AttributeKeys];
[Colors release];
[AttributeKeys release];
OutstandingTasks--;
}, NSDefaultRunLoopMode, false);
}
| 29.75089 | 180 | 0.71244 | windystrife |
b55be79846204fcc7725da9029f1c2ecec9edf9a | 1,029 | cpp | C++ | C++/dnf_sort.cpp | ayushyado/HACKTOBERFEST2021-2 | b63d568fd7f33023ca0b0dbd91325444c70c4d10 | [
"MIT"
] | 125 | 2021-10-01T19:05:26.000Z | 2021-10-03T13:32:42.000Z | C++/dnf_sort.cpp | ayushyado/HACKTOBERFEST2021-2 | b63d568fd7f33023ca0b0dbd91325444c70c4d10 | [
"MIT"
] | 201 | 2021-10-30T20:40:01.000Z | 2022-03-22T17:26:28.000Z | C++/dnf_sort.cpp | ayushyado/HACKTOBERFEST2021-2 | b63d568fd7f33023ca0b0dbd91325444c70c4d10 | [
"MIT"
] | 294 | 2021-10-01T18:46:05.000Z | 2021-10-03T14:25:07.000Z | #include <bits/stdc++.h>
using namespace std;
//this sorting algorithm is for sorting 0s,1s and 2s
//we have to traverse the whole array or vector
//so the time complexity becomes O(n)
void dnfsort(vector<int>&v){
int n = v.size();
//here we will be having three pointers
//forb iterating through the vector
int low =0;
int mid = 0;
int high = n-1;
while(mid<=high){
if(v[mid]==0){
swap(v[mid],v[low]);
low++;
mid++;
}
else if(v[mid]==1){
mid++;
}
else{
swap(v[mid],v[high]);
high--;
}
}
}
int main(){
cout<<"Enter the size of the vector :";
int n; cin>>n;
vector<int> v;
cout<<"\n";
cout<<"Enter the vector elemnts :"<<"\n";
while(n--){
int x; cin>>x;
v.push_back(x);
}
dnfsort(v);
cout<<"\n";
cout<<"Now the sorted vector is : "<<"\n";
for(int i : v ){
cout<<i<<" ";
}
return 0;
} | 19.788462 | 52 | 0.47619 | ayushyado |
b55f75814e6ddfa4e911f9b69ec6adf31340e725 | 7,949 | cpp | C++ | src/MD5/MD5.cpp | mykhailok01/RS5_Implementation | 4fd3e00ae74c4c8d143112e1a9bf01cb423b0cd1 | [
"MIT"
] | null | null | null | src/MD5/MD5.cpp | mykhailok01/RS5_Implementation | 4fd3e00ae74c4c8d143112e1a9bf01cb423b0cd1 | [
"MIT"
] | null | null | null | src/MD5/MD5.cpp | mykhailok01/RS5_Implementation | 4fd3e00ae74c4c8d143112e1a9bf01cb423b0cd1 | [
"MIT"
] | null | null | null | #include "MD5.hpp"
#include <climits>
#include <cassert>
#include <sstream>
#include <vector>
#include <iostream>
#include <limits>
#include <bitset>
using Chunk = std::array<std::uint32_t, 16>;// 512 bit
constexpr size_t CHUNK_SIZE = sizeof(Chunk::value_type) * 16;
constexpr auto BITS_CHUNK_SIZE = static_cast<std::uint64_t>(CHUNK_SIZE) * CHAR_BIT;
constexpr uint64_t BITS_SIZE_PART_SIZE = sizeof(uint64_t) * CHAR_BIT;
constexpr size_t BITS_CHUNK_PART_SIZE = sizeof(Chunk::value_type) * CHAR_BIT;
template <typename I>
std::string toString(I val, size_t hexLen = sizeof(I)<<1)
{
static const char* digits = "0123456789ABCDEF";
std::string result(hexLen,'0');
for (size_t i=0, j=(hexLen-1)*4 ; i<hexLen; ++i,j-=4)
result[i] = digits[(val>>j) & 0x0f];
return result;
}
template <typename I, uint64_t binLen = sizeof(I) * CHAR_BIT>
std::string toBinaryStr(I val)
{
return std::bitset<binLen>(val).to_string();
}
std::string toString(const Chunk &chunk)
{
std::string result;
for(size_t i = 0; i < chunk.size() - 1; ++i)
result += toString(chunk[i]) + " ";
result += toString(chunk.back());
return result;
}
std::uint32_t convert(const std::string &data, std::size_t begin)
{
assert(begin < data.size());
std::uint32_t value = 0;
size_t i = begin, end = begin + 4;
for (; i < end && i < data.size(); ++i)
{
value <<=CHAR_BIT;
value += static_cast<std::uint32_t>(data[i]);
}
return value << (end - i) * CHAR_BIT;
}
std::vector<Chunk> toChunks(const std::string& data)
{
std::vector<Chunk> result;
for(size_t chunckBeginning = 0; chunckBeginning < data.size(); chunckBeginning += 64)
{
Chunk chunk = {};
for (size_t index32Bit = 0, dataIndex = chunckBeginning;
index32Bit < chunk.size() && dataIndex < data.size();
index32Bit++)
{
chunk[index32Bit] = convert(data, dataIndex);
dataIndex += sizeof(chunk[index32Bit]);
}
result.push_back(chunk);
}
if (result.empty())
result.push_back(Chunk());
return result;
}
void alignSizeTo448Mod512(std::vector<Chunk> &chunks, std::uint64_t bitsDataSize)
{
if (bitsDataSize >= BITS_CHUNK_SIZE * chunks.size() - BITS_SIZE_PART_SIZE)
chunks.push_back(Chunk());
}
Chunk::value_type revertBytes(Chunk::value_type value)
{
auto selectByte = [] (Chunk::value_type val, size_t i)->Chunk::value_type
{
size_t firstBit = i * CHAR_BIT;
val = val << firstBit >> firstBit;
size_t bitsToEnd = BITS_CHUNK_PART_SIZE - firstBit - CHAR_BIT;
val = val >> bitsToEnd << bitsToEnd;
return val;
};
return selectByte(value, 0) >> (BITS_CHUNK_PART_SIZE - CHAR_BIT) |
selectByte(value, 1) >> CHAR_BIT |
selectByte(value, 2) << CHAR_BIT |
selectByte(value, 3) << (BITS_CHUNK_PART_SIZE - CHAR_BIT);
}
void insertLeadingBit(std::vector<Chunk> &chunks, std::uint64_t bitsDataSize)
{
auto lastDataChunkIndex = bitsDataSize / BITS_CHUNK_SIZE;
Chunk &lastDataChunk = chunks[lastDataChunkIndex];
auto bitsDataSizeRest = (bitsDataSize % BITS_CHUNK_SIZE);
auto &lastDataChunkPart = lastDataChunk[bitsDataSizeRest / BITS_CHUNK_PART_SIZE];
bitsDataSizeRest %= BITS_CHUNK_PART_SIZE;
lastDataChunkPart |= (1ul << (BITS_CHUNK_PART_SIZE - bitsDataSizeRest - 1));
}
void insertDataSize(std::vector<Chunk> &chunks, std::uint64_t bitsDataSize)
{
auto &lastChunk = chunks.back();
auto &lastChunkPart = lastChunk.back();
lastChunkPart = revertBytes(bitsDataSize >> BITS_CHUNK_PART_SIZE);
auto &penultimateChunkPart = lastChunk[lastChunk.size() - 2];
penultimateChunkPart = revertBytes(bitsDataSize << BITS_CHUNK_PART_SIZE >> BITS_CHUNK_PART_SIZE);
}
Chunk::value_type leftRotate(Chunk::value_type value, size_t amount)
{
assert(amount <= 31);
Chunk::value_type mask = (1u << amount) - 1;
Chunk::value_type left = value << amount;
Chunk::value_type right = value >> (BITS_CHUNK_PART_SIZE - amount);
return (left & ~mask) | (right & mask);
}
MD5Hash calculateMD5Hash(const std::vector<Chunk> &chunks)
{
constexpr std::array<std::size_t, 64> s = {
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
};
constexpr std::array<std::uint32_t, 64> K = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
};
MD5Hash hash = {
0x67452301,// A
0xefcdab89,// B
0x98badcfe,// C
0x10325476 // D
};
for (const auto& chunk : chunks)
{
MD5Hash tmpHash = hash;
for (size_t i = 0; i < K.size(); ++i)
{
MD5Hash::value_type F = 0;
size_t g = 0;
if (0 <= i && i <= 15)
{
F = (tmpHash[1] & tmpHash[2]) | (~tmpHash[1] & tmpHash[3]);
g = i;
}
else if (16 <= i && i <= 31)
{
F = (tmpHash[3] & tmpHash[1]) | (~tmpHash[3] & tmpHash[2]);
g = (5 * i + 1) % 16;
}
else if (32 <= i && i <= 47)
{
F = tmpHash[1] ^ tmpHash[2] ^ tmpHash[3];
g = (3 * i + 5) % 16;
}
else if (48 <= i && i <= 63)
{
F = tmpHash[2] ^ (tmpHash[1] | (~tmpHash[3]));
g = (7 * i) % 16;
}
F = (F + tmpHash[0] + K[i] + chunk[g]) & ~std::uint32_t(0);
tmpHash[0] = tmpHash[3];
tmpHash[3] = tmpHash[2];
tmpHash[2] = tmpHash[1];
tmpHash[1] = tmpHash[1] + leftRotate(F, s[i]);
}
for (size_t i = 0; i < hash.size(); ++i)
{
hash[i] += tmpHash[i];
}
}
for (auto& val : hash)
val = revertBytes(val);
return hash;
}
void revertBytesInEachChunk(std::vector<Chunk>& chunks)
{
for(auto &chunk: chunks)
for(auto & word: chunk)
word = revertBytes(word);
}
std::array<std::uint32_t, 4> generateMD5Hash(const std::string &data)
{
static_assert(CHAR_BIT == 8, "generateMD5Hash requires byte to be 8 bit long");
static_assert(sizeof(size_t) == 8 || sizeof(size_t) == 4, "generateMD5Hash requires size_t to be 8 or 4 bytes ");
std::uint64_t bitsDataSize = static_cast<std::uint64_t>(data.size()) * sizeof(std::string::value_type) * CHAR_BIT;
assert(bitsDataSize != std::numeric_limits<std::uint64_t>::max());
auto chunks = toChunks(data);
alignSizeTo448Mod512(chunks, bitsDataSize);
insertLeadingBit(chunks, bitsDataSize);
insertDataSize(chunks, bitsDataSize);
revertBytesInEachChunk(chunks);
return calculateMD5Hash(chunks);
}
std::string toString(const MD5Hash &hash)
{
std::string result;
for(size_t i = 0; i < hash.size(); ++i)
result += toString(hash[i]);
return result;
} | 34.71179 | 118 | 0.602592 | mykhailok01 |
b55fbdbfacd906739e63e2851b93ebfc455b8733 | 1,443 | cpp | C++ | cpp/opendnp3/src/opendnp3/objects/Group51.cpp | tarm/dnp3_orig | 87c639b3462c980fba255e85793f6ec663abe981 | [
"Apache-2.0"
] | null | null | null | cpp/opendnp3/src/opendnp3/objects/Group51.cpp | tarm/dnp3_orig | 87c639b3462c980fba255e85793f6ec663abe981 | [
"Apache-2.0"
] | null | null | null | cpp/opendnp3/src/opendnp3/objects/Group51.cpp | tarm/dnp3_orig | 87c639b3462c980fba255e85793f6ec663abe981 | [
"Apache-2.0"
] | 3 | 2016-07-13T18:54:13.000Z | 2021-04-12T13:30:39.000Z | //
// _ _ ______ _ _ _ _ _ _ _
// | \ | | | ____| | (_) | (_) | | | |
// | \| | ___ | |__ __| |_| |_ _ _ __ __ _| | | |
// | . ` |/ _ \ | __| / _` | | __| | '_ \ / _` | | | |
// | |\ | (_) | | |___| (_| | | |_| | | | | (_| |_|_|_|
// |_| \_|\___/ |______\__,_|_|\__|_|_| |_|\__, (_|_|_)
// __/ |
// |___/
// Copyright 2013 Automatak LLC
//
// Automatak LLC (www.automatak.com) licenses this file
// to you under the the Apache License Version 2.0 (the "License"):
//
// http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "Group51.h"
#include <openpal/Serialization.h>
using namespace openpal;
namespace opendnp3 {
const GroupVariationID Group51Var1::ID(51,1);
Group51Var1 Group51Var1::Read(ReadOnlyBuffer& buffer)
{
Group51Var1 obj;
obj.time = UInt48::Read(buffer);
buffer.Advance(6);
return obj;
}
void Group51Var1::Write(const Group51Var1& arg, openpal::WriteBuffer& buffer)
{
UInt48::Write(buffer, arg.time);
buffer.Advance(6);
}
const GroupVariationID Group51Var2::ID(51,2);
Group51Var2 Group51Var2::Read(ReadOnlyBuffer& buffer)
{
Group51Var2 obj;
obj.time = UInt48::Read(buffer);
buffer.Advance(6);
return obj;
}
void Group51Var2::Write(const Group51Var2& arg, openpal::WriteBuffer& buffer)
{
UInt48::Write(buffer, arg.time);
buffer.Advance(6);
}
}
| 24.05 | 77 | 0.559252 | tarm |
b5623319810028e4069c7445e0129611ab599b5a | 11,007 | hpp | C++ | src/core/utils/maybe.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | src/core/utils/maybe.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | src/core/utils/maybe.hpp | lowkey42/BanishedBlaze | 71e66f444a84bea1eca3639de3f3ff1f79e385d1 | [
"MIT"
] | null | null | null | /** simple wrapper for optional values or references *************************
* *
* Copyright (c) 2014 Florian Oetke *
* This file is distributed under the MIT License *
* See LICENSE file for details. *
\*****************************************************************************/
#pragma once
#include "log.hpp"
#include "func_traits.hpp"
#include <stdexcept>
#include <functional>
#include <memory>
#include <type_traits>
namespace lux {
namespace util {
namespace details {
struct maybe_else_callable {
bool is_nothing;
template<typename Func>
void on_nothing(Func f) {
if(is_nothing)
f();
}
};
}
template<typename T>
class maybe {
public:
maybe()noexcept : _valid(false) {}
/*implicit*/ maybe(T&& data)noexcept : _valid(true), _data(std::move(data)) {}
/*implicit*/ maybe(const T& data)noexcept : _valid(true), _data(data) {}
maybe(const maybe& o)noexcept : _valid(o._valid), _data(o._data) {}
maybe(maybe&& o)noexcept : _valid(o._valid), _data(std::move(o._data)) {
o._valid = false;
}
~maybe()noexcept {
if(is_some())
_data.~T();
}
operator maybe<const T>()const noexcept {
return is_some() ? maybe<const T>(_data) : maybe<const T>::nothing();
}
bool operator!()const noexcept {
return is_nothing();
}
maybe& operator=(const maybe& o)noexcept {
_valid = o._valid;
_data = o._data;
return *this;
}
maybe& operator=(maybe&& o)noexcept {
if(o._valid) {
if(_valid)
_data = std::move(o._data);
else
new(&_data) T(std::move(o._data));
o._data.~T();
}
_valid = o._valid;
o._valid = false;
return *this;
}
static maybe nothing() noexcept {
return maybe();
}
bool is_some()const noexcept {
return _valid;
}
bool is_nothing()const noexcept {
return !is_some();
}
T& get_or_throw() {
INVARIANT(is_some(), "Called getOrThrow on nothing.");
return _data;
}
const T& get_or_throw()const {
INVARIANT(is_some(), "Called getOrThrow on nothing.");
return _data;
}
T& get_ref_or_other(T& other)noexcept {
return is_some() ? _data : other;
}
const T& get_ref_or_other(const T& other)const noexcept {
return is_some() ? _data : other;
}
T get_or_other(T other)const noexcept {
return is_some() ? _data : other;
}
template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>>
void process(Func&& f)const {
if(is_some())
f(_data);
}
template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>>
auto process(Func&& f)const -> maybe<std::result_of_t<Func(const T&)>> {
if(is_some())
return f(_data);
else
return nothing();
}
template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>>
void process(Func&& f) {
if(is_some())
f(_data);
}
template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>>
auto process(Func&& f) -> maybe<std::result_of_t<Func(T&)>> {
if(is_some())
return f(_data);
else
return nothing();
}
template<typename RT, typename Func>
auto process(RT def, Func&& f) -> RT {
if(is_some())
return f(_data);
return def;
}
template<typename RT, typename Func>
auto process(RT def, Func&& f)const -> RT {
if(is_some())
return f(_data);
return def;
}
private:
bool _valid;
union {
T _data;
};
};
// TODO: change to nothing_t
struct nothing {
template<typename T>
operator maybe<T>()const noexcept {
return maybe<T>::nothing();
}
};
template<typename T>
maybe<std::remove_reference_t<T>> just(T&& inst) {
return maybe<std::remove_reference_t<T>>(std::forward<T>(inst));
}
template<typename T>
maybe<T> justCopy(const T& inst) {
return maybe<T>(inst);
}
template<typename T>
maybe<T&> justPtr(T* inst) {
return inst!=nullptr ? maybe<T&>(*inst) : nothing();
}
template<typename T, typename Func>
auto operator>>(const maybe<T>& t, Func f)
-> std::enable_if_t<!std::is_same<void,decltype(f(t.get_or_throw()))>::value,
maybe<decltype(f(t.get_or_throw()))>> {
return t.is_some() ? just(f(t.get_or_throw())) : nothing();
}
template<typename T, typename Func>
auto operator>>(const maybe<T>& t, Func f)
-> std::enable_if_t<std::is_same<void,decltype(f(t.get_or_throw()))>::value,
void> {
if(t.is_some())
f(t.get_or_throw());
}
template<typename T>
bool operator! (const maybe<T>& m) {
return !m.is_some();
}
template<typename T>
class maybe<T&> {
public:
maybe() : _ref(nullptr) {}
/*implicit*/ maybe(T& data)noexcept : _ref(&data) {}
template<typename U, class = std::enable_if_t<std::is_convertible<U*, T*>::value> >
maybe(U& o)noexcept : _ref(&o) {}
maybe(const maybe& o)noexcept : _ref(o._ref) {}
maybe(maybe&& o)noexcept : _ref(o._ref) {
o._ref = nullptr;
}
template<typename U, class = std::enable_if_t<std::is_convertible<U*, T*>::value> >
maybe(const maybe<U>& o)noexcept : _ref(o._ref) {}
~maybe()noexcept = default;
operator maybe<const T&>()const noexcept {
return is_some() ? maybe<const T&>(*_ref) : maybe<const T&>::nothing();
}
bool operator!()const noexcept {
return is_nothing();
}
maybe& operator=(const maybe& o)noexcept {
_ref = o._ref;
return *this;
}
maybe& operator=(maybe&& o)noexcept {
std::swap(_ref=nullptr, o._ref);
return *this;
}
static maybe nothing() noexcept {
return maybe();
}
bool is_some()const noexcept {
return _ref!=nullptr;
}
bool is_nothing()const noexcept {
return !is_some();
}
T& get_or_throw()const {
INVARIANT(is_some(), "Called getOrThrow on nothing.");
return *_ref;
}
T& get_or_other(std::remove_const_t<T>& other)const noexcept {
return is_some() ? *_ref : other;
}
const T& get_or_other(const T& other)const noexcept {
return is_some() ? *_ref : other;
}
template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>>
void process(Func&& f)const {
if(is_some())
f(*_ref);
}
template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>>
auto process(Func&& f)const -> maybe<std::result_of_t<Func(const T&)>> {
if(is_some())
return f(*_ref);
else
return nothing();
}
template<typename Func, class=std::enable_if_t<std::is_same<std::result_of_t<Func(T&)>, void>::value>>
void process(Func&& f) {
if(is_some())
f(*_ref);
}
template<typename Func, class=std::enable_if_t<not std::is_same<std::result_of_t<Func(T&)>, void>::value>>
auto process(Func&& f) -> maybe<std::result_of_t<Func(T&)>> {
if(is_some())
return f(*_ref);
else
return nothing();
}
template<typename RT, typename Func>
auto process(RT def, Func&& f) -> RT {
if(is_some())
return f(get_or_throw());
return def;
}
template<typename RT, typename Func>
auto process(RT def, Func&& f)const -> RT {
if(is_some())
return f(get_or_throw());
return def;
}
private:
T* _ref;
};
namespace details {
template<int ...>
struct seq { };
template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> { };
template<int ...S>
struct gens<0, S...> {
typedef seq<S...> type;
};
template<typename... T>
struct processor {
std::tuple<T&&...> args;
template<typename Func>
void operator>>(Func&& f) {
call(std::forward<Func>(f), typename gens<sizeof...(T)>::type());
}
private:
template<typename Func, int ...S>
void call(Func&& f, seq<S...>) {
call(std::forward<Func>(f), std::forward<decltype(std::get<S>(args))>(std::get<S>(args))...);
}
template<typename Func, typename... Args>
void call(Func&& f, Args&&... m) {
for(bool b : {m.is_some()...})
if(!b)
return;
f(m.get_or_throw()...);
}
};
}
/*
* Usage:
* maybe<bool> b = true;
* maybe<int> i = nothing();
* maybe<float> f = 1.0f;
*
* process(b,i,f)>> [](bool b, int i, float& f){
* // ...
* };
*/
template<typename... T>
auto process(T&&... m) -> details::processor<T...> {
return details::processor<T...>{std::tuple<decltype(m)...>(std::forward<T>(m)...)};
}
template<class Map, class Key>
auto find_maybe(Map& map, const Key& key) -> auto {
auto iter = map.find(key);
return iter!=map.end() ? justPtr(&iter->second) : nothing();
}
template<typename T>
class lazy {
public:
using source_t = std::function<T()>;
/*implicit*/ lazy(source_t s) : _source(s){}
operator T(){
return _source;
}
private:
source_t _source;
};
template<typename T>
inline lazy<T> later(typename lazy<T>::source_t f) {
return lazy<T>(f);
}
template <class F>
struct return_type;
template <class R, class T, class... A>
struct return_type<R (T::*)(A...)>
{
typedef R type;
};
template <class R, class... A>
struct return_type<R (*)(A...)>
{
typedef R type;
};
template<typename S, typename T>
inline lazy<T> later(S* s, T (S::*f)()) {
std::weak_ptr<S> weak_s = s->shared_from_this();
return lazy<T>([weak_s, f](){
auto shared_s = weak_s.lock();
if(shared_s) {
auto s = shared_s.get();
return (s->*f)();
} else {
return T{};
}
});
}
}
}
#ifdef LUX_DEFINE_MAYBE_MACROS
#define LUX_NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N,...) N
#define LUX_NARGS(...) LUX_NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
/* This will let macros expand before concating them */
#define LUX_PRIMITIVE_CAT(x, y) x ## y
#define LUX_CAT(x, y) LUX_PRIMITIVE_CAT(x, y)
#define LUX_APPLY(macro, ...) LUX_CAT(LUX_APPLY_, LUX_NARGS(__VA_ARGS__))(macro, __VA_ARGS__)
#define LUX_APPLY_1(m, x1) m(x1)
#define LUX_APPLY_2(m, x, ...) m(x), LUX_APPLY_1(m,__VA_ARGS__)
#define LUX_APPLY_3(m, x, ...) m(x), LUX_APPLY_2(m,__VA_ARGS__)
#define LUX_APPLY_4(m, x, ...) m(x), LUX_APPLY_3(m,__VA_ARGS__)
#define LUX_APPLY_5(m, x, ...) m(x), LUX_APPLY_4(m,__VA_ARGS__)
#define LUX_APPLY_6(m, x, ...) m(x), LUX_APPLY_5(m,__VA_ARGS__)
#define LUX_APPLY_7(m, x, ...) m(x), LUX_APPLY_6(m,__VA_ARGS__)
#define LUX_APPLY_8(m, x, ...) m(x), LUX_APPLY_7(m,__VA_ARGS__)
#define LUX_APPLY_9(m, x, ...) m(x), LUX_APPLY_8(m,__VA_ARGS__)
#define LUX_APPLY_10(m, x, ...) m(x), LUX_APPLY_9(m,__VA_ARGS__)
#define LUX_PROCESS_MAYBE_ARG_EXP(name) decltype(name.get_or_throw()) name
#define LUX_PROCESS_MAYBE(...) ::lux::util::process(__VA_ARGS__) >> [&](LUX_APPLY(LUX_PROCESS_MAYBE_ARG_EXP, __VA_ARGS__))
#endif
| 25.187643 | 123 | 0.600073 | lowkey42 |
b5630a7c5a980b93057022c640b102796a94a44f | 8,802 | cpp | C++ | src/mesh/store/nodestore.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | 1 | 2021-09-16T10:15:50.000Z | 2021-09-16T10:15:50.000Z | src/mesh/store/nodestore.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | null | null | null | src/mesh/store/nodestore.cpp | It4innovations/mesio | de966f2a13e1e301be818485815d43ceff1e7094 | [
"BSD-3-Clause"
] | null | null | null |
#include "store.h"
#include "nodestore.h"
#include "statisticsstore.h"
#include "mesh/mesh.h"
#include "esinfo/mpiinfo.h"
#include "esinfo/meshinfo.h"
#include "basis/containers/point.h"
#include "basis/containers/serializededata.h"
#include "basis/utilities/packing.h"
using namespace mesio;
NodeStore::NodeStore()
: size(0),
distribution({0, 0}),
IDs(NULL),
elements(NULL),
originCoordinates(NULL),
coordinates(NULL),
ranks(NULL),
domains(NULL)
{
}
size_t NodeStore::packedFullSize() const
{
size_t packedSize = 0;
packedSize += utils::packedSize(size);
packedSize += utils::packedSize(uniqInfo.nhalo);
packedSize += utils::packedSize(uniqInfo.offset);
packedSize += utils::packedSize(uniqInfo.size);
packedSize += utils::packedSize(uniqInfo.totalSize);
packedSize += utils::packedSize(uniqInfo.position);
packedSize += utils::packedSize(distribution);
packedSize += utils::packedSize(IDs);
packedSize += utils::packedSize(elements);
packedSize += utils::packedSize(originCoordinates);
packedSize += utils::packedSize(coordinates);
packedSize += utils::packedSize(ranks);
packedSize += utils::packedSize(domains);
packedSize += utils::packedSize(data.size());
for (size_t i = 0; i < data.size(); i++) {
packedSize += data[i]->packedSize();
}
return packedSize;
}
void NodeStore::packFull(char* &p) const
{
utils::pack(size, p);
utils::pack(uniqInfo.nhalo, p);
utils::pack(uniqInfo.offset, p);
utils::pack(uniqInfo.size, p);
utils::pack(uniqInfo.totalSize, p);
utils::pack(uniqInfo.position, p);
utils::pack(distribution, p);
utils::pack(IDs, p);
utils::pack(elements, p);
utils::pack(originCoordinates, p);
utils::pack(coordinates, p);
utils::pack(ranks, p);
utils::pack(domains, p);
utils::pack(data.size(), p);
for (size_t i = 0; i < data.size(); i++) {
data[i]->pack(p);
}
}
void NodeStore::unpackFull(const char* &p)
{
utils::unpack(size, p);
utils::unpack(uniqInfo.nhalo, p);
utils::unpack(uniqInfo.offset, p);
utils::unpack(uniqInfo.size, p);
utils::unpack(uniqInfo.totalSize, p);
utils::unpack(uniqInfo.position, p);
utils::unpack(distribution, p);
utils::unpack(IDs, p);
utils::unpack(elements, p);
utils::unpack(originCoordinates, p);
utils::unpack(coordinates, p);
utils::unpack(ranks, p);
utils::unpack(domains, p);
size_t size;
utils::unpack(size, p);
for (size_t i = 0; i < size; i++) {
data.push_back(new NodeData(p));
}
}
size_t NodeStore::packedSize() const
{
return
utils::packedSize(size) +
utils::packedSize(uniqInfo.nhalo) +
utils::packedSize(uniqInfo.offset) +
utils::packedSize(uniqInfo.size) +
utils::packedSize(uniqInfo.totalSize) +
utils::packedSize(uniqInfo.position) +
IDs->packedSize() +
coordinates->packedSize();
}
void NodeStore::pack(char* &p) const
{
utils::pack(size, p);
utils::pack(uniqInfo.nhalo, p);
utils::pack(uniqInfo.offset, p);
utils::pack(uniqInfo.size, p);
utils::pack(uniqInfo.totalSize, p);
utils::pack(uniqInfo.position, p);
IDs->pack(p);
coordinates->pack(p);
}
void NodeStore::unpack(const char* &p)
{
if (IDs == NULL) {
IDs = new serializededata<esint, esint>(1, tarray<esint>(1, 0));
}
if (coordinates == NULL) {
coordinates = new serializededata<esint, Point>(1, tarray<Point>(1, 0));
}
utils::unpack(size, p);
utils::unpack(uniqInfo.nhalo, p);
utils::unpack(uniqInfo.offset, p);
utils::unpack(uniqInfo.size, p);
utils::unpack(uniqInfo.totalSize, p);
utils::unpack(uniqInfo.position, p);
IDs->unpack(p);
coordinates->unpack(p);
}
size_t NodeStore::packedDataHeaderSize() const
{
size_t size = sizeof(size_t);
for (size_t i = 0; i < data.size(); i++) {
if (data[i]->name.size()) {
size += utils::packedSize(data[i]->dimension);
size += utils::packedSize(data[i]->dataType);
size += utils::packedSize(data[i]->name);
}
}
return size;
}
void NodeStore::packDataHeader(char* &p) const
{
size_t size = 0;
for (size_t i = 0; i < data.size(); i++) {
if (data[i]->name.size()) {
size += 1;
}
}
utils::pack(size, p);
for (size_t i = 0; i < data.size(); i++) {
if (data[i]->name.size()) {
utils::pack(data[i]->dimension, p);
utils::pack(data[i]->dataType, p);
utils::pack(data[i]->name, p);
}
}
}
void NodeStore::unpackDataHeader(const char* &p)
{
size_t size;
utils::unpack(size, p);
for (size_t i = 0; i < size; i++) {
data.push_back(new NodeData(0, NamedData::DataType::VECTOR, {}));
utils::unpack(data[i]->dimension, p);
utils::unpack(data[i]->dataType, p);
utils::unpack(data[i]->name, p);
}
}
size_t NodeStore::packedDataSize() const
{
size_t size = 0;
for (size_t i = 0; i < data.size(); i++) {
if (data[i]->name.size()) {
size += utils::packedSize(data[i]->data);
}
}
return size;
}
void NodeStore::packData(char* &p) const
{
for (size_t i = 0; i < data.size(); i++) {
if (data[i]->name.size()) {
utils::pack(data[i]->data, p);
}
}
}
void NodeStore::unpackData(const char* &p)
{
for (size_t i = 0; i < data.size(); i++) {
utils::unpack(data[i]->data, p);
}
}
NodeStore::~NodeStore()
{
if (IDs != NULL) { delete IDs; }
if (elements != NULL) { delete elements; }
if (originCoordinates != NULL) { delete originCoordinates; }
if (coordinates != NULL) { delete coordinates; }
if (ranks != NULL) { delete ranks; }
if (domains != NULL) { delete domains; }
for (size_t i = 0; i < data.size(); i++) {
delete data[i];
}
}
void NodeStore::store(const std::string &file)
{
std::ofstream os(file + std::to_string(info::mpi::rank) + ".txt");
Store::storedata(os, "IDs", IDs);
Store::storedata(os, "elements", elements);
Store::storedata(os, "coordinates", coordinates);
Store::storedata(os, "ranks", ranks);
Store::storedata(os, "domains", domains);
}
void NodeStore::permute(const std::vector<esint> &permutation, const std::vector<size_t> &distribution)
{
this->distribution = distribution;
if (IDs != NULL) { IDs->permute(permutation, distribution); }
if (elements != NULL) { elements->permute(permutation, distribution); }
if (originCoordinates != NULL) { originCoordinates->permute(permutation, distribution); }
if (coordinates != NULL) { coordinates->permute(permutation, distribution); }
if (ranks != NULL) { ranks->permute(permutation, distribution); }
if (domains != NULL) { domains->permute(permutation, distribution); }
}
std::vector<esint> NodeStore::gatherNodeDistribution()
{
return Store::gatherDistribution(size);
}
std::vector<esint> NodeStore::gatherUniqueNodeDistribution()
{
return Store::gatherDistribution(uniqInfo.size);
}
NodeData* NodeStore::appendData(int dimension, NamedData::DataType datatype, const std::string &name)
{
data.push_back(new NodeData(dimension, datatype, name));
data.back()->data.resize(dimension * size);
return data.back();
}
void NodeData::statistics(const tarray<esint> &nodes, esint totalsize, Statistics *statistics) const
{
for (int d = 0; d < nstatistics(); d++) {
(statistics + d)->reset();
}
auto nranks = info::mesh->nodes->ranks->begin();
esint prev = 0;
esint doffset = nstatistics() != dimension ? 1 : 0;
for (auto n = nodes.begin(); n != nodes.end(); prev = *n++) {
nranks += *n - prev;
if (*nranks->begin() == info::mpi::rank) {
double value = 0;
for (int d = 0; d < dimension; d++) {
value += store[*n * dimension + d] * store[*n * dimension + d];
(statistics + d + doffset)->min = std::min((statistics + d + doffset)->min, store[*n * dimension + d]);
(statistics + d + doffset)->max = std::max((statistics + d + doffset)->max, store[*n * dimension + d]);
(statistics + d + doffset)->avg += store[*n * dimension + d];
(statistics + d + doffset)->norm += store[*n * dimension + d] * store[*n * dimension + d];
(statistics + d + doffset)->absmin = std::min((statistics + d + doffset)->absmin, std::fabs(store[*n * dimension + d]));
(statistics + d + doffset)->absmax = std::max((statistics + d + doffset)->absmax, std::fabs(store[*n * dimension + d]));
}
if (dataType == DataType::VECTOR) {
value = std::sqrt(value);
statistics->min = std::min(statistics->min, value);
statistics->max = std::max(statistics->max, value);
statistics->avg += value;
statistics->norm += value * value;
statistics->absmin = std::min(statistics->absmin, std::fabs(value));
statistics->absmax = std::max(statistics->absmax, std::fabs(value));
}
}
}
std::vector<Statistics> global(nstatistics());
Communication::allReduce(statistics, global.data(), nstatistics(), MPITools::operations->STATISTICS, MPITools::operations->mergeStatistics);
memcpy(statistics, global.data(), sizeof(Statistics) * nstatistics());
for (int i = 0; i < nstatistics(); i++) {
(statistics + i)->avg /= totalsize;
(statistics + i)->norm = std::sqrt((statistics + i)->norm);
}
}
| 27.592476 | 141 | 0.658828 | It4innovations |
b56965082b5113142dd9d4e0dc2e936303a05c20 | 2,054 | hpp | C++ | falcon/utility/temporary_set.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | 2 | 2018-02-02T14:19:59.000Z | 2018-05-13T02:48:24.000Z | falcon/utility/temporary_set.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | falcon/utility/temporary_set.hpp | jonathanpoelen/falcon | 5b60a39787eedf15b801d83384193a05efd41a89 | [
"MIT"
] | null | null | null | #ifndef FALCON_UTILITYTEMPORARY_SET_HPP
#define FALCON_UTILITYTEMPORARY_SET_HPP
#include <falcon/utility/move.hpp>
#include <falcon/c++/noexcept.hpp>
#include <falcon/c++/reference.hpp>
#include <falcon/functional/operators.hpp>
#if __cplusplus >= 201103L
# include <type_traits>
#endif
namespace falcon {
///\brief Modifies the value passed during the lifetime of the object
template<class T, class Assigner = assign<T, T> >
class temporary_set
{
T * value_;
T old_value_;
Assigner assign_;
public:
typedef T type;
public:
template<class U>
temporary_set(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_)
: value_(&oldvalue_)
, old_value_(FALCON_MOVE(oldvalue_))
{
assign_(*value_, FALCON_FORWARD(U, newvalue_));
}
template<class U>
temporary_set(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_, Assigner fun)
: value_(&oldvalue_)
, old_value_(FALCON_MOVE(oldvalue_))
, assign_(fun)
{
assign_(*value_, FALCON_FORWARD(U, newvalue_));
}
#if __cplusplus >= 201103L
temporary_set(temporary_set &&) = default;
temporary_set(temporary_set const &) = delete;
temporary_set& operator=(temporary_set &&) = default;
temporary_set& operator=(temporary_set const &) = delete;
#endif
~temporary_set()
{
assign_(*value_, FALCON_MOVE(old_value_));
}
const T& old() const CPP_NOEXCEPT
{ return old_value_; }
void old(const T & new_old)
{ old_value_ = new_old; }
#if __cplusplus >= 201103L
void old(T && new_old)
{ old_value_ = std::move(new_old); }
#endif
};
///\brief make a temporary_set
template<class T, class U>
temporary_set<T>
temporary_value(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_)
{ return temporary_set<T>(oldvalue_, FALCON_FORWARD(U, newvalue_)); }
template<class T, class U, class Assigner>
temporary_set<T, Assigner>
temporary_value(T& oldvalue_, U CPP_RVALUE_OR_CONST_REFERENCE newvalue_, Assigner CPP_RVALUE fun)
{ return temporary_set<T, Assigner>(oldvalue_
, FALCON_FORWARD(U, newvalue_), FALCON_FORWARD(Assigner, fun)); }
}
#endif
| 25.04878 | 97 | 0.74148 | jonathanpoelen |
b56a3466b5195036e43924f472b337d6a6b914a6 | 4,071 | hpp | C++ | qubus/include/qubus/pattern/binary_operator.hpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/include/qubus/pattern/binary_operator.hpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | qubus/include/qubus/pattern/binary_operator.hpp | qubusproject/Qubus | 0feb8d6df00459c5af402545dbe7c82ee3ec4b7c | [
"BSL-1.0"
] | null | null | null | #ifndef QUBUS_PATTERN_BINARY_OPERATOR_HPP
#define QUBUS_PATTERN_BINARY_OPERATOR_HPP
#include <qubus/IR/binary_operator_expr.hpp>
#include <qubus/pattern/variable.hpp>
#include <qubus/pattern/any.hpp>
#include <qubus/pattern/value.hpp>
#include <utility>
#include <functional>
namespace qubus
{
namespace pattern
{
template <typename Tag, typename LHS, typename RHS>
class binary_operator_pattern
{
public:
binary_operator_pattern(Tag tag_, LHS lhs_, RHS rhs_)
:tag_(std::move(tag_)), lhs_(std::move(lhs_)), rhs_(std::move(rhs_))
{
}
template <typename BaseType>
bool match(const BaseType& value, const variable<const binary_operator_expr&>* var = nullptr) const
{
if (auto concret_value = value.template try_as<binary_operator_expr>())
{
if (tag_.match(concret_value->tag()))
{
if (lhs_.match(concret_value->left()) && rhs_.match(concret_value->right()))
{
if (var)
{
var->set(*concret_value);
}
return true;
}
}
}
return false;
}
void reset() const
{
tag_.reset();
lhs_.reset();
rhs_.reset();
}
private:
Tag tag_;
LHS lhs_;
RHS rhs_;
};
template <typename Tag, typename LHS, typename RHS>
binary_operator_pattern<Tag, LHS, RHS> binary_operator(Tag tag, LHS lhs, RHS rhs)
{
return binary_operator_pattern<Tag, LHS, RHS>(tag, lhs, rhs);
}
template <typename LHS, typename RHS>
binary_operator_pattern<any, LHS, RHS> binary_operator(LHS lhs, RHS rhs)
{
return binary_operator_pattern<any, LHS, RHS>(_, lhs, rhs);
}
template<typename LHS, typename RHS>
auto operator+(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::plus), lhs, rhs);
}
template<typename LHS, typename RHS>
auto operator-(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::minus), lhs, rhs);
}
template<typename LHS, typename RHS>
auto operator*(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::multiplies), lhs, rhs);
}
template<typename LHS, typename RHS>
auto operator/(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::divides), lhs, rhs);
}
template<typename LHS, typename RHS>
auto operator%(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::modulus), lhs, rhs);
}
template<typename LHS, typename RHS>
auto div_floor(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::div_floor), lhs, rhs);
}
template<typename LHS, typename RHS>
auto assign(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::assign), lhs, rhs);
}
template<typename LHS, typename RHS>
auto plus_assign(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::plus_assign), lhs, rhs);
}
template<typename LHS, typename RHS>
auto equal_to(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::equal_to), lhs, rhs);
}
template<typename LHS, typename RHS>
auto not_equal_to(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::not_equal_to), lhs, rhs);
}
template<typename LHS, typename RHS>
auto less(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::less), lhs, rhs);
}
template<typename LHS, typename RHS>
auto greater(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::greater), lhs, rhs);
}
template<typename LHS, typename RHS>
auto less_equal(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::less_equal), lhs, rhs);
}
template<typename LHS, typename RHS>
auto greater_equal(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::greater_equal), lhs, rhs);
}
template<typename LHS, typename RHS>
auto logical_and(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::logical_and), lhs, rhs);
}
template<typename LHS, typename RHS>
auto logical_or(LHS lhs, RHS rhs)
{
return binary_operator(value(binary_op_tag::logical_or), lhs, rhs);
}
}
}
#endif | 23.807018 | 103 | 0.688529 | qubusproject |
b56d896e4139c6fd4fa5337d66ec4dd83567bef5 | 3,142 | hpp | C++ | include/cppgit2/fetch.hpp | jhasse/cppgit2 | 7c069680bcfa70686053bc1f573524813c1f206f | [
"MIT"
] | 84 | 2020-03-22T14:03:37.000Z | 2022-01-04T05:51:55.000Z | include/cppgit2/fetch.hpp | jhasse/cppgit2 | 7c069680bcfa70686053bc1f573524813c1f206f | [
"MIT"
] | 7 | 2020-03-27T21:36:13.000Z | 2020-12-05T23:41:25.000Z | include/cppgit2/fetch.hpp | jhasse/cppgit2 | 7c069680bcfa70686053bc1f573524813c1f206f | [
"MIT"
] | 18 | 2020-04-25T09:55:17.000Z | 2022-03-06T23:20:43.000Z | #pragma once
#include <cppgit2/libgit2_api.hpp>
#include <cppgit2/proxy.hpp>
#include <cppgit2/strarray.hpp>
#include <git2.h>
#include <string>
#include <vector>
namespace cppgit2 {
class fetch : public libgit2_api {
public:
class options : public libgit2_api {
public:
options() : c_ptr_(nullptr) {
auto ret =
git_fetch_init_options(&default_options_, GIT_FETCH_OPTIONS_VERSION);
c_ptr_ = &default_options_;
if (ret != 0)
throw git_exception();
}
options(git_fetch_options *c_ptr) : c_ptr_(c_ptr) {}
// Version
unsigned int version() const { return c_ptr_->version; }
void set_version(unsigned int version) { c_ptr_->version = version; }
// TODO: Add callbacks to use for this fetch operation
// Acceptable prune settings when fetching
enum class prune {
// Use the setting from the configuration
unspecified,
// Force pruning on
prune,
// Force pruning off
no_prune
};
// Prune - Whether to perform a prune after the fetch
prune prune_option() const {
return static_cast<fetch::options::prune>(c_ptr_->prune);
}
void set_prune_option(prune option) {
c_ptr_->prune = static_cast<git_fetch_prune_t>(option);
}
// Update fetchhead
// Whether to write the results to FETCH_HEAD. Defaults to on. Leave this
// default in order to behave like git.
bool update_fetchhead() const { return c_ptr_->update_fetchhead; }
void set_update_fetchhead(bool value) { c_ptr_->update_fetchhead = value; }
// Automatic tag following option
// Lets us select the --tags option to use.
enum class autotag {
// Use the setting from the configuration
unspecified = 0,
// Ask the server for tags pointing to objects we're already downloading.
auto_,
// Don't ask for any tags beyond the refspecs.
none,
// Ask for the all the tags.
all
};
// Download tags
// Determines how to behave regarding tags on the remote, such as
// auto-downloading tags for objects we're downloading or downloading all of
// them. The default is to auto-follow tags.
autotag download_tags_option() const {
return static_cast<autotag>(c_ptr_->download_tags);
}
void set_download_tags_option(autotag download_tags) {
c_ptr_->download_tags =
static_cast<git_remote_autotag_option_t>(download_tags);
}
// Proxy options
proxy::options proxy_options() const {
return proxy::options(&c_ptr_->proxy_opts);
}
void set_proxy_options(const proxy::options &options) {
c_ptr_->proxy_opts = *(options.c_ptr());
}
// Custom headers
strarray custom_headers() const {
return strarray(&c_ptr_->custom_headers);
}
void set_custom_headers(const std::vector<std::string> &headers) {
c_ptr_->custom_headers = *(strarray(headers).c_ptr());
}
// Access libgit2 C ptr
const git_fetch_options *c_ptr() const { return c_ptr_; }
private:
git_fetch_options *c_ptr_;
git_fetch_options default_options_;
};
};
} // namespace cppgit2 | 29.364486 | 80 | 0.669955 | jhasse |
b56f1995d8b993312a57a37084c760cfcd038b1c | 740 | cpp | C++ | src/SpectatorView.Native/SpectatorView.WinRTExtensions/SpectatorView.WinRTExtensions.cpp | sereilly/MixedReality-SpectatorView | a4f58e25bbe6c002cbf7b134c4babe5e4d7bc9b9 | [
"MIT"
] | 165 | 2019-06-19T18:41:20.000Z | 2022-03-16T12:17:02.000Z | src/SpectatorView.Native/SpectatorView.WinRTExtensions/SpectatorView.WinRTExtensions.cpp | sereilly/MixedReality-SpectatorView | a4f58e25bbe6c002cbf7b134c4babe5e4d7bc9b9 | [
"MIT"
] | 297 | 2019-06-18T19:01:43.000Z | 2022-03-31T00:11:07.000Z | src/SpectatorView.Native/SpectatorView.WinRTExtensions/SpectatorView.WinRTExtensions.cpp | sereilly/MixedReality-SpectatorView | a4f58e25bbe6c002cbf7b134c4babe5e4d7bc9b9 | [
"MIT"
] | 108 | 2019-06-17T22:44:08.000Z | 2022-03-18T05:44:57.000Z | #include "pch.h"
#include "SpectatorView.WinRTExtensions.h"
// Because Marshal.GetObjectForIUnknown does not work when using the .NET Native compiler with IInspectable
// objects, this method allows managed code to explicitly specify a type for the marshaller to query for.
// Example usage from managed code for marshalling a SpatialCoordinateSystem using this method:
//
// [DllImport("SpectatorView.WinRTExtensions.dll", EntryPoint = "MarshalIInspectable")]
// private static extern void GetSpatialCoordinateSystem(IntPtr nativePtr, out SpatialCoordinateSystem coordinateSystem);
extern "C" __declspec(dllexport) void __stdcall MarshalIInspectable(IUnknown* nativePtr, IUnknown** inspectable)
{
*inspectable = nativePtr;
} | 52.857143 | 125 | 0.797297 | sereilly |
b5704f6293dea12047ce0271d638fae94aac3a22 | 4,707 | cc | C++ | solver_bank.cc | frenebo/SOAX | c6aacd1ce9d919a205a712a4db8f0ab8a1ecacd1 | [
"BSD-3-Clause"
] | 8 | 2015-09-14T00:37:59.000Z | 2020-12-30T22:47:34.000Z | solver_bank.cc | frenebo/SOAX | c6aacd1ce9d919a205a712a4db8f0ab8a1ecacd1 | [
"BSD-3-Clause"
] | 3 | 2015-05-14T15:48:50.000Z | 2020-12-30T17:46:14.000Z | solver_bank.cc | frenebo/SOAX | c6aacd1ce9d919a205a712a4db8f0ab8a1ecacd1 | [
"BSD-3-Clause"
] | 9 | 2015-09-14T11:35:51.000Z | 2021-12-14T23:38:47.000Z | /**
* Copyright (c) 2015, Lehigh University
* All rights reserved.
* See COPYING for license.
*
* This file implements the solvers for linear system for SOAX.
*/
#include "./solver_bank.h"
namespace soax {
SolverBank::SolverBank() : alpha_(0.01), beta_(0.1), gamma_(2.0) {}
SolverBank::~SolverBank() {
this->ClearSolvers(open_solvers_);
this->ClearSolvers(closed_solvers_);
}
void SolverBank::ClearSolvers(SolverContainer &solvers) {
if (solvers.empty()) return;
for (SolverContainer::iterator it = solvers.begin();
it != solvers.end(); ++it) {
if (*it) {
(*it)->DestroyMatrix(0);
(*it)->DestroyVector(0);
(*it)->DestroySolution(0);
delete *it;
}
}
solvers.clear();
}
void SolverBank::Reset(bool reset_matrix) {
if (reset_matrix) {
this->ClearSolvers(open_solvers_);
this->ClearSolvers(closed_solvers_);
} else {
this->ResetSolutionAndVector(open_solvers_);
this->ResetSolutionAndVector(closed_solvers_);
}
}
void SolverBank::ResetSolutionAndVector(SolverContainer &solvers) {
if (solvers.empty()) return;
for (SolverContainer::iterator it = solvers.begin();
it != solvers.end(); ++it) {
if (*it) {
(*it)->InitializeSolution(0);
(*it)->InitializeVector(0);
}
}
}
void SolverBank::SolveSystem(const VectorContainer &vectors, unsigned dim,
bool open) {
SolverContainer &solvers = open ? open_solvers_ : closed_solvers_;
unsigned position = vectors.size() - kMinimumEvolvingSize;
if (position >= solvers.size()) {
this->ExpandSolverContainer(solvers, position);
}
if (!solvers[position]) {
solvers[position] = new SolverType;
this->InitializeSolver(solvers[position], vectors.size(), open);
}
for (unsigned i = 0; i < vectors.size(); ++i) {
solvers[position]->SetVectorValue(i, vectors[i][dim], 0);
}
solvers[position]->Solve();
}
void SolverBank::ExpandSolverContainer(SolverContainer &solvers,
unsigned position) {
unsigned num_added_solvers = position - solvers.size() + 1;
for (unsigned i = 0; i < num_added_solvers; ++i) {
solvers.push_back(NULL);
}
}
void SolverBank::InitializeSolver(SolverType *solver, unsigned order,
bool open) {
solver->SetNumberOfMatrices(1);
solver->SetNumberOfVectors(1);
solver->SetNumberOfSolutions(1);
solver->SetMaximumNonZeroValuesInMatrix(kMinimumEvolvingSize * order);
solver->SetSystemOrder(order);
solver->InitializeMatrix(0);
solver->InitializeVector(0);
solver->InitializeSolution(0);
if (open)
this->FillMatrixOpen(solver, order);
else
this->FillMatrixClosed(solver, order);
}
void SolverBank::FillMatrixOpen(SolverType *solver, unsigned order) {
/* alpha_0 = 0; alpha_{N-1} = alpha; beta_0 = beta_{N-1} = 0 */
const double diag0 = 2 * alpha_ + 6 * beta_ + gamma_;
const double diag1 = -alpha_ - 4 * beta_;
// main diagonal
solver->SetMatrixValue(0, 0, alpha_ + beta_ + gamma_, 0);
solver->SetMatrixValue(1, 1, 2 * alpha_ + 5 * beta_ + gamma_, 0);
for (unsigned i = 2; i < order - 2; i++)
solver->SetMatrixValue(i, i, diag0, 0);
solver->SetMatrixValue(order - 2, order - 2,
2 * alpha_ + 5 * beta_ + gamma_, 0);
solver->SetMatrixValue(order - 1, order - 1, alpha_ + beta_ + gamma_, 0);
// +1/-1 diagonal
solver->SetMatrixValue(0, 1, -alpha_ - 2 * beta_, 0);
solver->SetMatrixValue(1, 0, -alpha_ - 2 * beta_, 0);
for (unsigned i = 1; i < order - 2; i++) {
solver->SetMatrixValue(i, i + 1, diag1, 0);
solver->SetMatrixValue(i + 1, i, diag1, 0);
}
solver->SetMatrixValue(order - 2, order - 1, -alpha_ - 2 * beta_, 0);
solver->SetMatrixValue(order - 1, order - 2, -alpha_ - 2 * beta_, 0);
// +2/-2 diagonal
for (unsigned i = 2; i < order; ++i) {
solver->SetMatrixValue(i, i-2, beta_, 0);
solver->SetMatrixValue(i-2, i, beta_, 0);
}
}
void SolverBank::FillMatrixClosed(SolverType *solver, unsigned order) {
const double diag0 = 2 * alpha_ + 6 * beta_ + gamma_;
const double diag1 = -alpha_ - 4 * beta_;
for (unsigned i = 0; i < order; ++i) {
solver->SetMatrixValue(i, (i+order-2)%order, beta_, 0);
solver->SetMatrixValue(i, (i+order-1)%order, diag1, 0);
solver->SetMatrixValue(i, i, diag0, 0);
solver->SetMatrixValue(i, (i+order+1)%order, diag1, 0);
solver->SetMatrixValue(i, (i+order+2)%order, beta_, 0);
}
}
double SolverBank::GetSolution(unsigned order, unsigned index, bool open) {
SolverContainer &solvers = open? open_solvers_ : closed_solvers_;
return solvers[order - kMinimumEvolvingSize]->GetSolutionValue(index, 0);
}
} // namespace soax
| 31.172185 | 75 | 0.647546 | frenebo |
b5722f716ca8c1cf400982c86e5c78912e13ed10 | 2,776 | cpp | C++ | src/ofxNode.cpp | lpestl/ofxGraphVisualization | 218e67b2519eed5050f09f51e31260690fe4eacc | [
"MIT"
] | null | null | null | src/ofxNode.cpp | lpestl/ofxGraphVisualization | 218e67b2519eed5050f09f51e31260690fe4eacc | [
"MIT"
] | null | null | null | src/ofxNode.cpp | lpestl/ofxGraphVisualization | 218e67b2519eed5050f09f51e31260690fe4eacc | [
"MIT"
] | null | null | null | #include "ofxNode.h"
#include <random>
#include "ofxTweener.h"
void ofxNode::setup(std::shared_ptr<ofRectangle> boundRect, std::shared_ptr<ofxTrueTypeFontUC> font)
{
captureFont_ = font;
boundRect_ = boundRect;
position_.set(ofRandom(boundRect_->getMinX(), boundRect_->getMaxX()), ofRandom(boundRect_->getMinY(), boundRect_->getMaxY())/*xRange(generator), yRange(generator)*/);
speed_.set(0, 0);
}
void ofxNode::update()
{
updatePosition();
}
void ofxNode::draw(bool isNameVisible)
{
ofDrawCircle(position_.x, position_.y, radius_);
if (isNameVisible)
{
ofPushStyle();
ofSetColor(ofColor::black);
const auto capture = ofToString(id_);
if ((captureFont_ != nullptr) && (captureFont_->isLoaded()))
{
const auto textRect = captureFont_->getStringBoundingBox(capture, position_.x, position_.y);
captureFont_->drawString(ofToString(id_), position_.x - textRect.width / 2, position_.y + textRect.height / 2);
}
else
{
ofDrawBitmapString(capture, position_.x, position_.y);
}
ofPopStyle();
}
}
void ofxNode::setPosition(ofVec2f newPos)
{
if (boundRect_->inside(newPos))
{
position_.set(newPos);
}
}
ofVec2f ofxNode::getPosition() const
{
return position_;
}
void ofxNode::setSpeed(ofVec2f newSpeed)
{
speed_.set(newSpeed);
}
ofVec2f ofxNode::getSpeed() const
{
return speed_;
}
void ofxNode::setRadius(float radius)
{
targetRadius_ = radius;
//radius_ = radius;
Tweener.addTween(radius_, targetRadius_, 0.5);
}
float ofxNode::getRadius() const
{
return radius_;
}
float ofxNode::getTargetRadius() const
{
return targetRadius_;
}
void ofxNode::updatePosition()
{
if (!((speed_.x == 0) && (speed_.y == 0))) {
const auto deltaTime = ofGetLastFrameTime();
ofVec2f deltaPos(speed_.x * deltaTime, speed_.y * deltaTime);
if (!boundRect_->inside(position_.x + deltaPos.x, position_.y))
{
if ((position_.x + deltaPos.x) < boundRect_->getMinX())
{
position_.x = boundRect_->getMinX() - position_.x - deltaPos.x + boundRect_->getMinX();
speed_.x = speed_.x * -1;
}
if ((position_.x + deltaPos.x) >= boundRect_->getMaxX())
{
position_.x = boundRect_->getMaxX() - position_.x - deltaPos.x + boundRect_->getMaxX();
speed_.x = speed_.x * -1;
}
}
else
position_.x += deltaPos.x;
if (!boundRect_->inside(position_.x, position_.y + deltaPos.y))
{
if ((position_.y + deltaPos.y) < boundRect_->getMinY())
{
position_.y = boundRect_->getMinY() - position_.y - deltaPos.y + boundRect_->getMinY();
speed_.y = speed_.y * -1;
}
if ((position_.y + deltaPos.y) >= boundRect_->getMaxY())
{
position_.y = boundRect_->getMaxY() - position_.y - deltaPos.y + boundRect_->getMaxY();
speed_.y = speed_.y * -1;
}
}
else
position_.y += deltaPos.y;
}
}
| 22.208 | 167 | 0.674352 | lpestl |
b5729bc51e2f1e778024289cec93bc0e1651c438 | 639 | cc | C++ | system_info/system_info_cellular_network_desktop.cc | sstolinski/tizen-extensions-crosswalk | 749cf5285bf1c9c04a4ce9f3880a744dcf221a69 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2016-11-21T21:21:19.000Z | 2016-11-21T21:21:19.000Z | system_info/system_info_cellular_network_desktop.cc | sstolinski/tizen-extensions-crosswalk | 749cf5285bf1c9c04a4ce9f3880a744dcf221a69 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | system_info/system_info_cellular_network_desktop.cc | sstolinski/tizen-extensions-crosswalk | 749cf5285bf1c9c04a4ce9f3880a744dcf221a69 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "system_info/system_info_cellular_network.h"
const std::string SysInfoCellularNetwork::name_ = "CELLULAR_NETWORK";
void SysInfoCellularNetwork::Get(picojson::value& error,
picojson::value& data) {
system_info::SetPicoJsonObjectValue(error, "message",
picojson::value("Cellular Network is not supported on desktop."));
}
void SysInfoCellularNetwork::StartListening() { }
void SysInfoCellularNetwork::StopListening() { }
| 37.588235 | 73 | 0.730829 | sstolinski |
b57442bec007ffc6c7f2cb92d52dffcd43e3c08c | 2,574 | hpp | C++ | engine/include/ph/sdl/Mouse.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/sdl/Mouse.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/sdl/Mouse.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
// For other contributors see Contributors.txt
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#pragma once
#include <SDL.h>
#include <sfz/containers/DynArray.hpp>
#include <sfz/geometry/AABB2D.hpp>
#include <sfz/math/Vector.hpp>
#include "ph/sdl/ButtonState.hpp"
namespace ph {
namespace sdl {
using sfz::DynArray;
using sfz::AABB2D;
using sfz::vec2;
// Mouse structs
// ------------------------------------------------------------------------------------------------
struct Mouse final {
// Public members
// --------------------------------------------------------------------------------------------
ButtonState leftButton = ButtonState::NOT_PRESSED;
ButtonState rightButton = ButtonState::NOT_PRESSED;
ButtonState middleButton = ButtonState::NOT_PRESSED;
/// A raw position should be in the range [0, 1] where (0,0) is the bottom left corner.
/// In a scaled mouse from "scaleMouse()" the position should be in the specified coordinate
/// system.
vec2 position;
vec2 motion; // Positive-x: right, Positive-y: up
vec2 wheel;
// Constructors & destructors
// --------------------------------------------------------------------------------------------
Mouse() noexcept = default;
Mouse(const Mouse&) noexcept = default;
Mouse& operator= (const Mouse&) noexcept = default;
// Public methods
// --------------------------------------------------------------------------------------------
void update(int windowWidth, int windowHeight, const DynArray<SDL_Event>& events) noexcept;
Mouse scaleMouse(vec2 camPos, vec2 camDim) const noexcept;
Mouse scaleMouse(const AABB2D& camera) const noexcept;
};
} // namespace sdl
} // namespace ph
| 34.783784 | 99 | 0.628205 | PetorSFZ |
b57989b723bd246a6624c126ca4f3f2acf401fcf | 1,125 | cpp | C++ | IGC/AdaptorOCL/cif/cif/import/cif_main.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 440 | 2018-01-30T00:43:22.000Z | 2022-03-24T17:28:37.000Z | IGC/AdaptorOCL/cif/cif/import/cif_main.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 225 | 2018-02-02T03:10:47.000Z | 2022-03-31T10:50:37.000Z | IGC/AdaptorOCL/cif/cif/import/cif_main.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 138 | 2018-01-30T08:15:11.000Z | 2022-03-22T14:16:39.000Z | /*========================== begin_copyright_notice ============================
Copyright (C) 2017-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "cif/common/cif.h"
#include "cif/import/library_api.h"
#include "cif/import/cif_main.h"
namespace CIF {
CIF::RAII::UPtr_t<CIFMain> OpenLibraryInterface(LibraryHandle &lib) {
CIFMain *ret = nullptr;
void *createMainFuncPtr = lib.GetFuncPointer(CIF::CreateCIFMainFuncName);
if (createMainFuncPtr == nullptr) {
return CIF::RAII::UPtr(ret = nullptr);
}
auto CreateCIFFunc =
reinterpret_cast<CIF::CreateCIFMainFunc_t>(createMainFuncPtr);
auto main = (*CreateCIFFunc)();
return CIF::RAII::UPtr(main);
}
std::unique_ptr<CIFPackage>
OpenLibraryInterface(std::unique_ptr<CIF::LibraryHandle> &&lib) {
if (lib.get() == nullptr) {
return std::unique_ptr<CIFPackage>(nullptr);
}
auto entryPoint = OpenLibraryInterface(*lib.get());
CIFPackage *pckg = new CIFPackage(std::move(entryPoint), std::move(lib));
return std::unique_ptr<CIFPackage>(pckg);
}
}
| 30.405405 | 80 | 0.657778 | kurapov-peter |
b579e2c62547c27f052a384b37705400e2b6f822 | 507 | hpp | C++ | osc-seq-cpp/src/ui_elements/text_elt.hpp | Acaruso/osc-seq-cpp | 14d2d5ce0fdad8d183e19781a279f9442db9c79f | [
"MIT"
] | null | null | null | osc-seq-cpp/src/ui_elements/text_elt.hpp | Acaruso/osc-seq-cpp | 14d2d5ce0fdad8d183e19781a279f9442db9c79f | [
"MIT"
] | null | null | null | osc-seq-cpp/src/ui_elements/text_elt.hpp | Acaruso/osc-seq-cpp | 14d2d5ce0fdad8d183e19781a279f9442db9c79f | [
"MIT"
] | null | null | null | #pragma once
#include <functional>
#include <string>
#include <SDL.h>
#include <SDL_ttf.h>
#include "../store/coord.hpp"
#include "../store/store.hpp"
void text_elt(std::string text, Coord& coord, Store& store, int z_coord = 1);
void text_elt(std::string text, FC_Font* font, Coord& coord, Store& store, int z_coord = 1);
void text_elt_draggable(
std::string id,
std::string text,
Coord& coord,
Store& store,
std::function<void()> on_click,
std::function<void(int)> on_drag
);
| 21.125 | 92 | 0.676529 | Acaruso |
Subsets and Splits