hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
84ec95c44cc910110f3ba23ac3f3ad8e20017554
25,603
cpp
C++
src/Component/Component.cpp
TheReincarnator/glaziery
f688943163b73cea7034e929539fff8aa39d63e5
[ "MIT" ]
null
null
null
src/Component/Component.cpp
TheReincarnator/glaziery
f688943163b73cea7034e929539fff8aa39d63e5
[ "MIT" ]
null
null
null
src/Component/Component.cpp
TheReincarnator/glaziery
f688943163b73cea7034e929539fff8aa39d63e5
[ "MIT" ]
null
null
null
/* * This file is part of the Glaziery. * Copyright Thomas Jacob. * * READ README.TXT BEFORE USE!! */ // Main header file #include <Glaziery/src/Headers.h> Component::Component() { ASSERTION_COBJECT(this); disposed = false; maximumSize = Vector(4096, 4096); minimumSize = Vector(0, 0); parent = NULL; size = Vector(64, 32); visible = true; visibleDeferred = visible; } Component::~Component() { ASSERTION_COBJECT(this); while (!effects.IsEmpty()) { ComponentEffect * effect = effects.UnlinkFirst(); effect->onComponentDestroying(); effect->release(); } } void Component::addEffect(ComponentEffect * effect) { ASSERTION_COBJECT(this); effects.Append(effect); effect->addReference(); } void Component::addContextMenuItems(Menu * menu, Vector position, bool option1, bool option2) { ASSERTION_COBJECT(this); } void Component::appendWidget(Widget * widget) { ASSERTION_COBJECT(this); if (widget->component != NULL) throw EILLEGALSTATE("The widget is already registered to another component"); widget->component = this; widgets.Append(widget); } void Component::cancelEffects() { ASSERTION_COBJECT(this); for (int i=0; i<effects.GetCount(); i++) effects.Get(i)->cancel(); } void Component::center() { ASSERTION_COBJECT(this); Vector parentSize; if (parent != NULL) parentSize = parent->getSize(); else { PlatformAdapter * adapter = Desktop::getInstance()->getPlatformAdapter(); parentSize = adapter->getScreenSize(); } moveTo((parentSize - size) / 2); } void Component::deleteChild(Component * child) { ASSERTION_COBJECT(this); ASSERTION_COBJECT(child); if (child->getParent() != this) throw EILLEGALARGUMENT("The component is not a child of this component"); delete child; } void Component::destroy() { ASSERTION_COBJECT(this); if (disposed) return; // Add the component to the disposables. // It will be destroyed next frame. disposed = true; Desktop * desktop = Desktop::getInstance(); desktop->addDisposable(this); // Then, notify listeners. onDestroying(); } void Component::executeDeferrals() { ASSERTION_COBJECT(this); EventTarget::executeDeferrals(); if (visibleDeferred && !visible) show(); else if (!visibleDeferred && visible) hide(); } Vector Component::getAbsolutePosition() { ASSERTION_COBJECT(this); if (parent == NULL) return position; else return position + parent->getChildrenOrigin(); } Vector Component::getChildrenOrigin() { ASSERTION_COBJECT(this); return getAbsolutePosition(); } const ArrayList<ComponentEffect> & Component::getEffects() { ASSERTION_COBJECT(this); return effects; } EventTarget * Component::getEventTargetAt(Vector position) { ASSERTION_COBJECT(this); int widgetsCount = widgets.GetCount(); for (int i=0; i<widgetsCount; i++) { Widget * widget = widgets.Get(i); if (widget->isHitAt(position)) return widget; } return this; } Component * Component::getFocusChild() { ASSERTION_COBJECT(this); return NULL; } Vector Component::getMaximumSize() { ASSERTION_COBJECT(this); return maximumSize; } Vector Component::getMinimumSize() { ASSERTION_COBJECT(this); return minimumSize; } Vector Component::getOrigin() { ASSERTION_COBJECT(this); return getAbsolutePosition(); } Component * Component::getParent() { ASSERTION_COBJECT(this); return parent; } Vector Component::getPosition() { ASSERTION_COBJECT(this); return position; } class Vector Component::getSize() { ASSERTION_COBJECT(this); return size; } const ArrayList<Widget> & Component::getWidgets() { ASSERTION_COBJECT(this); return widgets; } bool Component::hasFocus() { ASSERTION_COBJECT(this); Component * parent = getParent(); if (parent != NULL) return parent->getFocusChild() == this && parent->hasFocus(); else return Desktop::getInstance()->getFocusWindowOrPopup() == this; } void Component::hide() { ASSERTION_COBJECT(this); if (!visible) return; // Invalidation must take place before hiding, because the invalidate checks that flag invalidate(); visible = false; visibleDeferred = visible; int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onHidden(this); } } void Component::hideDeferred() { ASSERTION_COBJECT(this); setVisibleDeferred(false); } #if defined(_DEBUG) && (defined(_AFX) || defined(_AFXDLL)) IMPLEMENT_DYNAMIC(Component, EventTarget); #endif void Component::invalidate() { ASSERTION_COBJECT(this); invalidateArea(Vector(), size); } void Component::invalidateArea(Vector position, Vector size) { ASSERTION_COBJECT(this); Component * parent = getParent(); if (parent != NULL && parent->isChildVisible(this)) parent->invalidateArea(getPosition() + position, size); } bool Component::isChildVisible(Component * child) { ASSERTION_COBJECT(this); return child->isVisible(); } bool Component::isDisposed() { ASSERTION_COBJECT(this); return disposed; } bool Component::isVisible() { ASSERTION_COBJECT(this); return visible; } bool Component::isVisibleIncludingAncestors() { ASSERTION_COBJECT(this); Component * ancestor = this; while (ancestor != NULL) { if (!ancestor->isVisible()) return false; ancestor = ancestor->getParent(); } return true; } void Component::moveComponent(Component * relatedComponent, Vector position) { ASSERTION_COBJECT(this); relatedComponent->moveInternal(position, false); } bool Component::moveInternal(Vector position, bool notifyParent) { ASSERTION_COBJECT(this); if (this->position == position) return false; Vector oldPosition = this->position; this->position = position; if (parent != NULL && notifyParent) parent->onChildMoved(this, oldPosition); int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onMoved(this, oldPosition); } invalidate(); return true; } bool Component::moveRelative(Vector delta) { ASSERTION_COBJECT(this); return moveTo(position + delta); } bool Component::moveTo(Vector position) { ASSERTION_COBJECT(this); return moveInternal(position, true); } bool Component::onAnyKey(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onAnyKey(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onAnyKey(option1, option2)) consumed = true; return consumed; } bool Component::onBackSpace() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onBackSpace(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onBackSpace()) consumed = true; return consumed; } bool Component::onBackTab(bool secondary) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onBackTab(secondary); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onBackTab(secondary)) consumed = true; return consumed; } bool Component::onCancel() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCancel(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCancel()) consumed = true; return consumed; } bool Component::onCharacter(char character, bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCharacter(character, option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCharacter(character, option1, option2)) consumed = true; return consumed; } void Component::onChildMaximumSizeChanged(Component * child, Vector oldMaximumSize) { ASSERTION_COBJECT(this); } void Component::onChildMinimumSizeChanged(Component * child, Vector oldMinimumSize) { ASSERTION_COBJECT(this); } void Component::onChildMoved(Component * child, Vector oldPosition) { ASSERTION_COBJECT(this); } void Component::onChildResized(Component * child, Vector oldSize) { ASSERTION_COBJECT(this); } void Component::onContextClick(Vector position, bool option1, bool option2) { ASSERTION_COBJECT(this); EventTarget::onContextClick(position, option1, option2); Menu * menu; if ((menu = new Menu(this)) == NULL) throw EOUTOFMEMORY; addContextMenuItems(menu, position, option1, option2); if (menu->getItems().IsEmpty()) { delete menu; return; } MenuPopup * popup = new MenuPopup(menu, true); Desktop::getInstance()->addPopup(popup); Vector popupPosition = getAbsolutePosition() + position; if (popupPosition.x + popup->getSize().x > Desktop::getInstance()->getSize().x) popupPosition.x -= popup->getSize().x; if (popupPosition.y + popup->getSize().y > Desktop::getInstance()->getSize().y) popupPosition.y -= popup->getSize().y; popup->moveTo(popupPosition); } bool Component::onCopy() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCopy(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCopy()) consumed = true; return consumed; } bool Component::onCut() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onCut(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onCut()) consumed = true; return consumed; } bool Component::onDelete() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onDelete(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onDelete()) consumed = true; return consumed; } void Component::onDestroying() { ASSERTION_COBJECT(this); ArrayList<Component::Listener> listenersToNotify; int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) { listenersToNotify.Append(componentListener); componentListener->addReference(); } } listenersCount = listenersToNotify.GetCount(); while (!listenersToNotify.IsEmpty()) { Component::Listener * listener = listenersToNotify.UnlinkFirst(); listener->onDestroying(this); listener->release(); } } bool Component::onEdit() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onEdit(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onEdit()) consumed = true; return consumed; } bool Component::onEnter(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onEnter(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onEnter(option1, option2)) consumed = true; return consumed; } void Component::onGotFocus(bool byParent) { ASSERTION_COBJECT(this); // First notify listeners of this component about focus gain int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onGotFocus(this, byParent); } // Then notify child Component * focusChild = getFocusChild(); if (focusChild != NULL) focusChild->onGotFocus(true); // Finally, invalidate the component invalidate(); } bool Component::onHotKey(char character, bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onHotKey(character, option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onHotKey(character, option1, option2)) consumed = true; return consumed; } bool Component::onKeyStroke(int keyCode, bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onKeyStroke(keyCode, option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onKeyStroke(keyCode, option1, option2)) consumed = true; return consumed; } void Component::onLostFocus() { ASSERTION_COBJECT(this); // First notify child about focus loss Component * focusChild = getFocusChild(); if (focusChild != NULL) focusChild->onLostFocus(); // Then notify listeners of this component int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onLostFocus(this); } // Finally, invalidate the component invalidate(); } void Component::onMaximumSizeChanged(Vector oldMaximumSize) { ASSERTION_COBJECT(this); } void Component::onMinimumSizeChanged(Vector oldMinimumSize) { ASSERTION_COBJECT(this); } bool Component::onMoveDown(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveDown(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveDown(option1, option2)) consumed = true; return consumed; } bool Component::onMoveLeft(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveLeft(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveLeft(option1, option2)) consumed = true; return consumed; } bool Component::onMoveRight(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveRight(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveRight(option1, option2)) consumed = true; return consumed; } bool Component::onMoveToEnd(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveToEnd(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveToEnd(option1, option2)) consumed = true; return consumed; } bool Component::onMoveToStart(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveToStart(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveToStart(option1, option2)) consumed = true; return consumed; } bool Component::onMoveUp(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onMoveUp(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onMoveUp(option1, option2)) consumed = true; return consumed; } bool Component::onPageDown(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onPageDown(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onPageDown(option1, option2)) consumed = true; return consumed; } bool Component::onPageUp(bool option1, bool option2) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onPageUp(option1, option2); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onPageUp(option1, option2)) consumed = true; return consumed; } bool Component::onPaste() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onPaste(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onPaste()) consumed = true; return consumed; } bool Component::onSelectAll() { ASSERTION_COBJECT(this); bool consumed = EventTarget::onSelectAll(); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onSelectAll()) consumed = true; return consumed; } bool Component::onTab(bool secondary) { ASSERTION_COBJECT(this); bool consumed = EventTarget::onTab(secondary); Component * focusChild = getFocusChild(); if (focusChild != NULL) if (focusChild->onTab(secondary)) consumed = true; return consumed; } void Component::prependWidget(Widget * widget) { ASSERTION_COBJECT(this); if (widget->component != NULL) throw EILLEGALARGUMENT("The widget is already registered to another component"); widget->component = this; widgets.Prepend(widget); } void Component::removeEffect(ComponentEffect * effect) { ASSERTION_COBJECT(this); ComponentEffect * unlinkedEffect = effects.Unlink(effect); if (unlinkedEffect != NULL) unlinkedEffect->release(); } void Component::removeWidget(Widget * widget) { ASSERTION_COBJECT(this); widgets.Delete(widget); } bool Component::resize(Vector size) { ASSERTION_COBJECT(this); return resizeInternal(size, true); } bool Component::resizeToMaximum() { ASSERTION_COBJECT(this); return resizeInternal(maximumSize, true); } bool Component::resizeToMinimum() { ASSERTION_COBJECT(this); return resizeInternal(minimumSize, true); } void Component::resizeComponent(Component * relatedComponent, Vector size) { ASSERTION_COBJECT(this); relatedComponent->resizeInternal(size, false); } bool Component::resizeInternal(Vector size, bool notifyParent) { ASSERTION_COBJECT(this); size = Vector(size.x > maximumSize.x ? maximumSize.x : size.x, size.y > maximumSize.y ? maximumSize.y : size.y); size = Vector(size.x < minimumSize.x ? minimumSize.x : size.x, size.y < minimumSize.y ? minimumSize.y : size.y); if (this->size == size) return false; Vector oldSize = this->size; this->size = size; if (parent != NULL && notifyParent) parent->onChildResized(this, oldSize); int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onResized(this, oldSize); } invalidate(); return true; } void Component::setComponentParent(Component * child) { ASSERTION_COBJECT(this); if (child->getParent() != NULL) throw EILLEGALARGUMENT("The component already has a parent, it may not be changed"); child->parent = this; } void Component::setComponentMaximumSize(Component * component, Vector maximumSize, bool notifyParent) { ASSERTION_COBJECT(this); component->setMaximumSizeInternal(maximumSize, notifyParent); } void Component::setComponentMinimumSize(Component * component, Vector minimumSize, bool notifyParent) { ASSERTION_COBJECT(this); component->setMinimumSizeInternal(minimumSize, notifyParent); } void Component::setDisposed() { ASSERTION_COBJECT(this); disposed = true; } void Component::setMaximumSize(Vector maximumSize) { ASSERTION_COBJECT(this); setMaximumSizeInternal(maximumSize, true); } void Component::setMaximumSizeInternal(Vector maximumSize, bool notifyParent) { ASSERTION_COBJECT(this); if (maximumSize.x < 0) maximumSize.x = 0; if (maximumSize.y < 0) maximumSize.y = 0; if (this->maximumSize == maximumSize) return; Vector oldMaximumSize = this->maximumSize; this->maximumSize = maximumSize; onMaximumSizeChanged(oldMaximumSize); if (notifyParent && parent != NULL) parent->onChildMaximumSizeChanged(this, oldMaximumSize); if (!(minimumSize <= maximumSize)) setMinimumSize(Vector(minimumSize.x > maximumSize.x ? maximumSize.x : minimumSize.x, minimumSize.y > maximumSize.y ? maximumSize.y : minimumSize.y)); if (!(size <= maximumSize)) resize(Vector(size.x > maximumSize.x ? maximumSize.x : size.x, size.y > maximumSize.y ? maximumSize.y : size.y)); } void Component::setMinimumSize(Vector minimumSize) { ASSERTION_COBJECT(this); setMinimumSizeInternal(minimumSize, true); } void Component::setMinimumSizeInternal(Vector minimumSize, bool notifyParent) { ASSERTION_COBJECT(this); if (minimumSize.x < 0) minimumSize.x = 0; if (minimumSize.y < 0) minimumSize.y = 0; if (this->minimumSize == minimumSize) return; Vector oldMinimumSize = this->minimumSize; this->minimumSize = minimumSize; onMinimumSizeChanged(oldMinimumSize); if (notifyParent && parent != NULL) parent->onChildMinimumSizeChanged(this, oldMinimumSize); if (!(maximumSize >= minimumSize)) setMaximumSize(Vector(maximumSize.x < minimumSize.x ? minimumSize.x : maximumSize.x, maximumSize.y < minimumSize.y ? minimumSize.y : maximumSize.y)); if (!(size >= minimumSize)) resize(Vector(size.x < minimumSize.x ? minimumSize.x : size.x, size.y < minimumSize.y ? minimumSize.y : size.y)); } void Component::setSkinData(SkinData * skinData) { ASSERTION_COBJECT(this); GlazieryObject::setSkinData(skinData); skinData->component = this; } void Component::setVisible(bool visible) { ASSERTION_COBJECT(this); if (visible) show(); else hide(); } void Component::setVisibleDeferred(bool visible) { ASSERTION_COBJECT(this); if (visible) showDeferred(); else hideDeferred(); } void Component::show() { ASSERTION_COBJECT(this); if (visible) return; visible = true; visibleDeferred = visible; int listenersCount = listeners.GetCount(); for (int i=0; i<listenersCount; i++) { Component::Listener * componentListener = dynamic_cast<Component::Listener *>(listeners.Get(i)); if (componentListener != NULL) componentListener->onShown(this); } invalidate(); } BalloonPopup * Component::showBalloonPopup(const String & text) { ASSERTION_COBJECT(this); BalloonPopup * popup; if ((popup = new BalloonPopup) == NULL) throw EOUTOFMEMORY; Desktop::getInstance()->addPopup(popup); popup->setMessage(text); popup->pointTo(this); return popup; } void Component::showDeferred() { ASSERTION_COBJECT(this); Mutex * mutex = Desktop::getInstance()->getDeferralMutex(); if (!mutex->lock()) return; visibleDeferred = visible; Desktop::getInstance()->deferObject(this); mutex->release(); } String Component::toString() { ASSERTION_COBJECT(this); String string; string.Format("Component(position:%s,size:%s)", (const char *) position.toString(), (const char *) size.toString()); return string; } void Component::tutorialClick(PointerEffect::ButtonEffect buttonEffect, bool option1, bool option2, long time) { ASSERTION_COBJECT(this); Desktop * desktop = Desktop::getInstance(); if (!Desktop::getInstance()->isTutorialMode()) throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only"); if (time < 0) time = 1000; if (buttonEffect == PointerEffect::BUTTONEFFECT_DRAGDROP) throw EILLEGALARGUMENT("tutorialClick cannot have a drag-drop button effect. Use tutorialDragDropTo instead."); Vector positionEnd = getAbsolutePosition() + getSize() / 2; if (Desktop::getInstance()->getPointerPosition() == positionEnd) time = 0; PointerEffect * pointerEffect; if ((pointerEffect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; pointerEffect->setPositionEnd(positionEnd); pointerEffect->setTimeCurveToAcceleration(); pointerEffect->setButtonEffect(buttonEffect); pointerEffect->setButtonOption1(option1); pointerEffect->setButtonOption2(option2); Desktop::getInstance()->addEffect(pointerEffect); pointerEffect->waitFor(); } void Component::tutorialDragDropTo(Vector position, bool option1, bool option2, long time) { ASSERTION_COBJECT(this); if (!Desktop::getInstance()->isTutorialMode()) throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only"); if (time < 0) time = 1000; EffectSequence * sequence; if ((sequence = new EffectSequence) == NULL) throw EOUTOFMEMORY; Vector dragPosition = getAbsolutePosition() + getSize() / 2; if (Desktop::getInstance()->getPointerPosition() == dragPosition) time = 0; PointerEffect * effect; if ((effect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; effect->setPositionEnd(dragPosition); effect->setTimeCurveToAcceleration(); sequence->appendEffect(effect); if ((effect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; effect->setPositionEnd(position); effect->setTimeCurveToAcceleration(); effect->setButtonEffect(PointerEffect::BUTTONEFFECT_DRAGDROP); effect->setButtonOption1(option1); effect->setButtonOption2(option2); sequence->appendEffect(effect); Desktop::getInstance()->addEffect(sequence); effect->waitFor(); } void Component::tutorialMoveTo(long time) { ASSERTION_COBJECT(this); if (!Desktop::getInstance()->isTutorialMode()) throw EILLEGALSTATE("Use the tutorial methods in Tutorial::run() implementations only"); Vector positionEnd = getAbsolutePosition() + getSize() / 2; if (Desktop::getInstance()->getPointerPosition() == positionEnd) return; if (time < 0) time = 1000; PointerEffect * effect; if ((effect = new PointerEffect(time)) == NULL) \ throw EOUTOFMEMORY; effect->setPositionEnd(positionEnd); effect->setTimeCurveToAcceleration(); Desktop::getInstance()->addEffect(effect); effect->waitFor(); } void Component::unsetComponentParent(Component * child) { ASSERTION_COBJECT(this); ASSERTION_COBJECT(child); child->parent = NULL; } void Component::Listener::onDestroying(Component * component) { ASSERTION_COBJECT(this); } void Component::Listener::onGotFocus(Component * component, bool byParent) { ASSERTION_COBJECT(this); } void Component::Listener::onHidden(Component * component) { ASSERTION_COBJECT(this); } void Component::Listener::onLostFocus(Component * component) { ASSERTION_COBJECT(this); } void Component::Listener::onMoved(Component * component, Vector oldPosition) { ASSERTION_COBJECT(this); } void Component::Listener::onResized(Component * component, Vector oldSize) { ASSERTION_COBJECT(this); } void Component::Listener::onShown(Component * component) { ASSERTION_COBJECT(this); }
21.389307
113
0.732883
TheReincarnator
84eecad9d8db36e8099376e696f0e1c538abaecf
1,724
cpp
C++
lib/AnnotateInstructions.cpp
compor/loop-meta-annotator
2ecc6633960c1372e1f88c493fe7831f0df0ee7d
[ "MIT" ]
null
null
null
lib/AnnotateInstructions.cpp
compor/loop-meta-annotator
2ecc6633960c1372e1f88c493fe7831f0df0ee7d
[ "MIT" ]
null
null
null
lib/AnnotateInstructions.cpp
compor/loop-meta-annotator
2ecc6633960c1372e1f88c493fe7831f0df0ee7d
[ "MIT" ]
1
2020-06-16T10:21:20.000Z
2020-06-16T10:21:20.000Z
// // // #include "AnnotateValues/AnnotateInstructions.hpp" #include "llvm/IR/Module.h" // using llvm::Module #include "llvm/IR/Type.h" // using llvm::IntType #include "llvm/IR/Constants.h" // using llvm::ConstantInt #include "llvm/IR/Metadata.h" // using llvm::Metadata // using llvm::MDNode // using llvm::ConstantAsMetadata #include "llvm/IR/MDBuilder.h" // using llvm::MDBuilder #include "llvm/ADT/SmallVector.h" // using llvm::SmallVector #include "llvm/Support/Casting.h" // using llvm::dyn_cast #include <cassert> // using assert namespace icsa { namespace AnnotateInstructions { bool Reader::has(const llvm::Instruction &CurInstruction) const { return nullptr != CurInstruction.getMetadata(key()); } InstructionIDTy Reader::get(const llvm::Instruction &CurInstruction) const { const auto *IDNode = CurInstruction.getMetadata(key()); assert(nullptr != IDNode && "Instruction does not have the requested metadata!"); const auto *constantMD = llvm::dyn_cast<llvm::ConstantAsMetadata>(IDNode->getOperand(1).get()); const auto &IDConstant = constantMD->getValue()->getUniqueInteger(); return IDConstant.getLimitedValue(); } // InstructionIDTy Writer::put(llvm::Instruction &CurInstruction) { auto &curContext = CurInstruction.getParent()->getParent()->getContext(); llvm::MDBuilder builder{curContext}; auto *intType = llvm::Type::getInt32Ty(curContext); auto curID = current(); llvm::SmallVector<llvm::Metadata *, 1> IDValues{ builder.createConstant(llvm::ConstantInt::get(intType, curID))}; next(); CurInstruction.setMetadata(key(), llvm::MDNode::get(curContext, IDValues)); return curID; } } // namespace AnnotateInstructions } // namespace icsa
23.616438
77
0.723898
compor
84efda42e10bc5a89ecf957576cddb0c81dd3c5d
519
hpp
C++
Game.hpp
CLA-TC1030/s1t1.sye
c210a4956fe0fbb978b1d541d2fdf6079f804585
[ "MIT" ]
null
null
null
Game.hpp
CLA-TC1030/s1t1.sye
c210a4956fe0fbb978b1d541d2fdf6079f804585
[ "MIT" ]
null
null
null
Game.hpp
CLA-TC1030/s1t1.sye
c210a4956fe0fbb978b1d541d2fdf6079f804585
[ "MIT" ]
null
null
null
#pragma once #include "Ctesconf.hpp" #include "Tablero.hpp" #include "Jugador.hpp" #include "CDado.hpp" #include <fstream> #include <ostream> class Game { private: Tablero t; Jugador j[MAX_JUGADORES]; CDado d; bool swio; // Archivos de entrada/salida para el caso de configuracion de IO por archivos --------- std::ifstream fi{"input"}; std::ofstream fo{"output"}; public: static int turno; Game(); Game(std::string, bool, bool); void start(); void outMsg(std::string); };
19.961538
88
0.649326
CLA-TC1030
84f4004ce83c63e784a536adba6b4f4724bafc27
2,696
cpp
C++
src/fuselage/CCPACSFuselages.cpp
Mk-arc/tigl
45ace0b17008e2beab3286babe310a817fcd6578
[ "Apache-2.0" ]
171
2015-04-13T11:24:34.000Z
2022-03-26T00:56:38.000Z
src/fuselage/CCPACSFuselages.cpp
Mk-arc/tigl
45ace0b17008e2beab3286babe310a817fcd6578
[ "Apache-2.0" ]
620
2015-01-20T08:34:36.000Z
2022-03-30T11:05:33.000Z
src/fuselage/CCPACSFuselages.cpp
Mk-arc/tigl
45ace0b17008e2beab3286babe310a817fcd6578
[ "Apache-2.0" ]
56
2015-02-09T13:33:56.000Z
2022-03-19T04:52:51.000Z
/* * Copyright (C) 2007-2013 German Aerospace Center (DLR/SC) * * Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de> * 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. */ /** * @file * @brief Implementation of CPACS fuselages handling routines. */ #include "CCPACSFuselages.h" #include "CCPACSFuselage.h" #include "CCPACSAircraftModel.h" #include "CCPACSFuselageProfiles.h" #include "CCPACSConfiguration.h" #include "CTiglError.h" namespace tigl { CCPACSFuselages::CCPACSFuselages(CCPACSAircraftModel* parent, CTiglUIDManager* uidMgr) : generated::CPACSFuselages(parent, uidMgr) {} CCPACSFuselages::CCPACSFuselages(CCPACSRotorcraftModel* parent, CTiglUIDManager* uidMgr) : generated::CPACSFuselages(parent, uidMgr) {} // Read CPACS fuselages element void CCPACSFuselages::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) { generated::CPACSFuselages::ReadCPACS(tixiHandle, xpath); } // Write CPACS fuselage elements void CCPACSFuselages::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const { generated::CPACSFuselages::WriteCPACS(tixiHandle, xpath); } // Returns the total count of fuselages in a configuration int CCPACSFuselages::GetFuselageCount() const { return static_cast<int>(m_fuselages.size()); } // Returns the fuselage for a given index. CCPACSFuselage& CCPACSFuselages::GetFuselage(int index) const { index--; if (index < 0 || index >= GetFuselageCount()) { throw CTiglError("Invalid index in CCPACSFuselages::GetFuselage", TIGL_INDEX_ERROR); } return *m_fuselages[index]; } // Returns the fuselage for a given UID. CCPACSFuselage& CCPACSFuselages::GetFuselage(const std::string& UID) const { return *m_fuselages[GetFuselageIndex(UID) - 1]; } // Returns the fuselage index for a given UID. int CCPACSFuselages::GetFuselageIndex(const std::string& UID) const { for (int i=0; i < GetFuselageCount(); i++) { const std::string tmpUID(m_fuselages[i]->GetUID()); if (tmpUID == UID) { return i+1; } } // UID not there throw CTiglError("Invalid UID in CCPACSFuselages::GetFuselageIndex", TIGL_UID_ERROR); } } // end namespace tigl
31.348837
102
0.736647
Mk-arc
84f8acb67141d9256497274918609d9aa1529ad4
7,462
cpp
C++
2019/20.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
2
2020-08-06T22:14:51.000Z
2020-08-10T19:42:36.000Z
2019/20.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
2019/20.cpp
wgevaert/AOC
aaa9c06f9817e338cca01bbf37b6ba81256dd5ba
[ "WTFPL" ]
null
null
null
#include <iostream> #include <vector> #define NORTH 1 #define SOUTH 2 #define WEST 3 #define EAST 4 void get_direction(int command, int& dx, int & dy) { switch(command) { case NORTH: dx=0;dy=1;break; case SOUTH: dx=0;dy=-1;break; case WEST: dx=-1;dy=0;break; case EAST: dx=1;dy=0;break; default:std::cout<<command<<" IS NOT A VALID DIRECTION"<<std::endl; } } struct flower { bool flowing = true,waiting =false; int px,py,size; flower(int pos_x,int pos_y,int sze) {px=pos_x;py=pos_y;flowing=true;size = sze;} flower(){}; }; struct tile { char type,p1,p2; int dist=-1,x,y; }; #define WALL '#' #define PATH '.' #define PORTAL 'p' #define USED 'O' #define NOTHING ' ' int main() { int x=0,x_max=0,y_max=0; int x_start,y_start,x_end,y_end; char a=std::cin.get(); tile robot_pos[300][300]; std::vector<int> lines_with_letters ={0}; std::vector<std::pair<int,int>> portals={}; while (!std::cin.eof()) { if (a!='\n') { if ('A'<=a&&a<='Z') { robot_pos[x][y_max].type = a; if (lines_with_letters.back() != y_max)lines_with_letters.push_back(y_max); } else if (a=='.') { robot_pos[x][y_max].type = a; } else if (a=='#') { robot_pos[x][y_max].type = a; } else if (a!=' ') { std::cout<<"UNEXPECTED CHAR: "<<a<<" (VALUE "<<static_cast<int>(a)<<")\n"<<std::flush; } else robot_pos[x][y_max].type = a; x++; } else { if (x>x_max)x_max = x; y_max++; x=0; } a=std::cin.get(); } std::cout<<--x_max<<' '<<--y_max<<std::endl; for (int j=0;j<=y_max;j++) { for (int i=0;i<=x_max;i++) { std::cout<<robot_pos[i][j].type<<' '; }std::cout<<'\t'<<j<<"\n"; }std::cout<<std::flush; for (int line : lines_with_letters) { for (int i=0;i<=x_max;i++) { if (robot_pos[i][line].type <= 'Z' && 'A' <= robot_pos[i][line].type) { if (line < y_max-3 && robot_pos[i][line+1].type <='Z' && robot_pos[i][line+1].type >='A' && robot_pos[i][line+2].type == PATH) { robot_pos[i][line+2].p1 = robot_pos[i][line].type; robot_pos[i][line+2].p2 = robot_pos[i][line+1].type; portals.push_back({i,line+2}); } else if (x < x_max-2 && robot_pos[i+1][line].type <='Z' && robot_pos[i+1][line].type >='A' && robot_pos[i-1][line].type == PATH) { robot_pos[i-1][line].p1 = robot_pos[i][line].type; robot_pos[i-1][line].p2 = robot_pos[i+1][line].type; portals.push_back({i-1,line}); } else if (x < x_max-3 && robot_pos[i+1][line].type <='Z' && robot_pos[i+1][line].type >='A' && robot_pos[i+2][line].type == PATH) { robot_pos[i+2][line].p1 = robot_pos[i][line].type; robot_pos[i+2][line].p2 = robot_pos[i+1][line].type; portals.push_back({i+2,line}); } else if (line < y_max && robot_pos[i][line+1].type <='Z' && robot_pos[i][line+1].type >='A' && robot_pos[i][line-1].type == PATH) { robot_pos[i][line-1].p1 = robot_pos[i][line].type; robot_pos[i][line-1].p2 = robot_pos[i][line+1].type; portals.push_back({i,line-1}); } robot_pos[i][line].type=NOTHING; } } } lines_with_letters.clear(); int st,ed; for (int i=0;i<portals.size();i++){ if (robot_pos[portals[i].first][portals[i].second].p1 == 'A' && robot_pos[portals[i].first][portals[i].second].p2 == 'A'){ x_start = portals[i].first; y_start = portals[i].second; st = i; } else if(robot_pos[portals[i].first][portals[i].second].p1 == 'Z' && robot_pos[portals[i].first][portals[i].second].p2 == 'Z') { x_end = portals[i].first; y_end = portals[i].second; ed = i; } else for(int j=i+1;j<portals.size();j++) if(robot_pos[portals[i].first][portals[i].second].p1 == robot_pos[portals[j].first][portals[j].second].p1 && robot_pos[portals[i].first][portals[i].second].p2 == robot_pos[portals[j].first][portals[j].second].p2) { std::cout<< "Connecting "<<robot_pos[portals[i].first][portals[i].second].p1<<robot_pos[portals[i].first][portals[i].second].p2<<" on "<<portals[i].first<<','<<portals[i].second<<" to "<<portals[j].first<<','<<portals[j].second<<std::endl; robot_pos[portals[i].first][portals[i].second].x = portals[j].first; robot_pos[portals[i].first][portals[i].second].y = portals[j].second; robot_pos[portals[j].first][portals[j].second].x = portals[i].first; robot_pos[portals[j].first][portals[j].second].y = portals[i].second; robot_pos[portals[i].first][portals[i].second].type = PORTAL; robot_pos[portals[j].first][portals[j].second].type = PORTAL; } } for (int i=0;i<portals.size();i++) { if (i!=st && i!= ed && robot_pos[portals[i].first][portals[i].second].type != PORTAL) { std::cout<<"ERROR: "<<robot_pos[portals[i].first][portals[i].second].p1<<robot_pos[portals[i].first][portals[i].second].p2<<" ON "<< portals[i].first<<','<<portals[i].second<<" IS NOT CONNECTED"<<std::endl; } } std::cout<<"SEARCHING ROUTE FROM "<<x_start<<','<<y_start<<" TO "<<x_end<<','<<y_end<<std::endl; for (int j=0;j<y_max;j++) { for (int i=0;i<x_max;i++) { std::cout<<robot_pos[i][j].type<<' '; }std::cout<<"\n"; }std::cout<<std::flush; flower myflowers[2048]; bool flowed; int flower_cnt=1,px,py,dx,dy; myflowers[0]=flower(x_start,y_start,0); unsigned cnt=0; while (robot_pos[x_end][y_end].type != USED) { int dummy=flower_cnt; for (int flwr=0;flwr<dummy;flwr++) { if (!myflowers[flwr].flowing){ continue; } if (myflowers[flwr].waiting) { myflowers[flwr].waiting = false; myflowers[flwr].size++; } px=myflowers[flwr].px; py=myflowers[flwr].py; flowed = false; for (int i=1;i<=4;i++) { get_direction(i,dx,dy); if (robot_pos[px+dx][py+dy].type==PATH || robot_pos[px+dx][py+dy].type==PORTAL) { int new_x=px+dx,new_y=py+dy; bool should_wait = false; if (robot_pos[new_x][new_y].type==PORTAL) { new_x = robot_pos[px+dx][py+dy].x; new_y = robot_pos[px+dx][py+dy].y; should_wait=true; } if (!flowed) { myflowers[flwr].px = new_x; myflowers[flwr].py = new_y; myflowers[flwr].size++; myflowers[flwr].waiting = should_wait; } else { std::cout<<"SIZE: "<<myflowers[flwr].size; myflowers[flower_cnt]=flower(new_x,new_y,myflowers[flwr].size); std::cout<<','<<myflowers[flower_cnt].size<<std::endl; myflowers[flower_cnt].waiting = should_wait; flower_cnt++; } robot_pos[px+dx][py+dy].type = robot_pos[new_x][new_y].type = USED; robot_pos[px+dx][py+dy].dist = myflowers[flwr].size; flowed = true; } } if (!flowed) { myflowers[flwr].flowing = false; } } std::cout<<"\n\nAFTER "<<cnt+1<<" MINUTES:"<<std::endl; for(int j=0;j<=y_max;j++){ for(int i=0;i<=x_max;i++){ if (i==x_end && j==y_end) std::cout<<'X'; else std::cout<<robot_pos[i][j].type; }std::cout<<std::endl; } ++cnt; } std::cout<<robot_pos[x_end][y_end].dist<<std::endl; return 0; }
38.266667
243
0.552935
wgevaert
84fa61c5233c5531a96f34bc8ca5316b913690c2
13,923
cpp
C++
liblwScript/Ast.cpp
lwScript/lwScript
86f3e991bda2725abe90e13468f58185d8b77483
[ "Apache-2.0" ]
1
2021-11-22T05:28:13.000Z
2021-11-22T05:28:13.000Z
liblwScript/Ast.cpp
lwScript/lwScript
86f3e991bda2725abe90e13468f58185d8b77483
[ "Apache-2.0" ]
null
null
null
liblwScript/Ast.cpp
lwScript/lwScript
86f3e991bda2725abe90e13468f58185d8b77483
[ "Apache-2.0" ]
null
null
null
#include "Ast.h" namespace lws { //----------------------Expressions----------------------------- IntNumExpr::IntNumExpr() : value(0) { } IntNumExpr::IntNumExpr(int64_t value) : value(value) { } IntNumExpr::~IntNumExpr() { } std::wstring IntNumExpr::Stringify() { return std::to_wstring(value); } AstType IntNumExpr::Type() { return AST_INT; } RealNumExpr::RealNumExpr() : value(0.0) { } RealNumExpr::RealNumExpr(double value) : value(value) { } RealNumExpr::~RealNumExpr() { } std::wstring RealNumExpr::Stringify() { return std::to_wstring(value); } AstType RealNumExpr::Type() { return AST_REAL; } StrExpr::StrExpr() { } StrExpr::StrExpr(std::wstring_view str) : value(str) { } StrExpr::~StrExpr() { } std::wstring StrExpr::Stringify() { return L"\"" + value + L"\""; } AstType StrExpr::Type() { return AST_STR; } NullExpr::NullExpr() { } NullExpr::~NullExpr() { } std::wstring NullExpr::Stringify() { return L"null"; } AstType NullExpr::Type() { return AST_NULL; } BoolExpr::BoolExpr() : value(false) { } BoolExpr::BoolExpr(bool value) : value(value) { } BoolExpr::~BoolExpr() { } std::wstring BoolExpr::Stringify() { return value ? L"true" : L"false"; } AstType BoolExpr::Type() { return AST_BOOL; } IdentifierExpr::IdentifierExpr() { } IdentifierExpr::IdentifierExpr(std::wstring_view literal) : literal(literal) { } IdentifierExpr::~IdentifierExpr() { } std::wstring IdentifierExpr::Stringify() { return literal; } AstType IdentifierExpr::Type() { return AST_IDENTIFIER; } ArrayExpr::ArrayExpr() { } ArrayExpr::ArrayExpr(std::vector<Expr *> elements) : elements(elements) { } ArrayExpr::~ArrayExpr() { std::vector<Expr *>().swap(elements); } std::wstring ArrayExpr::Stringify() { std::wstring result = L"["; if (!elements.empty()) { for (auto e : elements) result += e->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L"]"; return result; } AstType ArrayExpr::Type() { return AST_ARRAY; } TableExpr::TableExpr() { } TableExpr::TableExpr(std::unordered_map<Expr *, Expr *> elements) : elements(elements) { } TableExpr::~TableExpr() { std::unordered_map<Expr *, Expr *>().swap(elements); } std::wstring TableExpr::Stringify() { std::wstring result = L"{"; if (!elements.empty()) { for (auto [key, value] : elements) result += key->Stringify() + L":" + value->Stringify(); result = result.substr(0, result.size() - 1); } result += L"}"; return result; } AstType TableExpr::Type() { return AST_TABLE; } GroupExpr::GroupExpr() : expr(nullptr) { } GroupExpr::GroupExpr(Expr *expr) : expr(expr) { } GroupExpr::~GroupExpr() { } std::wstring GroupExpr::Stringify() { return L"(" + expr->Stringify() + L")"; } AstType GroupExpr::Type() { return AST_GROUP; } PrefixExpr::PrefixExpr() : right(nullptr) { } PrefixExpr::PrefixExpr(std::wstring_view op, Expr *right) : op(op), right(right) { } PrefixExpr::~PrefixExpr() { delete right; right = nullptr; } std::wstring PrefixExpr::Stringify() { return op + right->Stringify(); } AstType PrefixExpr::Type() { return AST_PREFIX; } InfixExpr::InfixExpr() : left(nullptr), right(nullptr) { } InfixExpr::InfixExpr(std::wstring_view op, Expr *left, Expr *right) : op(op), left(left), right(right) { } InfixExpr::~InfixExpr() { delete left; left = nullptr; delete right; right = nullptr; } std::wstring InfixExpr::Stringify() { return left->Stringify() + op + right->Stringify(); } AstType InfixExpr::Type() { return AST_INFIX; } PostfixExpr::PostfixExpr() : left(nullptr) { } PostfixExpr::PostfixExpr(Expr *left, std::wstring_view op) : left(left), op(op) { } PostfixExpr::~PostfixExpr() { delete left; left = nullptr; } std::wstring PostfixExpr::Stringify() { return left->Stringify() + op; } AstType PostfixExpr::Type() { return AST_POSTFIX; } ConditionExpr::ConditionExpr() : condition(nullptr), trueBranch(nullptr), falseBranch(nullptr) { } ConditionExpr::ConditionExpr(Expr *condition, Expr *trueBranch, Expr *falseBranch) : condition(condition), trueBranch(trueBranch), falseBranch(falseBranch) { } ConditionExpr::~ConditionExpr() { delete condition; condition = nullptr; delete trueBranch; trueBranch = nullptr; delete falseBranch; trueBranch = nullptr; } std::wstring ConditionExpr::Stringify() { return condition->Stringify() + L"?" + trueBranch->Stringify() + L":" + falseBranch->Stringify(); } AstType ConditionExpr::Type() { return AST_CONDITION; } IndexExpr::IndexExpr() : ds(nullptr), index(nullptr) { } IndexExpr::IndexExpr(Expr *ds, Expr *index) : ds(ds), index(index) { } IndexExpr::~IndexExpr() { delete ds; ds = nullptr; delete index; index = nullptr; } std::wstring IndexExpr::Stringify() { return ds->Stringify() + L"[" + index->Stringify() + L"]"; } AstType IndexExpr::Type() { return AST_INDEX; } RefExpr::RefExpr() : refExpr(nullptr) { } RefExpr::RefExpr(Expr *refExpr) : refExpr(refExpr) {} RefExpr::~RefExpr() { } std::wstring RefExpr::Stringify() { return L"&" + refExpr->Stringify(); } AstType RefExpr::Type() { return AST_REF; } LambdaExpr::LambdaExpr() : body(nullptr) { } LambdaExpr::LambdaExpr(std::vector<IdentifierExpr *> parameters, ScopeStmt *body) : parameters(parameters), body(body) { } LambdaExpr::~LambdaExpr() { std::vector<IdentifierExpr *>().swap(parameters); delete body; body = nullptr; } std::wstring LambdaExpr::Stringify() { std::wstring result = L"fn("; if (!parameters.empty()) { for (auto param : parameters) result += param->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L")"; result += body->Stringify(); return result; } AstType LambdaExpr::Type() { return AST_LAMBDA; } FunctionCallExpr::FunctionCallExpr() { } FunctionCallExpr::FunctionCallExpr(Expr *name, std::vector<Expr *> arguments) : name(name), arguments(arguments) { } FunctionCallExpr::~FunctionCallExpr() { } std::wstring FunctionCallExpr::Stringify() { std::wstring result = name->Stringify() + L"("; if (!arguments.empty()) { for (const auto &arg : arguments) result += arg->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L")"; return result; } AstType FunctionCallExpr::Type() { return AST_FUNCTION_CALL; } ClassCallExpr::ClassCallExpr() : callee(nullptr), callMember(nullptr) { } ClassCallExpr::ClassCallExpr(Expr *callee, Expr *callMember) : callee(callee), callMember(callMember) { } ClassCallExpr::~ClassCallExpr() { } std::wstring ClassCallExpr::Stringify() { return callee->Stringify() + L"." + callMember->Stringify(); } AstType ClassCallExpr::Type() { return AST_CLASS_CALL; } //----------------------Statements----------------------------- ExprStmt::ExprStmt() : expr(nullptr) { } ExprStmt::ExprStmt(Expr *expr) : expr(expr) { } ExprStmt::~ExprStmt() { delete expr; expr = nullptr; } std::wstring ExprStmt::Stringify() { return expr->Stringify() + L";"; } AstType ExprStmt::Type() { return AST_EXPR; } LetStmt::LetStmt() { } LetStmt::LetStmt(const std::unordered_map<IdentifierExpr *, VarDesc> &variables) : variables(variables) { } LetStmt::~LetStmt() { std::unordered_map<IdentifierExpr *, VarDesc>().swap(variables); } std::wstring LetStmt::Stringify() { std::wstring result = L"let "; if (!variables.empty()) { for (auto [key, value] : variables) result += key->Stringify() + L":" + value.type + L"=" + value.value->Stringify() + L","; result = result.substr(0, result.size() - 1); } return result + L";"; } AstType LetStmt::Type() { return AST_LET; } ConstStmt::ConstStmt() { } ConstStmt::ConstStmt(const std::unordered_map<IdentifierExpr *, VarDesc> &consts) : consts(consts) { } ConstStmt::~ConstStmt() { std::unordered_map<IdentifierExpr *, VarDesc>().swap(consts); } std::wstring ConstStmt::Stringify() { std::wstring result = L"const "; if (!consts.empty()) { for (auto [key, value] : consts) result += key->Stringify() + L":" + value.type + L"=" + value.value->Stringify() + L","; result = result.substr(0, result.size() - 1); } return result + L";"; } AstType ConstStmt::Type() { return AST_CONST; } ReturnStmt::ReturnStmt() : expr(nullptr) { } ReturnStmt::ReturnStmt(Expr *expr) : expr(expr) { } ReturnStmt::~ReturnStmt() { delete expr; expr = nullptr; } std::wstring ReturnStmt::Stringify() { if (expr) return L"return " + expr->Stringify() + L";"; else return L"return;"; } AstType ReturnStmt::Type() { return AST_RETURN; } IfStmt::IfStmt() : condition(nullptr), thenBranch(nullptr), elseBranch(nullptr) { } IfStmt::IfStmt(Expr *condition, Stmt *thenBranch, Stmt *elseBranch) : condition(condition), thenBranch(thenBranch), elseBranch(elseBranch) { } IfStmt::~IfStmt() { delete condition; condition = nullptr; delete thenBranch; thenBranch = nullptr; delete elseBranch; elseBranch = nullptr; } std::wstring IfStmt::Stringify() { std::wstring result; result = L"if(" + condition->Stringify() + L")" + thenBranch->Stringify(); if (elseBranch != nullptr) result += L"else " + elseBranch->Stringify(); return result; } AstType IfStmt::Type() { return AST_IF; } ScopeStmt::ScopeStmt() { } ScopeStmt::ScopeStmt(std::vector<Stmt *> stmts) : stmts(stmts) {} ScopeStmt::~ScopeStmt() { std::vector<Stmt *>().swap(stmts); } std::wstring ScopeStmt::Stringify() { std::wstring result = L"{"; for (const auto &stmt : stmts) result += stmt->Stringify(); result += L"}"; return result; } AstType ScopeStmt::Type() { return AST_SCOPE; } WhileStmt::WhileStmt() : condition(nullptr), body(nullptr), increment(nullptr) { } WhileStmt::WhileStmt(Expr *condition, ScopeStmt *body, ScopeStmt *increment) : condition(condition), body(body), increment(increment) { } WhileStmt::~WhileStmt() { delete condition; condition = nullptr; delete body; body = nullptr; delete increment; increment = nullptr; } std::wstring WhileStmt::Stringify() { std::wstring result = L"while(" + condition->Stringify() + L"){" + body->Stringify(); if (increment) result += increment->Stringify(); return result += L"}"; } AstType WhileStmt::Type() { return AST_WHILE; } BreakStmt::BreakStmt() { } BreakStmt::~BreakStmt() { } std::wstring BreakStmt::Stringify() { return L"break;"; } AstType BreakStmt::Type() { return AST_BREAK; } ContinueStmt::ContinueStmt() { } ContinueStmt::~ContinueStmt() { } std::wstring ContinueStmt::Stringify() { return L"continue;"; } AstType ContinueStmt::Type() { return AST_CONTINUE; } EnumStmt::EnumStmt() { } EnumStmt::EnumStmt(IdentifierExpr *enumName, const std::unordered_map<IdentifierExpr *, Expr *> &enumItems) : enumName(enumName), enumItems(enumItems) { } EnumStmt::~EnumStmt() { } std::wstring EnumStmt::Stringify() { std::wstring result = L"enum " + enumName->Stringify() + L"{"; if (!enumItems.empty()) { for (auto [key, value] : enumItems) result += key->Stringify() + L"=" + value->Stringify() + L","; result = result.substr(0, result.size() - 1); } return result + L"}"; } AstType EnumStmt::Type() { return AST_ENUM; } FunctionStmt::FunctionStmt() : name(nullptr), body(nullptr) { } FunctionStmt::FunctionStmt(IdentifierExpr *name, std::vector<IdentifierExpr *> parameters, ScopeStmt *body) : name(name), parameters(parameters), body(body) { } FunctionStmt::~FunctionStmt() { std::vector<IdentifierExpr *>().swap(parameters); delete body; body = nullptr; } std::wstring FunctionStmt::Stringify() { std::wstring result = L"fn " + name->Stringify() + L"("; if (!parameters.empty()) { for (auto param : parameters) result += param->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L")"; result += body->Stringify(); return result; } AstType FunctionStmt::Type() { return AST_FUNCTION; } ClassStmt::ClassStmt() { } ClassStmt::ClassStmt(std::wstring name, std::vector<LetStmt *> letStmts, std::vector<ConstStmt *> constStmts, std::vector<FunctionStmt *> fnStmts, std::vector<IdentifierExpr *> parentClasses) : name(name), letStmts(letStmts), constStmts(constStmts), fnStmts(fnStmts), parentClasses(parentClasses) { } ClassStmt::~ClassStmt() { std::vector<IdentifierExpr *>().swap(parentClasses); std::vector<LetStmt *>().swap(letStmts); std::vector<ConstStmt *>().swap(constStmts); std::vector<FunctionStmt *>().swap(fnStmts); } std::wstring ClassStmt::Stringify() { std::wstring result = L"class " + name; if (!parentClasses.empty()) { result += L":"; for (const auto &parentClass : parentClasses) result += parentClass->Stringify() + L","; result = result.substr(0, result.size() - 1); } result += L"{"; for (auto constStmt : constStmts) result += constStmt->Stringify(); for (auto letStmt : letStmts) result += letStmt->Stringify(); for (auto fnStmt : fnStmts) result += fnStmt->Stringify(); return result + L"}"; } AstType ClassStmt::Type() { return AST_CLASS; } AstStmts::AstStmts() { } AstStmts::AstStmts(std::vector<Stmt *> stmts) : stmts(stmts) {} AstStmts::~AstStmts() { std::vector<Stmt *>().swap(stmts); } std::wstring AstStmts::Stringify() { std::wstring result; for (const auto &stmt : stmts) result += stmt->Stringify(); return result; } AstType AstStmts::Type() { return AST_ASTSTMTS; } }
17.579545
108
0.635352
lwScript
84fb0470375bc6017671736d95673dd7afbf2a31
1,068
cpp
C++
POJ/POJ1723.cpp
dong628/OhMyCodes
238e3045a98505a4880e85ad71d43d64a20f9452
[ "MIT" ]
2
2020-07-18T01:19:04.000Z
2020-11-03T17:34:22.000Z
POJ/POJ1723.cpp
dong628/OhMyCodes
238e3045a98505a4880e85ad71d43d64a20f9452
[ "MIT" ]
null
null
null
POJ/POJ1723.cpp
dong628/OhMyCodes
238e3045a98505a4880e85ad71d43d64a20f9452
[ "MIT" ]
1
2021-09-09T12:52:58.000Z
2021-09-09T12:52:58.000Z
#include <cstdio> #include <iostream> #include <algorithm> const int Max=105; int col[3*Max], zws, n, ans; struct Node { int x, y; } p[Max]; bool cmp0(Node x, Node y) { return x.y < y.y; } bool cmp1(Node x, Node y) { return x.x < y.x; } inline int abs(int x) { return x>0?x:-x; } int main(){ freopen("data.in", "r", stdin); scanf("%d", &n); for(int i=0; i<n; i++){ scanf("%d %d", &p[i].x, &p[i].y); col[p[i].x+Max]++; // xmax = p[i].x>xmax?p[i].x:xmax; // xmin = p[i].x<xmin?p[i].x:xmin; } std::sort(p, p+n, cmp0); zws=p[n>>1].y; for(int i=0; i<n; i++){ ans+=abs(p[i].y-zws); } std::sort(p, p+n, cmp1); zws=p[n>>1].x+Max; for(int i=0; i<n/2; i++){ if(col[zws+i]>1){ for(int j=zws+i+1; j<=zws+i+1+n; j++){ if(col[j]==0){ col[j]++; col[zws+i]--; ans+=j-(zws+i); } if(col[zws+i]==1) break; } } if(col[zws-i]>1){ for(int j=zws-i-1; j>=zws-i-1-n; j--){ if(col[j]==0){ col[j]++; col[zws-i]--; ans+=zws-i-j; } if(col[zws+i]==1) break; } } } printf("%d", ans); return 0; }
18.413793
47
0.484082
dong628
ebcc816ccfca1e227e3c1745a7c02ddd4ef27ca9
7,718
cpp
C++
extra_src/json2array_jacek.cpp
anujaprojects1/shinglejs
fd2052afcd6f3b0e83df6634aa8dcf997aee4e6b
[ "ECL-2.0", "Apache-2.0" ]
30
2017-07-19T12:35:41.000Z
2020-04-19T07:55:20.000Z
extra_src/json2array_jacek.cpp
anujaprojects1/shinglejs
fd2052afcd6f3b0e83df6634aa8dcf997aee4e6b
[ "ECL-2.0", "Apache-2.0" ]
3
2018-08-12T09:01:47.000Z
2018-08-15T13:48:31.000Z
extra_src/json2array_jacek.cpp
anujaprojects1/shinglejs
fd2052afcd6f3b0e83df6634aa8dcf997aee4e6b
[ "ECL-2.0", "Apache-2.0" ]
2
2018-08-11T16:06:33.000Z
2020-01-12T15:25:34.000Z
#include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "graph.h" #include "MFRUtils.h" #include "jsontokenizer.h" #include <set> #include <map> #include <string> /************************************************ Started 2016 Ayal Pinkus Read in json arrays and dump as binary files for faster processing later on. ************************************************/ struct EdgeIds { EdgeIds(long long nodeIdA, long long nodeIdB) { if (nodeIdA < nodeIdB) { low = nodeIdA; high = nodeIdB; } else { low = nodeIdB; high = nodeIdA; } }; EdgeIds(const EdgeIds& other) { low=other.low; high=other.high; }; long long low; long long high; }; bool operator< (const EdgeIds& lhs, const EdgeIds& rhs) { if (lhs.high < rhs.high) { return true; } else if (lhs.high > rhs.high) { return false; } else { if (lhs.low < rhs.low) { return true; } else { return false; } } } std::set<EdgeIds> edgeids; static FILE* json_in_file = NULL; static FILE* node_out_file = NULL; static FILE* edge_out_file = NULL; static void processFile(const char* fname) { JSONTokenizer tokenizer(fname); // // Read nodes // tokenizer.Match("{"); tokenizer.Match("nodes"); tokenizer.Match(":"); tokenizer.Match("["); while (!strcmp(tokenizer.nextToken, "{")) { MFRNode node; tokenizer.Match("{"); while (strcmp(tokenizer.nextToken, "}")) { if (!strcasecmp(tokenizer.nextToken, "eid")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.SetNodeId(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "name")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.SetName(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "author_name")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.SetName(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "x")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.x = atof(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "y")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.y = atof(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "community")) { tokenizer.LookAhead(); tokenizer.Match(":"); node.community = atol(tokenizer.nextToken); } else { tokenizer.LookAhead(); tokenizer.Match(":"); } tokenizer.LookAhead(); if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("}"); fwrite(&node,sizeof(MFRNode),1,node_out_file); { static int nodecount=0; if ((nodecount & 1023) == 0) { fprintf(stderr,"\rNode %d",nodecount); } nodecount++; } if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("]"); tokenizer.Match(","); tokenizer.Match("edges"); tokenizer.Match(":"); tokenizer.Match("["); while (!strcmp(tokenizer.nextToken, "[")) { MFREdgeExt edge; tokenizer.Match("["); edge.SetNodeIdA(tokenizer.nextToken); tokenizer.LookAhead(); tokenizer.Match(","); edge.SetNodeIdB(tokenizer.nextToken); tokenizer.LookAhead(); // Read edge strength here. tokenizer.Match(","); // Bug in data: some fields were left empty, so assuming edge strength 1 here. if (!strcmp(tokenizer.nextToken, ",")) { edge.strength = 1; } else { edge.strength = atoi(tokenizer.nextToken); tokenizer.LookAhead(); } /* Skip any additional fields */ while (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); tokenizer.LookAhead(); } tokenizer.Match("]"); if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } EdgeIds thisedge(atoll(edge.nodeidA), atoll(edge.nodeidB)); std::set<EdgeIds>::iterator eentry = edgeids.find(thisedge); if (eentry == edgeids.end()) { edgeids.insert(thisedge); fwrite(&edge,sizeof(MFREdgeExt),1,edge_out_file); { static int edgecount=0; if ((edgecount & 1023) == 0) { fprintf(stderr, "\rEdge %d",edgecount); } edgecount++; } } } tokenizer.Match("]"); tokenizer.Match("}"); } static void processMetaNodeFile(MFRNodeArray& nodes, const char* fname) { JSONTokenizer tokenizer(fname); tokenizer.Match("{"); tokenizer.Match("nodes"); tokenizer.Match(":"); tokenizer.Match("["); while (!strcmp(tokenizer.nextToken, "{")) { char nodeid[256]; int hindex=0; double pagerank; int pagerank_set = 0; int asjc=0; tokenizer.Match("{"); while (strcmp(tokenizer.nextToken, "}")) { if (!strcasecmp(tokenizer.nextToken, "eid")) { pagerank_set = 0; pagerank=0; hindex=0; asjc=10; tokenizer.LookAhead(); tokenizer.Match(":"); strcpy(nodeid,tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "hindex")) { tokenizer.LookAhead(); tokenizer.Match(":"); hindex = atoi(tokenizer.nextToken); } else if (!strcasecmp(tokenizer.nextToken, "pagerank")) { tokenizer.LookAhead(); tokenizer.Match(":"); pagerank = atof(tokenizer.nextToken); pagerank_set = 1; } else if (!strcasecmp(tokenizer.nextToken, "asjc")) { tokenizer.LookAhead(); tokenizer.Match(":"); char* ptr = tokenizer.nextToken; int len = strlen(ptr); if (len>2 && *ptr == '\"') { ptr[len-1] = 0; ptr = ptr + 1; } asjc = atoi(ptr); } else { tokenizer.LookAhead(); tokenizer.Match(":"); } tokenizer.LookAhead(); if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("}"); MFRNode* node = nodes.LookUp(nodeid); if (node == NULL) { fprintf(stderr,"WARNING: meta data for non-existing node with id %s.\n", nodeid); } else { // I don't want to have to handle -1 in shingle.js. asjc 1000 is "general" if (asjc<0) { asjc = 10; } node->size = hindex; node->level = hindex; if (pagerank_set) { node->level = pagerank; } node->community = asjc; } if (!strcmp(tokenizer.nextToken, ",")) { tokenizer.Match(","); } } tokenizer.Match("]"); tokenizer.Match("}"); } int main(int argc, char** argv) { printf("sizeof(long long)=%lud\n",sizeof(long long)); if (argc<4) { fprintf(stderr,"%s data_path node_out_file edge_out_file",argv[0]); exit(-1); } const char* data_path = argv[1]; const char* node_out_fname = argv[2]; const char* edge_out_fname = argv[3]; node_out_file = MFRUtils::OpenFile(node_out_fname,"w"); edge_out_file = MFRUtils::OpenFile(edge_out_fname,"w"); char json_in_fname[1024]; sprintf(json_in_fname,"%snode.json",data_path); processFile(json_in_fname); fclose(node_out_file); fclose(edge_out_file); MFRNodeArray nodes(node_out_fname); nodes.Sort(); char json_meta_in_fname[1024]; sprintf(json_meta_in_fname,"%smeta.json",data_path); processMetaNodeFile(nodes, json_meta_in_fname); node_out_file = MFRUtils::OpenFile(node_out_fname,"w"); fwrite(nodes.nodes,nodes.nrnodes*sizeof(MFRNode),1,node_out_file); fclose(node_out_file); return 0; }
20.310526
87
0.575667
anujaprojects1
ebcdd79ecfcdaf4a82b7fa9d326a793522aa886d
4,853
cpp
C++
tests/SurfaceMeshIOTest.cpp
choyfung/pmp-library
4a72c918494dac92f5e77545b71c7a327dafe71e
[ "BSD-3-Clause" ]
1
2020-05-21T04:15:44.000Z
2020-05-21T04:15:44.000Z
tests/SurfaceMeshIOTest.cpp
choyfung/pmp-library
4a72c918494dac92f5e77545b71c7a327dafe71e
[ "BSD-3-Clause" ]
null
null
null
tests/SurfaceMeshIOTest.cpp
choyfung/pmp-library
4a72c918494dac92f5e77545b71c7a327dafe71e
[ "BSD-3-Clause" ]
1
2020-05-21T04:15:52.000Z
2020-05-21T04:15:52.000Z
//============================================================================= // Copyright (C) 2011-2018 The pmp-library developers // 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 "SurfaceMeshTest.h" #include <pmp/io/SurfaceMeshIO.h> #include <pmp/algorithms/SurfaceNormals.h> #include <vector> using namespace pmp; class SurfaceMeshIOTest : public SurfaceMeshTest { }; TEST_F(SurfaceMeshIOTest, polyIO) { addTriangle(); mesh.write("test.pmp"); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.pmp"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); // check malformed file names EXPECT_FALSE(mesh.write("testpolyly")); } TEST_F(SurfaceMeshIOTest, objIO) { addTriangle(); SurfaceNormals::computeVertexNormals(mesh); mesh.addHalfedgeProperty<TextureCoordinate>("h:texcoord",TextureCoordinate(0,0)); mesh.write("test.obj"); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.obj"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, offIO) { addTriangle(); SurfaceNormals::computeVertexNormals(mesh); mesh.addVertexProperty<TextureCoordinate>("v:texcoord",TextureCoordinate(0,0)); mesh.addVertexProperty<Color>("v:color",Color(0,0,0)); IOOptions options(false, // binary true, // normals true, // colors true); // texcoords mesh.write("test.off",options); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.off"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, offIOBinary) { addTriangle(); IOOptions options(true); mesh.write("binary.off", options); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("binary.off"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, stlIO) { mesh.read("pmp-data/stl/icosahedron_ascii.stl"); EXPECT_EQ(mesh.nVertices(), size_t(12)); EXPECT_EQ(mesh.nFaces(), size_t(20)); EXPECT_EQ(mesh.nEdges(), size_t(30)); mesh.clear(); mesh.read("pmp-data/stl/icosahedron_binary.stl"); EXPECT_EQ(mesh.nVertices(), size_t(12)); EXPECT_EQ(mesh.nFaces(), size_t(20)); EXPECT_EQ(mesh.nEdges(), size_t(30)); // try to write without normals being present EXPECT_FALSE(mesh.write("test.stl")); // the same with normals computed SurfaceNormals::computeFaceNormals(mesh); EXPECT_TRUE(mesh.write("test.stl")); // try to write non-triangle mesh mesh.clear(); addQuad(); EXPECT_FALSE(mesh.write("test.stl")); } TEST_F(SurfaceMeshIOTest, plyIO) { addTriangle(); mesh.write("test.ply"); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("test.ply"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); } TEST_F(SurfaceMeshIOTest, plyBinaryIO) { addTriangle(); IOOptions options(true); mesh.write("binary.ply",options); mesh.clear(); EXPECT_TRUE(mesh.isEmpty()); mesh.read("binary.ply"); EXPECT_EQ(mesh.nVertices(), size_t(3)); EXPECT_EQ(mesh.nFaces(), size_t(1)); }
33.239726
85
0.673604
choyfung
ebd3cb4b469c4b5d7736d9336083f25d368351e9
1,113
cc
C++
cc/py.cc
acorg/acmacs-py
e0bf6ff7ecfe7332980d15b50f9b6dd6f6f78de1
[ "MIT" ]
null
null
null
cc/py.cc
acorg/acmacs-py
e0bf6ff7ecfe7332980d15b50f9b6dd6f6f78de1
[ "MIT" ]
null
null
null
cc/py.cc
acorg/acmacs-py
e0bf6ff7ecfe7332980d15b50f9b6dd6f6f78de1
[ "MIT" ]
null
null
null
#include "acmacs-base/log.hh" #include "acmacs-py/py.hh" // ====================================================================== PYBIND11_MODULE(acmacs, mdl) { using namespace pybind11::literals; mdl.doc() = "Acmacs backend"; acmacs_py::chart(mdl); acmacs_py::chart_util(mdl); acmacs_py::avidity(mdl); acmacs_py::antigen(mdl); acmacs_py::titers(mdl); acmacs_py::DEPRECATED::antigen_indexes(mdl); acmacs_py::common(mdl); acmacs_py::merge(mdl); acmacs_py::mapi(mdl); acmacs_py::draw(mdl); acmacs_py::seqdb(mdl); acmacs_py::tal(mdl); // ---------------------------------------------------------------------- mdl.def( "enable_logging", // [](const std::string& keys) { acmacs::log::enable(std::string_view{keys}); }, // "keys"_a); mdl.def("logging_enabled", &acmacs::log::report_enabled); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
30.081081
88
0.4708
acorg
ebd7c9f5749615605bb85f9e6c95a39787740773
1,258
cpp
C++
main.cpp
jleben/protobuf-spec-comparator
9599c32d0b6d5a92c30fd9251c77aad9d6472a07
[ "MIT" ]
null
null
null
main.cpp
jleben/protobuf-spec-comparator
9599c32d0b6d5a92c30fd9251c77aad9d6472a07
[ "MIT" ]
null
null
null
main.cpp
jleben/protobuf-spec-comparator
9599c32d0b6d5a92c30fd9251c77aad9d6472a07
[ "MIT" ]
1
2021-09-17T07:22:26.000Z
2021-09-17T07:22:26.000Z
#include "comparison.h" #include <iostream> using namespace std; int main(int argc, char * argv[]) { if (argc < 6) { cerr << "Expected arguments: root-dir1 file1 root-dir2 file2 type [--binary]" << endl; cerr << "Use '.' for <type> to compare all messages and enums in given files." << endl; return 1; } Comparison::Options options; if (argc > 6) { for (int i = 6; i < argc; ++i) { string arg = argv[i]; if (arg == "--binary") { options.binary = true; } else { cerr << "Unknown option: " << arg << endl; return 1; } } } Comparison comparison(options); try { Source source1(argv[2], argv[1]); Source source2(argv[4], argv[3]); string message_name = argv[5]; if (message_name == ".") comparison.compare(source1, source2); else comparison.compare(source1, message_name, source2, message_name); } catch(std::exception & e) { cerr << e.what() << endl; return 1; } comparison.root.trim(); comparison.root.print(); return 0; }
21.322034
95
0.486486
jleben
ebd7d759c1ea2c2cc32f0d535d027c43f0b252ac
630
cc
C++
05_String/Json/Main.cc
pataya235/UdemyCpp_Template-main
46583e2d252005eaba3a8a6f04b112454722e315
[ "MIT" ]
null
null
null
05_String/Json/Main.cc
pataya235/UdemyCpp_Template-main
46583e2d252005eaba3a8a6f04b112454722e315
[ "MIT" ]
null
null
null
05_String/Json/Main.cc
pataya235/UdemyCpp_Template-main
46583e2d252005eaba3a8a6f04b112454722e315
[ "MIT" ]
null
null
null
#include "json.hpp" #include <fstream> #include <iostream> int main() { std::ifstream ifs("c_cpp_properties.json"); //input filestream to read nlohmann::json data; //json object ifs >> data; //.json file into data object std::cout << data["configurations"][0]["compilerPath"] << std::endl; std::cout << data["configurations"][0]["intelliSenseMode"] << std::endl; data["configurations"][0]["cppStandard"] = "c++11"; std::ofstream ofs("c_cpp_properties_edited.json"); //output filestream to write ofs << std::setw(4) << data; return 0; }
31.5
83
0.592063
pataya235
ebdcd9a0c15ccfd734063547817eab73805518ba
556
cpp
C++
async_error_handling.cpp
pgulotta/FunctionalCpp
e8a1a1af87c17050e49e129b08b68ce22ecf39ae
[ "MIT" ]
1
2020-04-28T17:40:27.000Z
2020-04-28T17:40:27.000Z
async_error_handling.cpp
pgulotta/FunctionalCpp
e8a1a1af87c17050e49e129b08b68ce22ecf39ae
[ "MIT" ]
null
null
null
async_error_handling.cpp
pgulotta/FunctionalCpp
e8a1a1af87c17050e49e129b08b68ce22ecf39ae
[ "MIT" ]
null
null
null
#include <iostream> #include <future> #include <exception> #include <stdexcept> using namespace std; int calculate() { throw runtime_error("Exception thrown from calculate()."); } int main() { // Use the launch::async policy to force asynchronous execution. auto myFuture = async(launch::async, calculate); // Do some more work... // Get the result. try { int result = myFuture.get(); cout << result << endl; } catch (const exception& ex) { cout << "Caught exception: " << ex.what() << endl; } return 0; }
18.533333
66
0.629496
pgulotta
ebdd6396f7658fccd5956c7a1219d5aa05f22d93
848
cpp
C++
src/ecs/Complex.cpp
murataka/two
f6f9835de844a38687e11f649ff97c3fb4146bbe
[ "Zlib" ]
578
2019-05-04T09:09:42.000Z
2022-03-27T23:02:21.000Z
src/ecs/Complex.cpp
murataka/two
f6f9835de844a38687e11f649ff97c3fb4146bbe
[ "Zlib" ]
14
2019-05-11T14:34:56.000Z
2021-02-02T07:06:46.000Z
src/ecs/Complex.cpp
murataka/two
f6f9835de844a38687e11f649ff97c3fb4146bbe
[ "Zlib" ]
42
2019-05-11T16:04:19.000Z
2022-01-24T02:21:43.000Z
// Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifdef TWO_MODULES module; #include <infra/Cpp20.h> module TWO(ecs); #else #include <type/Indexer.h> #include <type/Proto.h> #include <ecs/Complex.h> #endif namespace two { Complex::Complex(uint32_t id, Type& type) : m_id(index(type, id, Ref(this, type))) , m_type(type) , m_prototype(proto(type)) , m_parts(m_prototype.m_parts.size()) {} Complex::Complex(uint32_t id, Type& type, span<Ref> parts) : Complex(id, type) { this->setup(parts); } Complex::~Complex() { unindex(m_type, m_id); } void Complex::setup(span<Ref> parts) { for(Ref ref : parts) this->add_part(ref); } }
20.682927
91
0.688679
murataka
ebdda3f79a83aeca6739c5a05e0d93e71a216f05
1,035
cpp
C++
Dimensionality_Reduction/AE1d/src/loss.cpp
o8r/pytorch_cpp
70ba1e64270da6d870847c074ce33afb154f1ef8
[ "MIT" ]
181
2020-03-26T12:33:25.000Z
2022-03-28T04:04:25.000Z
Dimensionality_Reduction/AE1d/src/loss.cpp
o8r/pytorch_cpp
70ba1e64270da6d870847c074ce33afb154f1ef8
[ "MIT" ]
11
2020-07-26T13:18:50.000Z
2022-01-09T10:04:10.000Z
Dimensionality_Reduction/AE1d/src/loss.cpp
o8r/pytorch_cpp
70ba1e64270da6d870847c074ce33afb154f1ef8
[ "MIT" ]
38
2020-05-04T05:06:55.000Z
2022-03-29T19:10:51.000Z
#include <iostream> #include <string> // For External Library #include <torch/torch.h> // For Original Header #include "loss.hpp" #include "losses.hpp" // ----------------------------------- // class{Loss} -> constructor // ----------------------------------- Loss::Loss(const std::string loss){ if (loss == "l1"){ this->judge = 0; } else if (loss == "l2"){ this->judge = 1; } else{ std::cerr << "Error : The loss fuction isn't defined right." << std::endl; std::exit(1); } } // ----------------------------------- // class{Loss} -> operator // ----------------------------------- torch::Tensor Loss::operator()(torch::Tensor &input, torch::Tensor &target){ if (this->judge == 0){ static auto criterion = torch::nn::L1Loss(torch::nn::L1LossOptions().reduction(torch::kMean)); return criterion(input, target); } static auto criterion = torch::nn::MSELoss(torch::nn::MSELossOptions().reduction(torch::kMean)); return criterion(input, target); }
27.236842
102
0.520773
o8r
ebdfe31f9d93f6792305dd8137a3dd82eb496e68
1,721
cpp
C++
Vic2ToHoI4/Source/HOI4World/Ideas/Ideas.cpp
kingofmen/Vic2ToHoI4
04e3b872f84cf8aa56e44a63021fe66db1cfe233
[ "MIT" ]
1
2020-12-19T07:55:43.000Z
2020-12-19T07:55:43.000Z
Vic2ToHoI4/Source/HOI4World/Ideas/Ideas.cpp
kingofmen/Vic2ToHoI4
04e3b872f84cf8aa56e44a63021fe66db1cfe233
[ "MIT" ]
null
null
null
Vic2ToHoI4/Source/HOI4World/Ideas/Ideas.cpp
kingofmen/Vic2ToHoI4
04e3b872f84cf8aa56e44a63021fe66db1cfe233
[ "MIT" ]
null
null
null
#include "Ideas.h" #include "IdeaGroup.h" #include "IdeaUpdaters.h" #include "Log.h" #include "ParserHelpers.h" #include <fstream> HoI4::Ideas::Ideas() noexcept { importIdeologicalIdeas(); importGeneralIdeas(); } void HoI4::Ideas::importIdeologicalIdeas() { registerRegex(commonItems::catchallRegex, [this](const std::string& ideology, std::istream& theStream) { ideologicalIdeas.insert(make_pair(ideology, IdeaGroup(ideology, theStream))); }); parseFile("ideologicalIdeas.txt"); clearRegisteredKeywords(); } void HoI4::Ideas::importGeneralIdeas() { registerRegex(commonItems::catchallRegex, [this](const std::string& ideaGroupName, std::istream& theStream) { generalIdeas.emplace_back(IdeaGroup{ideaGroupName, theStream}); }); parseFile("converterIdeas.txt"); clearRegisteredKeywords(); } void HoI4::Ideas::updateIdeas(const std::set<std::string>& majorIdeologies) { Log(LogLevel::Info) << "\tUpdating ideas"; auto foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) { return (theGroup.getName() == "mobilization_laws"); }); updateMobilizationLaws(*foundGroup, majorIdeologies); foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) { return (theGroup.getName() == "economy"); }); updateEconomyIdeas(*foundGroup, majorIdeologies); foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) { return (theGroup.getName() == "trade_laws"); }); updateTradeLaws(*foundGroup, majorIdeologies); foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) { return (theGroup.getName() == "country"); }); updateGeneralIdeas(*foundGroup, majorIdeologies); }
27.758065
110
0.731551
kingofmen
ebe3e93682ad299f8ed7386b049f861e2e313e7d
436
cpp
C++
solved/c-e/clockhands/clock.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/c-e/clockhands/clock.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/c-e/clockhands/clock.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <algorithm> #include <cstdio> using namespace std; int H, M; double a, b; // angles for the two hands int main() { while (true) { scanf("%d:%d", &H, &M); if (H == 0 && M == 0) break; a = H*30 + 1.0*M/2.0; b = M*6; double x = a - b; double y = b - a; if (x < 0) x += 360; if (y < 0) y += 360; printf("%.3lf\n", min(x, y)); } return 0; }
16.148148
41
0.419725
abuasifkhan
ebe57cecc324b43eec1fdab43ab14ec9347ea301
5,050
cpp
C++
libs/dev/PCSTree/PA1/PCSTree.cpp
Norseman055/immaterial-engine
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
[ "MIT" ]
null
null
null
libs/dev/PCSTree/PA1/PCSTree.cpp
Norseman055/immaterial-engine
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
[ "MIT" ]
null
null
null
libs/dev/PCSTree/PA1/PCSTree.cpp
Norseman055/immaterial-engine
6aca0fad64f5b2b9fe6eb351528a79a39dc94625
[ "MIT" ]
null
null
null
#include <stdio.h> #include <assert.h> #include <string.h> #include "PCSTree.h" #include "PCSNode.h" // constructor PCSTree::PCSTree() { info.maxLevelCount = 0; info.maxNodeCount = 0; info.numLevels = 0; info.numNodes = 0; root = NULL; }; // destructor PCSTree::~PCSTree() { // printf("PCSTree: destructor()\n"); }; // get Root PCSNode *PCSTree::getRoot( void ) const { return (PCSNode *)root; } // insert void PCSTree::insert(PCSNode *inNode, PCSNode *parent) { if (this->getRoot() != 0) // if tree has a root already { inNode->setParent(parent); // set node's parent to specified parent. inNode->setLevel((inNode->getParent()->getLevel()) + 1); if (parent->getChild() != 0) // if parent node has children, add it as first sibling on list. { // store first sibling as tmp, add node as parent's child, adjust sibling list PCSNode *tmp = parent->getChild(); parent->setChild(inNode); inNode->setSibling(tmp); } else // if that parent node has no children, make it a child. { parent->setChild(inNode); // set parents node child to inNode } } else // tree has no root. it is now the root. forget your parent specifier. { root = inNode; // make root the first node inNode->setParent(NULL); // set the node's parent to null. its now the root. inNode->setLevel(1); } checkLevels(inNode); info.maxNodeCount++; info.numNodes++; } // Remove // super easy process. just remove its link from the parent and make sure siblings to left link to the right void PCSTree::remove(PCSNode * const inNode) { // make sure inNode is NOT the root. if it is the root, just zero out all its stats. if (inNode != root) { // check to see if inNode is NOT the only child. if (inNode->getParent()->getChild() != inNode || inNode->getSibling()) { // first case, its a "first child". set the parent's first child to the next child in line. if (inNode->getParent()->getChild() == inNode) { inNode->getParent()->setChild( inNode->getSibling() ); } // second case, its the "middle" or "youngest". find previous sibling point. else { PCSNode *tmp = inNode->getParent()->getChild(); // create temp node to find previous child while (tmp->getSibling() != inNode) tmp = tmp->getSibling(); // move temp node to position right before child // youngest if (inNode->getSibling() == NULL) tmp->setSibling(NULL); // set final sibling to null // middle else tmp->setSibling(inNode->getSibling()); // link inNode's previous sibling to its next sibling. } } // inNode is only child. just tell parent that it has no children. else inNode->getParent()->setChild(NULL); } else root = NULL; // set everything derived from inNode (children and their siblings, etc) to 0 if (inNode->getChild()) removeDown(inNode->getChild()); // clean up inNode links to 0 inNode->setChild(NULL); inNode->setParent(NULL); inNode->setSibling(NULL); // update info info.numNodes--; } // get tree info void PCSTree::getInfo( PCSTreeInfo &infoContainer ) { info.numLevels = 0; PCSNode *travelTree = root; if (travelTree != NULL) // if it isn't a null pointer, check the depth of the tree. { goDown(travelTree); } infoContainer.maxLevelCount = info.maxLevelCount; infoContainer.maxNodeCount = info.maxNodeCount; infoContainer.numLevels = info.numLevels; infoContainer.numNodes = info.numNodes; } void PCSTree::dumpTree( ) const { if (root) { printf("\ndumpTree() ----------------"); root->printDown(root); } } // this function is called just once to check the levels with getInfo(). void PCSTree::goDown( const PCSNode* const _root ) { if (_root->getChild() != NULL) // if root has a child, go down again. { goDown(_root->getChild()); } checkLevels(_root); // check levels for that tree if (_root->getSibling() != NULL) // now traverse siblings. { goDown(_root->getSibling()); } } // this deletes all children below a specified original root. basically the same as goDown, but calls remove function. // at its final iteration, it is always at the final sibling, so it zeroes everything out. void PCSTree::removeDown( PCSNode * const _root ) { if (_root->getChild() != NULL) // if root has a child, go down again. { removeDown(_root->getChild()); } if (_root->getSibling() != NULL) // now traverse siblings. { removeDown(_root->getSibling()); } // zero out current node _root->setChild(NULL); _root->setParent(NULL); _root->setSibling(NULL); // update info info.numNodes--; } // this is a function that just checks the number of levels away from the root any given node is. void PCSTree::checkLevels( const PCSNode * const inNode ) { if (inNode->getLevel() > info.maxLevelCount) // if current level is greater than max, increase max info.maxLevelCount = inNode->getLevel(); if (inNode->getLevel() > info.numLevels) // if current level is greater than recorded levels, increase recorded levels info.numLevels = inNode->getLevel(); }
26.302083
121
0.671683
Norseman055
ebe7b4999a1de061dfec998206e07727d0ea13c1
282
hpp
C++
src_ordenacao_imperador_algoritmo2/include/Bubble.hpp
victormagalhaess/TP2-ED-2020
78d020c6da1c036fd6643d6ed066f3440a45a981
[ "MIT" ]
null
null
null
src_ordenacao_imperador_algoritmo2/include/Bubble.hpp
victormagalhaess/TP2-ED-2020
78d020c6da1c036fd6643d6ed066f3440a45a981
[ "MIT" ]
null
null
null
src_ordenacao_imperador_algoritmo2/include/Bubble.hpp
victormagalhaess/TP2-ED-2020
78d020c6da1c036fd6643d6ed066f3440a45a981
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include "./Civilization.hpp" #ifndef BUBBLE #define BUBBLE namespace Emperor2 { class Bubble { public: Civilization *BubbleSort(Civilization *civilizations, int numberOfCivilizations); }; } // namespace Emperor2 #endif
20.142857
89
0.712766
victormagalhaess
ebea36374ee8bf322642b91d60d644b4f780b60f
2,255
hpp
C++
src/sosofo.hpp
hvellyr/sairy
3b7b797c71384222d58b67bded24ee5b5cc6aa2a
[ "BSD-3-Clause" ]
null
null
null
src/sosofo.hpp
hvellyr/sairy
3b7b797c71384222d58b67bded24ee5b5cc6aa2a
[ "BSD-3-Clause" ]
null
null
null
src/sosofo.hpp
hvellyr/sairy
3b7b797c71384222d58b67bded24ee5b5cc6aa2a
[ "BSD-3-Clause" ]
1
2018-01-29T10:57:09.000Z
2018-01-29T10:57:09.000Z
// Copyright (c) 2015 Gregor Klinke // All rights reserved. #pragma once #include "fo.hpp" #include <iterator> #include <memory> #include <string> #include <vector> namespace eyestep { class SosofoIterator; class Sosofo { public: /*! Creates an empty sosofo */ Sosofo(); Sosofo(const Sosofo& one, const Sosofo& two); Sosofo(const std::vector<Sosofo>& sosofos); /*! Creates a sosofo with exactly one formatting object */ Sosofo(std::shared_ptr<IFormattingObject> fo); Sosofo(const std::string& label, std::shared_ptr<IFormattingObject> fo); /*! Returns a new sosofo with all FOs from @p other appended */ Sosofo concat(const Sosofo& other) const; void set_label(const std::string& lbl) { _label = lbl; } const std::string& label() const { return _label; } bool empty() const { return _fos.empty(); } int length() const { return int(_fos.size()); } const IFormattingObject* operator[](size_t idx) const { return _fos[idx].get(); } SosofoIterator begin() const; SosofoIterator end() const; private: std::string _label; std::vector<std::shared_ptr<IFormattingObject>> _fos; }; class SosofoIterator { const Sosofo* _sosofo = nullptr; int _idx = 0; public: using iterator_category = std::forward_iterator_tag; using value_type = const IFormattingObject; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; /*! the end iterator */ SosofoIterator() = default; SosofoIterator(const Sosofo* sosofo, int idx) : _sosofo(sosofo) , _idx(idx) { if (_idx < 0 || _idx >= _sosofo->length()) { *this = {}; } } SosofoIterator& operator++() { ++_idx; if (_idx >= _sosofo->length()) { *this = {}; } return *this; } SosofoIterator operator++(int) { SosofoIterator retval = *this; ++(*this); return retval; } bool operator==(SosofoIterator other) const { return _sosofo == other._sosofo && _idx == other._idx; } bool operator!=(SosofoIterator other) const { return !(*this == other); } reference operator*() const { return *(*_sosofo)[_idx]; } pointer operator->() const { return (*_sosofo)[_idx]; } }; } // ns eyestep
19.273504
74
0.647007
hvellyr
ebefb9f00c972446b26434541bac080107dde993
7,796
cpp
C++
source/games/sw/src/mclip.cpp
alexey-lysiuk/Raze
690994ea1e6b105d4fc55d6b81ffda5e26e68c36
[ "RSA-MD" ]
null
null
null
source/games/sw/src/mclip.cpp
alexey-lysiuk/Raze
690994ea1e6b105d4fc55d6b81ffda5e26e68c36
[ "RSA-MD" ]
null
null
null
source/games/sw/src/mclip.cpp
alexey-lysiuk/Raze
690994ea1e6b105d4fc55d6b81ffda5e26e68c36
[ "RSA-MD" ]
null
null
null
//------------------------------------------------------------------------- /* Copyright (C) 1997, 2005 - 3D Realms Entertainment This file is part of Shadow Warrior version 1.2 Shadow Warrior 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. Original Source: 1997 - Frank Maddin and Jim Norwood Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms */ //------------------------------------------------------------------------- #include "ns.h" #include "build.h" #include "mytypes.h" #include "names2.h" #include "panel.h" #include "game.h" #include "tags.h" #include "player.h" #include "mclip.h" BEGIN_SW_NS int MultiClipMove(PLAYERp pp, int z, int floor_dist) { int i; vec3_t opos[MAX_CLIPBOX], pos[MAX_CLIPBOX]; SECTOR_OBJECTp sop = pp->sop; short ang; short min_ndx = 0; int min_dist = 999999; int dist; int ret_start; int ret; int min_ret=0; int xvect,yvect; for (i = 0; i < sop->clipbox_num; i++) { // move the box to position instead of using offset- this prevents small rounding errors // allowing you to move through wall ang = NORM_ANGLE(pp->angle.ang.asbuild() + sop->clipbox_ang[i]); vec3_t spos = { pp->posx, pp->posy, z }; xvect = sop->clipbox_vdist[i] * bcos(ang); yvect = sop->clipbox_vdist[i] * bsin(ang); ret_start = clipmove(&spos, &pp->cursectnum, xvect, yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER, 1); if (ret_start) { // hit something moving into start position min_dist = 0; min_ndx = i; // ox is where it should be opos[i].x = pos[i].x = pp->posx + MulScale(sop->clipbox_vdist[i], bcos(ang), 14); opos[i].y = pos[i].y = pp->posy + MulScale(sop->clipbox_vdist[i], bsin(ang), 14); // spos.x is where it hit pos[i].x = spos.x; pos[i].y = spos.y; // see the dist moved dist = ksqrt(SQ(pos[i].x - opos[i].x) + SQ(pos[i].y - opos[i].y)); // save it off if (dist < min_dist) { min_dist = dist; min_ndx = i; min_ret = ret_start; } } else { // save off the start position opos[i] = pos[i] = spos; pos[i].z = z; // move the box ret = clipmove(&pos[i], &pp->cursectnum, pp->xvect, pp->yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER); // save the dist moved dist = ksqrt(SQ(pos[i].x - opos[i].x) + SQ(pos[i].y - opos[i].y)); if (ret) { } if (dist < min_dist) { min_dist = dist; min_ndx = i; min_ret = ret; } } } // put posx and y off from offset pp->posx += pos[min_ndx].x - opos[min_ndx].x; pp->posy += pos[min_ndx].y - opos[min_ndx].y; return min_ret; } short MultiClipTurn(PLAYERp pp, short new_ang, int z, int floor_dist) { int i; SECTOR_OBJECTp sop = pp->sop; int ret; int x,y; short ang; int xvect, yvect; int cursectnum = pp->cursectnum; for (i = 0; i < sop->clipbox_num; i++) { ang = NORM_ANGLE(new_ang + sop->clipbox_ang[i]); vec3_t pos = { pp->posx, pp->posy, z }; xvect = sop->clipbox_vdist[i] * bcos(ang); yvect = sop->clipbox_vdist[i] * bsin(ang); // move the box ret = clipmove(&pos, &cursectnum, xvect, yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER); ASSERT(cursectnum >= 0); if (ret) { // attempt to move a bit when turning against a wall //ang = NORM_ANGLE(ang + 1024); //pp->xvect += 20 * bcos(ang); //pp->yvect += 20 * bsin(ang); return false; } } return true; } int testquadinsect(int *point_num, vec2_t const * q, short sectnum) { int i,next_i; *point_num = -1; for (i=0; i < 4; i++) { if (!inside(q[i].x, q[i].y, sectnum)) { *point_num = i; return false; } } for (i=0; i<4; i++) { next_i = (i+1) & 3; if (!cansee(q[i].x, q[i].y,0x3fffffff, sectnum, q[next_i].x, q[next_i].y,0x3fffffff, sectnum)) { return false; } } return true; } //Ken gives the tank clippin' a try... int RectClipMove(PLAYERp pp, int *qx, int *qy) { int i; vec2_t xy[4]; int point_num; for (i = 0; i < 4; i++) { xy[i].x = qx[i] + (pp->xvect>>14); xy[i].y = qy[i] + (pp->yvect>>14); } //Given the 4 points: x[4], y[4] if (testquadinsect(&point_num, xy, pp->cursectnum)) { pp->posx += (pp->xvect>>14); pp->posy += (pp->yvect>>14); return true; } if (point_num < 0) return false; if ((point_num == 0) || (point_num == 3)) //Left side bad - strafe right { for (i = 0; i < 4; i++) { xy[i].x = qx[i] - (pp->yvect>>15); xy[i].y = qy[i] + (pp->xvect>>15); } if (testquadinsect(&point_num, xy, pp->cursectnum)) { pp->posx -= (pp->yvect>>15); pp->posy += (pp->xvect>>15); } return false; } if ((point_num == 1) || (point_num == 2)) //Right side bad - strafe left { for (i = 0; i < 4; i++) { xy[i].x = qx[i] + (pp->yvect>>15); xy[i].y = qy[i] - (pp->xvect>>15); } if (testquadinsect(&point_num, xy, pp->cursectnum)) { pp->posx += (pp->yvect>>15); pp->posy -= (pp->xvect>>15); } return false; } return false; } int testpointinquad(int x, int y, int *qx, int *qy) { int i, cnt, x1, y1, x2, y2; cnt = 0; for (i=0; i<4; i++) { y1 = qy[i]-y; y2 = qy[(i+1)&3]-y; if ((y1^y2) >= 0) continue; x1 = qx[i]-x; x2 = qx[(i+1)&3]-x; if ((x1^x2) >= 0) cnt ^= x1; else cnt ^= (x1*y2-x2*y1)^y2; } return cnt>>31; } short RectClipTurn(PLAYERp pp, short new_ang, int *qx, int *qy, int *ox, int *oy) { int i; vec2_t xy[4]; SECTOR_OBJECTp sop = pp->sop; short rot_ang; int point_num; rot_ang = NORM_ANGLE(new_ang + sop->spin_ang - sop->ang_orig); for (i = 0; i < 4; i++) { vec2_t const p = { ox[i], oy[i] }; rotatepoint(pp->pos.vec2, p, rot_ang, &xy[i]); // cannot use sop->xmid and ymid because the SO is off the map at this point //rotatepoint(&sop->xmid, p, rot_ang, &xy[i]); } //Given the 4 points: x[4], y[4] if (testquadinsect(&point_num, xy, pp->cursectnum)) { // move to new pos for (i = 0; i < 4; i++) { qx[i] = xy[i].x; qy[i] = xy[i].y; } return true; } if (point_num < 0) return false; return false; } END_SW_NS
25.394137
137
0.506542
alexey-lysiuk
ebf103c146e5be8b574ba6777f15b84687b8e067
1,133
cpp
C++
oreore/oreore/cocos2d/actions/ShakeFadeOut.cpp
Giemsa/oreore
18c2f07bca7df9599aa68cf79d627e239b17461c
[ "Zlib" ]
4
2015-01-26T17:46:26.000Z
2018-12-28T09:09:19.000Z
oreore/oreore/cocos2d/actions/ShakeFadeOut.cpp
Giemsa/oreore
18c2f07bca7df9599aa68cf79d627e239b17461c
[ "Zlib" ]
null
null
null
oreore/oreore/cocos2d/actions/ShakeFadeOut.cpp
Giemsa/oreore
18c2f07bca7df9599aa68cf79d627e239b17461c
[ "Zlib" ]
null
null
null
#include "ShakeFadeOut.h" #include "../../Utils.h" namespace oreore { using namespace cocos2d; ShakeFadeOut *ShakeFadeOut::create(const float duration, const float strength) { return create(duration, strength, strength); } ShakeFadeOut *ShakeFadeOut::create(const float duration, const float level_x, const float level_y) { ShakeFadeOut *action = new ShakeFadeOut(); if(action && action->initWithDuration(duration, level_x, level_y)) { action->autorelease(); return action; } delete action; return nullptr; } void ShakeFadeOut::update(float time) { const float x = (random<float>(strength_x * 2) - strength_x) * (1.0f - time); const float y = (random<float>(strength_y * 2) - strength_y) * (1.0f - time); getOriginalTarget()->setPosition(dpos + Point(x, y)); } ShakeFadeOut *ShakeFadeOut::reverse() const { return clone(); } ShakeFadeOut *ShakeFadeOut::clone() const { return ShakeFadeOut::create(getDuration(), strength_x, strength_y); } }
25.75
102
0.616064
Giemsa
ebf67bcb4413e9c999e91f98f9eff5627331c191
12,727
cpp
C++
roxe.cdt/roxe_llvm/tools/llvm-mca/Scheduler.cpp
APFDev/actc
be5c1c0539d30a3745a725b0027767448ef8e1f6
[ "MIT" ]
5
2021-01-13T03:34:00.000Z
2021-09-09T05:42:18.000Z
roxe.cdt/roxe_llvm/tools/llvm-mca/Scheduler.cpp
APFDev/actc
be5c1c0539d30a3745a725b0027767448ef8e1f6
[ "MIT" ]
1
2020-05-16T06:30:28.000Z
2020-05-16T06:37:55.000Z
roxe.cdt/roxe_llvm/tools/llvm-mca/Scheduler.cpp
APFDev/actc
be5c1c0539d30a3745a725b0027767448ef8e1f6
[ "MIT" ]
6
2020-01-06T11:18:54.000Z
2020-01-07T09:32:18.000Z
//===--------------------- Scheduler.cpp ------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // A scheduler for processor resource units and processor resource groups. // //===----------------------------------------------------------------------===// #include "Scheduler.h" #include "Backend.h" #include "HWEventListener.h" #include "Support.h" #include "llvm/Support/raw_ostream.h" namespace mca { using namespace llvm; uint64_t ResourceState::selectNextInSequence() { assert(isReady()); uint64_t Next = getNextInSequence(); while (!isSubResourceReady(Next)) { updateNextInSequence(); Next = getNextInSequence(); } return Next; } #ifndef NDEBUG void ResourceState::dump() const { dbgs() << "MASK: " << ResourceMask << ", SIZE_MASK: " << ResourceSizeMask << ", NEXT: " << NextInSequenceMask << ", RDYMASK: " << ReadyMask << ", BufferSize=" << BufferSize << ", AvailableSlots=" << AvailableSlots << ", Reserved=" << Unavailable << '\n'; } #endif void ResourceManager::initialize(const llvm::MCSchedModel &SM) { computeProcResourceMasks(SM, ProcResID2Mask); for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) addResource(*SM.getProcResource(I), I, ProcResID2Mask[I]); } // Adds a new resource state in Resources, as well as a new descriptor in // ResourceDescriptor. Map 'Resources' allows to quickly obtain ResourceState // objects from resource mask identifiers. void ResourceManager::addResource(const MCProcResourceDesc &Desc, unsigned Index, uint64_t Mask) { assert(Resources.find(Mask) == Resources.end() && "Resource already added!"); Resources[Mask] = llvm::make_unique<ResourceState>(Desc, Index, Mask); } // Returns the actual resource consumed by this Use. // First, is the primary resource ID. // Second, is the specific sub-resource ID. std::pair<uint64_t, uint64_t> ResourceManager::selectPipe(uint64_t ResourceID) { ResourceState &RS = *Resources[ResourceID]; uint64_t SubResourceID = RS.selectNextInSequence(); if (RS.isAResourceGroup()) return selectPipe(SubResourceID); return std::pair<uint64_t, uint64_t>(ResourceID, SubResourceID); } void ResourceState::removeFromNextInSequence(uint64_t ID) { assert(NextInSequenceMask); assert(countPopulation(ID) == 1); if (ID > getNextInSequence()) RemovedFromNextInSequence |= ID; NextInSequenceMask = NextInSequenceMask & (~ID); if (!NextInSequenceMask) { NextInSequenceMask = ResourceSizeMask; assert(NextInSequenceMask != RemovedFromNextInSequence); NextInSequenceMask ^= RemovedFromNextInSequence; RemovedFromNextInSequence = 0; } } void ResourceManager::use(ResourceRef RR) { // Mark the sub-resource referenced by RR as used. ResourceState &RS = *Resources[RR.first]; RS.markSubResourceAsUsed(RR.second); // If there are still available units in RR.first, // then we are done. if (RS.isReady()) return; // Notify to other resources that RR.first is no longer available. for (const std::pair<uint64_t, UniqueResourceState> &Res : Resources) { ResourceState &Current = *Res.second.get(); if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first) continue; if (Current.containsResource(RR.first)) { Current.markSubResourceAsUsed(RR.first); Current.removeFromNextInSequence(RR.first); } } } void ResourceManager::release(ResourceRef RR) { ResourceState &RS = *Resources[RR.first]; bool WasFullyUsed = !RS.isReady(); RS.releaseSubResource(RR.second); if (!WasFullyUsed) return; for (const std::pair<uint64_t, UniqueResourceState> &Res : Resources) { ResourceState &Current = *Res.second.get(); if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first) continue; if (Current.containsResource(RR.first)) Current.releaseSubResource(RR.first); } } ResourceStateEvent ResourceManager::canBeDispatched(ArrayRef<uint64_t> Buffers) const { ResourceStateEvent Result = ResourceStateEvent::RS_BUFFER_AVAILABLE; for (uint64_t Buffer : Buffers) { Result = isBufferAvailable(Buffer); if (Result != ResourceStateEvent::RS_BUFFER_AVAILABLE) break; } return Result; } void ResourceManager::reserveBuffers(ArrayRef<uint64_t> Buffers) { for (const uint64_t R : Buffers) { reserveBuffer(R); ResourceState &Resource = *Resources[R]; if (Resource.isADispatchHazard()) { assert(!Resource.isReserved()); Resource.setReserved(); } } } void ResourceManager::releaseBuffers(ArrayRef<uint64_t> Buffers) { for (const uint64_t R : Buffers) releaseBuffer(R); } bool ResourceManager::canBeIssued(const InstrDesc &Desc) const { return std::all_of(Desc.Resources.begin(), Desc.Resources.end(), [&](const std::pair<uint64_t, const ResourceUsage> &E) { unsigned NumUnits = E.second.isReserved() ? 0U : E.second.NumUnits; return isReady(E.first, NumUnits); }); } // Returns true if all resources are in-order, and there is at least one // resource which is a dispatch hazard (BufferSize = 0). bool ResourceManager::mustIssueImmediately(const InstrDesc &Desc) { if (!canBeIssued(Desc)) return false; bool AllInOrderResources = all_of(Desc.Buffers, [&](uint64_t BufferMask) { const ResourceState &Resource = *Resources[BufferMask]; return Resource.isInOrder() || Resource.isADispatchHazard(); }); if (!AllInOrderResources) return false; return any_of(Desc.Buffers, [&](uint64_t BufferMask) { return Resources[BufferMask]->isADispatchHazard(); }); } void ResourceManager::issueInstruction( const InstrDesc &Desc, SmallVectorImpl<std::pair<ResourceRef, double>> &Pipes) { for (const std::pair<uint64_t, ResourceUsage> &R : Desc.Resources) { const CycleSegment &CS = R.second.CS; if (!CS.size()) { releaseResource(R.first); continue; } assert(CS.begin() == 0 && "Invalid {Start, End} cycles!"); if (!R.second.isReserved()) { ResourceRef Pipe = selectPipe(R.first); use(Pipe); BusyResources[Pipe] += CS.size(); // Replace the resource mask with a valid processor resource index. const ResourceState &RS = *Resources[Pipe.first]; Pipe.first = RS.getProcResourceID(); Pipes.emplace_back( std::pair<ResourceRef, double>(Pipe, static_cast<double>(CS.size()))); } else { assert((countPopulation(R.first) > 1) && "Expected a group!"); // Mark this group as reserved. assert(R.second.isReserved()); reserveResource(R.first); BusyResources[ResourceRef(R.first, R.first)] += CS.size(); } } } void ResourceManager::cycleEvent(SmallVectorImpl<ResourceRef> &ResourcesFreed) { for (std::pair<ResourceRef, unsigned> &BR : BusyResources) { if (BR.second) BR.second--; if (!BR.second) { // Release this resource. const ResourceRef &RR = BR.first; if (countPopulation(RR.first) == 1) release(RR); releaseResource(RR.first); ResourcesFreed.push_back(RR); } } for (const ResourceRef &RF : ResourcesFreed) BusyResources.erase(RF); } #ifndef NDEBUG void Scheduler::dump() const { dbgs() << "[SCHEDULER]: WaitQueue size is: " << WaitQueue.size() << '\n'; dbgs() << "[SCHEDULER]: ReadyQueue size is: " << ReadyQueue.size() << '\n'; dbgs() << "[SCHEDULER]: IssuedQueue size is: " << IssuedQueue.size() << '\n'; Resources->dump(); } #endif bool Scheduler::canBeDispatched(const InstRef &IR, HWStallEvent::GenericEventType &Event) const { Event = HWStallEvent::Invalid; const InstrDesc &Desc = IR.getInstruction()->getDesc(); if (Desc.MayLoad && LSU->isLQFull()) Event = HWStallEvent::LoadQueueFull; else if (Desc.MayStore && LSU->isSQFull()) Event = HWStallEvent::StoreQueueFull; else { switch (Resources->canBeDispatched(Desc.Buffers)) { default: return true; case ResourceStateEvent::RS_BUFFER_UNAVAILABLE: Event = HWStallEvent::SchedulerQueueFull; break; case ResourceStateEvent::RS_RESERVED: Event = HWStallEvent::DispatchGroupStall; } } return false; } void Scheduler::issueInstructionImpl( InstRef &IR, SmallVectorImpl<std::pair<ResourceRef, double>> &UsedResources) { Instruction *IS = IR.getInstruction(); const InstrDesc &D = IS->getDesc(); // Issue the instruction and collect all the consumed resources // into a vector. That vector is then used to notify the listener. Resources->issueInstruction(D, UsedResources); // Notify the instruction that it started executing. // This updates the internal state of each write. IS->execute(); if (IS->isExecuting()) IssuedQueue[IR.getSourceIndex()] = IS; } // Release the buffered resources and issue the instruction. void Scheduler::issueInstruction( InstRef &IR, SmallVectorImpl<std::pair<ResourceRef, double>> &UsedResources) { const InstrDesc &Desc = IR.getInstruction()->getDesc(); releaseBuffers(Desc.Buffers); issueInstructionImpl(IR, UsedResources); } void Scheduler::promoteToReadyQueue(SmallVectorImpl<InstRef> &Ready) { // Scan the set of waiting instructions and promote them to the // ready queue if operands are all ready. for (auto I = WaitQueue.begin(), E = WaitQueue.end(); I != E;) { const unsigned IID = I->first; Instruction *IS = I->second; // Check if this instruction is now ready. In case, force // a transition in state using method 'update()'. IS->update(); const InstrDesc &Desc = IS->getDesc(); bool IsMemOp = Desc.MayLoad || Desc.MayStore; if (!IS->isReady() || (IsMemOp && !LSU->isReady({IID, IS}))) { ++I; continue; } Ready.emplace_back(IID, IS); ReadyQueue[IID] = IS; auto ToRemove = I; ++I; WaitQueue.erase(ToRemove); } } InstRef Scheduler::select() { // Give priority to older instructions in the ReadyQueue. Since the ready // queue is ordered by key, this will always prioritize older instructions. const auto It = std::find_if(ReadyQueue.begin(), ReadyQueue.end(), [&](const QueueEntryTy &Entry) { const InstrDesc &D = Entry.second->getDesc(); return Resources->canBeIssued(D); }); if (It == ReadyQueue.end()) return {0, nullptr}; // We found an instruction to issue. InstRef IR(It->first, It->second); ReadyQueue.erase(It); return IR; } void Scheduler::updatePendingQueue(SmallVectorImpl<InstRef> &Ready) { // Notify to instructions in the pending queue that a new cycle just // started. for (QueueEntryTy Entry : WaitQueue) Entry.second->cycleEvent(); promoteToReadyQueue(Ready); } void Scheduler::updateIssuedQueue(SmallVectorImpl<InstRef> &Executed) { for (auto I = IssuedQueue.begin(), E = IssuedQueue.end(); I != E;) { const QueueEntryTy Entry = *I; Instruction *IS = Entry.second; IS->cycleEvent(); if (IS->isExecuted()) { Executed.push_back({Entry.first, Entry.second}); auto ToRemove = I; ++I; IssuedQueue.erase(ToRemove); } else { LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction " << Entry.first << " is still executing.\n"); ++I; } } } void Scheduler::onInstructionExecuted(const InstRef &IR) { LSU->onInstructionExecuted(IR); } void Scheduler::reclaimSimulatedResources(SmallVectorImpl<ResourceRef> &Freed) { Resources->cycleEvent(Freed); } bool Scheduler::reserveResources(InstRef &IR) { // If necessary, reserve queue entries in the load-store unit (LSU). const bool Reserved = LSU->reserve(IR); if (!IR.getInstruction()->isReady() || (Reserved && !LSU->isReady(IR))) { LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding " << IR << " to the Wait Queue\n"); WaitQueue[IR.getSourceIndex()] = IR.getInstruction(); return false; } return true; } bool Scheduler::issueImmediately(InstRef &IR) { const InstrDesc &Desc = IR.getInstruction()->getDesc(); if (!Desc.isZeroLatency() && !Resources->mustIssueImmediately(Desc)) { LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding " << IR << " to the Ready Queue\n"); ReadyQueue[IR.getSourceIndex()] = IR.getInstruction(); return false; } return true; } } // namespace mca
32.886305
80
0.656085
APFDev
ebf6f7382807ed1f1b6d9b7c3f094ef1253c0120
225,178
cpp
C++
bench/ml2cpp-demo/BaggingClassifier/FourClass_100/ml2cpp-demo_BaggingClassifier_FourClass_100.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
null
null
null
bench/ml2cpp-demo/BaggingClassifier/FourClass_100/ml2cpp-demo_BaggingClassifier_FourClass_100.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
33
2020-09-13T09:55:01.000Z
2022-01-06T11:53:55.000Z
bench/ml2cpp-demo/BaggingClassifier/FourClass_100/ml2cpp-demo_BaggingClassifier_FourClass_100.cpp
antoinecarme/ml2cpp
2b241d44de00eafda620c2b605690276faf5f8fb
[ "BSD-3-Clause" ]
1
2021-01-26T14:41:58.000Z
2021-01-26T14:41:58.000Z
// ******************************************************** // This C++ code was automatically generated by ml2cpp (development version). // Copyright 2020 // https://github.com/antoinecarme/ml2cpp // Model : BaggingClassifier // Dataset : FourClass_100 // This CPP code can be compiled using any C++-17 compiler. // g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_BaggingClassifier_FourClass_100.exe ml2cpp-demo_BaggingClassifier_FourClass_100.cpp // Model deployment code // ******************************************************** #include "../../Generic.i" namespace { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } namespace SubModel_0 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 0.0, 1.0, 0.0 }} , { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 7 , {0.0, 1.0, 0.0, 0.0 }} , { 8 , {0.0, 0.0, 1.0, 0.0 }} , { 11 , {1.0, 0.0, 0.0, 0.0 }} , { 12 , {0.0, 1.0, 0.0, 0.0 }} , { 13 , {0.0, 1.0, 0.0, 0.0 }} , { 17 , {0.0, 0.0, 0.0, 1.0 }} , { 18 , {1.0, 0.0, 0.0, 0.0 }} , { 20 , {0.0, 1.0, 0.0, 0.0 }} , { 21 , {0.0, 0.0, 0.0, 1.0 }} , { 23 , {1.0, 0.0, 0.0, 0.0 }} , { 25 , {0.0, 1.0, 0.0, 0.0 }} , { 26 , {0.0, 0.0, 0.0, 1.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_62 <= 1.503589004278183) ? ( 2 ) : ( 3 ) ) : ( (Feature_19 <= -0.5789696276187897) ? ( (Feature_78 <= -0.6031690239906311) ? ( (Feature_56 <= -8.097998857498169) ? ( 7 ) : ( 8 ) ) : ( (Feature_42 <= -0.2146744355559349) ? ( (Feature_90 <= 1.5686895251274109) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) : ( (Feature_99 <= 0.00624384731054306) ? ( (Feature_44 <= -0.7715538442134857) ? ( (Feature_53 <= -1.3674404621124268) ? ( 17 ) : ( 18 ) ) : ( (Feature_89 <= -1.1485321521759033) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_11 <= 0.45316772162914276) ? ( 23 ) : ( (Feature_50 <= -0.7742524668574333) ? ( 25 ) : ( 26 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_0 namespace SubModel_1 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.0, 0.0, 1.0, 0.0 }} , { 6 , {0.0, 0.0, 1.0, 0.0 }} , { 7 , {0.0, 1.0, 0.0, 0.0 }} , { 9 , {0.0, 0.0, 1.0, 0.0 }} , { 10 , {1.0, 0.0, 0.0, 0.0 }} , { 12 , {0.0, 0.0, 0.0, 1.0 }} , { 14 , {0.0, 1.0, 0.0, 0.0 }} , { 15 , {1.0, 0.0, 0.0, 0.0 }} , { 19 , {0.0, 0.0, 0.0, 1.0 }} , { 20 , {1.0, 0.0, 0.0, 0.0 }} , { 21 , {0.0, 1.0, 0.0, 0.0 }} , { 23 , {0.0, 1.0, 0.0, 0.0 }} , { 24 , {0.0, 0.0, 0.0, 1.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( 1 ) : ( (Feature_33 <= -0.08118173107504845) ? ( (Feature_41 <= 0.6967471539974213) ? ( (Feature_16 <= -0.818017452955246) ? ( (Feature_41 <= -0.07286195456981659) ? ( 6 ) : ( 7 ) ) : ( (Feature_41 <= -2.0635533332824707) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_78 <= 1.29881152510643) ? ( 12 ) : ( (Feature_14 <= -0.16014254093170166) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_46 <= 0.3926301449537277) ? ( (Feature_48 <= -0.17612321954220533) ? ( (Feature_30 <= -0.8991427272558212) ? ( 19 ) : ( 20 ) ) : ( 21 ) ) : ( (Feature_11 <= -1.096106618642807) ? ( 23 ) : ( 24 ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_1 namespace SubModel_2 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {0.0, 1.0, 0.0, 0.0 }} , { 5 , {1.0, 0.0, 0.0, 0.0 }} , { 8 , {1.0, 0.0, 0.0, 0.0 }} , { 9 , {0.0, 0.0, 1.0, 0.0 }} , { 10 , {0.0, 0.0, 0.0, 1.0 }} , { 11 , {0.0, 1.0, 0.0, 0.0 }} , { 16 , {0.0, 1.0, 0.0, 0.0 }} , { 17 , {1.0, 0.0, 0.0, 0.0 }} , { 18 , {0.0, 0.0, 1.0, 0.0 }} , { 21 , {0.0, 0.0, 1.0, 0.0 }} , { 22 , {0.5, 0.0, 0.0, 0.5 }} , { 23 , {0.0, 1.0, 0.0, 0.0 }} , { 24 , {1.0, 0.0, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_99 <= -0.09796052239835262) ? ( (Feature_78 <= 1.7039188742637634) ? ( (Feature_89 <= -0.5055654942989349) ? ( (Feature_54 <= 0.032076217234134674) ? ( 4 ) : ( 5 ) ) : ( (Feature_59 <= -0.3915305733680725) ? ( (Feature_94 <= -0.7241016756743193) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) ) : ( 11 ) ) : ( (Feature_24 <= 0.5892128348350525) ? ( (Feature_45 <= 0.11031141877174377) ? ( (Feature_38 <= -0.8665039539337158) ? ( (Feature_60 <= -0.029639005661010742) ? ( 16 ) : ( 17 ) ) : ( 18 ) ) : ( (Feature_24 <= -0.6491396576166153) ? ( (Feature_69 <= -0.3395440876483917) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) ) : ( 24 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_2 namespace SubModel_3 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 1 , {0.0, 0.0, 1.0, 0.0 }} , { 6 , {1.0, 0.0, 0.0, 0.0 }} , { 7 , {0.08, 0.44, 0.32, 0.16 }} , { 9 , {0.0, 0.0, 0.0, 1.0 }} , { 10 , {0.0, 1.0, 0.0, 0.0 }} , { 13 , {0.0, 0.0, 0.0, 1.0 }} , { 14 , {0.0, 1.0, 0.0, 0.0 }} , { 15 , {1.0, 0.0, 0.0, 0.0 }} , { 17 , {0.0, 1.0, 0.0, 0.0 }} , { 18 , {1.0, 0.0, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.2519255876541138) ? ( 1 ) : ( (Feature_92 <= 0.8728378117084503) ? ( (Feature_78 <= 0.8840557038784027) ? ( (Feature_41 <= 0.37245966494083405) ? ( (Feature_70 <= -0.36322344839572906) ? ( 6 ) : ( 7 ) ) : ( (Feature_7 <= 1.2444062232971191) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_14 <= -0.3580637127161026) ? ( (Feature_40 <= 1.0264981649816036) ? ( 13 ) : ( 14 ) ) : ( 15 ) ) ) : ( (Feature_79 <= 1.8128423690795898) ? ( 17 ) : ( 18 ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_3 namespace SubModel_4 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {0.0, 0.0, 0.0, 1.0 }} , { 6 , {0.0, 0.5, 0.5, 0.0 }} , { 7 , {1.0, 0.0, 0.0, 0.0 }} , { 8 , {0.0, 0.0, 1.0, 0.0 }} , { 11 , {0.0, 0.0, 0.0, 1.0 }} , { 12 , {0.0, 1.0, 0.0, 0.0 }} , { 14 , {0.0, 1.0, 0.0, 0.0 }} , { 15 , {0.0, 0.0, 1.0, 0.0 }} , { 19 , {1.0, 0.0, 0.0, 0.0 }} , { 20 , {0.0, 1.0, 0.0, 0.0 }} , { 22 , {0.0, 0.0, 1.0, 0.0 }} , { 23 , {1.0, 0.0, 0.0, 0.0 }} , { 25 , {1.0, 0.0, 0.0, 0.0 }} , { 26 , {0.0, 0.0, 0.0, 1.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_78 <= -0.6542530655860901) ? ( (Feature_44 <= 0.2128865383565426) ? ( (Feature_99 <= -1.187854915857315) ? ( (Feature_6 <= 0.2931538235861808) ? ( 4 ) : ( (Feature_50 <= -0.677160769701004) ? ( 6 ) : ( 7 ) ) ) : ( 8 ) ) : ( (Feature_9 <= 0.727972537279129) ? ( (Feature_74 <= 1.5878617763519287) ? ( 11 ) : ( 12 ) ) : ( (Feature_7 <= -0.2916768416762352) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_19 <= -0.08902734890580177) ? ( (Feature_32 <= 0.42078158259391785) ? ( (Feature_49 <= -2.1161219477653503) ? ( 19 ) : ( 20 ) ) : ( (Feature_43 <= 0.031263142824172974) ? ( 22 ) : ( 23 ) ) ) : ( (Feature_28 <= 1.1810160875320435) ? ( 25 ) : ( 26 ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_4 namespace SubModel_5 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 1.0, 0.0, 0.0 }} , { 4 , {0.0, 0.0, 1.0, 0.0 }} , { 6 , {1.0, 0.0, 0.0, 0.0 }} , { 7 , {0.0, 0.0, 1.0, 0.0 }} , { 11 , {0.0, 1.0, 0.0, 0.0 }} , { 12 , {1.0, 0.0, 0.0, 0.0 }} , { 15 , {0.6666666666666666, 0.0, 0.3333333333333333, 0.0 }} , { 16 , {0.0, 0.05263157894736842, 0.0, 0.9473684210526315 }} , { 17 , {0.0, 0.0, 1.0, 0.0 }} , { 21 , {1.0, 0.0, 0.0, 0.0 }} , { 22 , {0.0, 0.0, 0.0, 1.0 }} , { 23 , {0.0, 1.0, 0.0, 0.0 }} , { 25 , {1.0, 0.0, 0.0, 0.0 }} , { 26 , {0.0, 0.0, 1.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -1.309776484966278) ? ( (Feature_99 <= -2.194583535194397) ? ( 2 ) : ( (Feature_45 <= 0.1697009578347206) ? ( 4 ) : ( (Feature_76 <= -0.5688562635332346) ? ( 6 ) : ( 7 ) ) ) ) : ( (Feature_94 <= -0.33069832623004913) ? ( (Feature_38 <= -0.7251038551330566) ? ( (Feature_53 <= -3.49560284614563) ? ( 11 ) : ( 12 ) ) : ( (Feature_5 <= 0.5689798295497894) ? ( (Feature_73 <= -0.648361474275589) ? ( 15 ) : ( 16 ) ) : ( 17 ) ) ) : ( (Feature_24 <= 0.4838130474090576) ? ( (Feature_16 <= -0.5087056756019592) ? ( (Feature_76 <= -0.5111970640718937) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) : ( (Feature_91 <= -0.035808783024549484) ? ( 25 ) : ( 26 ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_5 namespace SubModel_6 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 4 , {0.0, 0.0, 1.0, 0.0 }} , { 8 , {0.9130434782608695, 0.043478260869565216, 0.043478260869565216, 0.0 }} , { 9 , {0.0, 0.16666666666666666, 0.16666666666666666, 0.6666666666666666 }} , { 11 , {0.1111111111111111, 0.8333333333333334, 0.0, 0.05555555555555555 }} , { 12 , {0.3333333333333333, 0.0, 0.0, 0.6666666666666666 }} , { 15 , {0.0, 0.0, 0.0, 1.0 }} , { 16 , {0.0, 0.0, 1.0, 0.0 }} , { 18 , {1.0, 0.0, 0.0, 0.0 }} , { 19 , {0.0, 0.0, 1.0, 0.0 }} , { 20 , {0.0, 1.0, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_73 <= 1.6641205549240112) ? ( (Feature_44 <= -2.1092634201049805) ? ( (Feature_63 <= -1.0751223862171173) ? ( 3 ) : ( 4 ) ) : ( (Feature_14 <= 1.0025184750556946) ? ( (Feature_45 <= 0.25321291387081146) ? ( (Feature_20 <= 0.688479095697403) ? ( 8 ) : ( 9 ) ) : ( (Feature_32 <= 0.28152644634246826) ? ( 11 ) : ( 12 ) ) ) : ( (Feature_99 <= -0.3237369656562805) ? ( (Feature_27 <= 0.9087257087230682) ? ( 15 ) : ( 16 ) ) : ( (Feature_38 <= -0.6264585703611374) ? ( 18 ) : ( 19 ) ) ) ) ) : ( 20 ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_6 namespace SubModel_7 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 0.0, 1.0, 0.0 }} , { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 7 , {0.0, 0.0, 1.0, 0.0 }} , { 8 , {0.0, 0.0, 0.0, 1.0 }} , { 10 , {0.0, 1.0, 0.0, 0.0 }} , { 12 , {1.0, 0.0, 0.0, 0.0 }} , { 13 , {0.0, 0.0, 1.0, 0.0 }} , { 16 , {0.0, 0.0, 0.0, 1.0 }} , { 18 , {0.0, 0.0, 0.0, 1.0 }} , { 19 , {0.0, 1.0, 0.0, 0.0 }} , { 22 , {1.0, 0.0, 0.0, 0.0 }} , { 23 , {0.0, 0.5, 0.0, 0.5 }} , { 25 , {0.0, 1.0, 0.0, 0.0 }} , { 26 , {0.07692307692307693, 0.3076923076923077, 0.5384615384615384, 0.07692307692307693 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_66 <= 1.6641189455986023) ? ( 2 ) : ( 3 ) ) : ( (Feature_44 <= -0.49318933486938477) ? ( (Feature_68 <= -0.910584956407547) ? ( (Feature_39 <= 0.012014441192150116) ? ( 7 ) : ( 8 ) ) : ( (Feature_32 <= -1.8123965859413147) ? ( 10 ) : ( (Feature_11 <= 1.5604674816131592) ? ( 12 ) : ( 13 ) ) ) ) : ( (Feature_99 <= -0.3237369656562805) ? ( (Feature_47 <= 0.7225238382816315) ? ( 16 ) : ( (Feature_93 <= -1.1102982759475708) ? ( 18 ) : ( 19 ) ) ) : ( (Feature_29 <= -1.114558756351471) ? ( (Feature_0 <= 0.44958434998989105) ? ( 22 ) : ( 23 ) ) : ( (Feature_30 <= -0.5763616859912872) ? ( 25 ) : ( 26 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_7 namespace SubModel_8 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 0.0, 1.0, 0.0 }} , { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 6 , {0.0, 0.0, 0.0, 1.0 }} , { 8 , {0.0, 0.0, 1.0, 0.0 }} , { 10 , {0.0, 1.0, 0.0, 0.0 }} , { 11 , {0.5, 0.0, 0.0, 0.5 }} , { 14 , {1.0, 0.0, 0.0, 0.0 }} , { 15 , {0.0, 1.0, 0.0, 0.0 }} , { 18 , {0.0, 0.0, 0.0, 1.0 }} , { 19 , {0.9285714285714286, 0.03571428571428571, 0.03571428571428571, 0.0 }} , { 21 , {0.0, 1.0, 0.0, 0.0 }} , { 22 , {0.0, 0.0, 0.0, 1.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_30 <= 0.7127983272075653) ? ( 2 ) : ( 3 ) ) : ( (Feature_78 <= -0.8434274196624756) ? ( (Feature_99 <= -0.5882234573364258) ? ( 6 ) : ( (Feature_19 <= -0.8192912638187408) ? ( 8 ) : ( (Feature_1 <= 0.6547807157039642) ? ( 10 ) : ( 11 ) ) ) ) : ( (Feature_43 <= -0.7006235718727112) ? ( (Feature_91 <= -0.12150455266237259) ? ( 14 ) : ( 15 ) ) : ( (Feature_27 <= 3.23024845123291) ? ( (Feature_81 <= -1.4423141479492188) ? ( 18 ) : ( 19 ) ) : ( (Feature_20 <= 0.9908088445663452) ? ( 21 ) : ( 22 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_8 namespace SubModel_9 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 0.0, 1.0, 0.0 }} , { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 8 , {0.0, 1.0, 0.0, 0.0 }} , { 9 , {1.0, 0.0, 0.0, 0.0 }} , { 11 , {0.0, 0.0, 0.3333333333333333, 0.6666666666666666 }} , { 12 , {1.0, 0.0, 0.0, 0.0 }} , { 13 , {1.0, 0.0, 0.0, 0.0 }} , { 15 , {0.0, 1.0, 0.0, 0.0 }} , { 18 , {0.0, 0.037037037037037035, 0.07407407407407407, 0.8888888888888888 }} , { 19 , {1.0, 0.0, 0.0, 0.0 }} , { 21 , {0.5, 0.5, 0.0, 0.0 }} , { 22 , {0.0, 0.0, 1.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_48 <= 1.2093676924705505) ? ( 2 ) : ( 3 ) ) : ( (Feature_29 <= -0.10024451464414597) ? ( (Feature_24 <= 0.3782288730144501) ? ( (Feature_49 <= 0.33082690834999084) ? ( (Feature_85 <= 1.473156750202179) ? ( 8 ) : ( 9 ) ) : ( (Feature_72 <= 0.03332477807998657) ? ( 11 ) : ( 12 ) ) ) : ( 13 ) ) : ( (Feature_28 <= -1.3160618543624878) ? ( 15 ) : ( (Feature_71 <= 0.7019776701927185) ? ( (Feature_93 <= 1.258106768131256) ? ( 18 ) : ( 19 ) ) : ( (Feature_77 <= -0.0934767834842205) ? ( 21 ) : ( 22 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_9 namespace SubModel_10 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 5 , {1.0, 0.0, 0.0, 0.0 }} , { 6 , {0.0, 1.0, 0.0, 0.0 }} , { 8 , {0.5, 0.5, 0.0, 0.0 }} , { 9 , {0.0, 0.0, 1.0, 0.0 }} , { 12 , {0.0, 1.0, 0.0, 0.0 }} , { 13 , {0.0, 0.0, 1.0, 0.0 }} , { 14 , {0.0, 0.0, 0.0, 1.0 }} , { 17 , {0.0, 1.0, 0.0, 0.0 }} , { 18 , {0.0, 0.0, 1.0, 0.0 }} , { 21 , {1.0, 0.0, 0.0, 0.0 }} , { 22 , {0.0, 1.0, 0.0, 0.0 }} , { 24 , {0.0, 0.0, 0.0, 1.0 }} , { 25 , {0.0, 1.0, 0.0, 0.0 }} , { 27 , {0.0, 1.0, 0.0, 0.0 }} , { 28 , {0.0, 0.0, 0.0, 1.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= 2.0125714540481567) ? ( (Feature_56 <= 0.6710653007030487) ? ( (Feature_10 <= 0.4213555306196213) ? ( (Feature_91 <= -0.9002590477466583) ? ( (Feature_61 <= 2.485666036605835) ? ( 5 ) : ( 6 ) ) : ( (Feature_40 <= -1.0761661529541016) ? ( 8 ) : ( 9 ) ) ) : ( (Feature_4 <= 0.049746282398700714) ? ( (Feature_36 <= 0.48682308197021484) ? ( 12 ) : ( 13 ) ) : ( 14 ) ) ) : ( (Feature_12 <= -0.7289259433746338) ? ( (Feature_36 <= 0.3711119145154953) ? ( 17 ) : ( 18 ) ) : ( (Feature_29 <= 0.9479873329401016) ? ( (Feature_78 <= 4.133114576339722) ? ( 21 ) : ( 22 ) ) : ( (Feature_91 <= 0.15714242216199636) ? ( 24 ) : ( 25 ) ) ) ) ) : ( (Feature_1 <= -0.5874605476856232) ? ( 27 ) : ( 28 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_10 namespace SubModel_11 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 0.0, 1.0, 0.0 }} , { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 8 , {0.7142857142857143, 0.14285714285714285, 0.0, 0.14285714285714285 }} , { 9 , {0.0, 0.7741935483870968, 0.0967741935483871, 0.12903225806451613 }} , { 11 , {1.0, 0.0, 0.0, 0.0 }} , { 12 , {0.0, 0.0, 1.0, 0.0 }} , { 14 , {1.0, 0.0, 0.0, 0.0 }} , { 15 , {0.0, 0.0, 1.0, 0.0 }} , { 16 , {0.0, 0.0, 0.0, 1.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_48 <= 0.9457052946090698) ? ( 2 ) : ( 3 ) ) : ( (Feature_20 <= 1.2383397221565247) ? ( (Feature_24 <= 0.5572461783885956) ? ( (Feature_71 <= 0.8951122760772705) ? ( (Feature_65 <= -1.0845131874084473) ? ( 8 ) : ( 9 ) ) : ( (Feature_1 <= 0.8677243292331696) ? ( 11 ) : ( 12 ) ) ) : ( (Feature_38 <= 0.7453548833727837) ? ( 14 ) : ( 15 ) ) ) : ( 16 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_11 namespace SubModel_12 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {0.0, 0.0, 0.0, 1.0 }} , { 6 , {0.0, 1.0, 0.0, 0.0 }} , { 7 , {0.0, 0.0, 1.0, 0.0 }} , { 9 , {0.0, 0.0, 0.0, 1.0 }} , { 10 , {0.0, 1.0, 0.0, 0.0 }} , { 12 , {0.0, 0.0, 0.0, 1.0 }} , { 14 , {0.0, 1.0, 0.0, 0.0 }} , { 15 , {1.0, 0.0, 0.0, 0.0 }} , { 18 , {1.0, 0.0, 0.0, 0.0 }} , { 20 , {0.0, 0.0, 1.0, 0.0 }} , { 21 , {0.0, 1.0, 0.0, 0.0 }} , { 24 , {0.0, 1.0, 0.0, 0.0 }} , { 25 , {1.0, 0.0, 0.0, 0.0 }} , { 28 , {1.0, 0.0, 0.0, 0.0 }} , { 29 , {0.0, 0.0, 0.0, 1.0 }} , { 31 , {0.0, 1.0, 0.0, 0.0 }} , { 32 , {0.0, 0.0, 0.6, 0.4 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_78 <= -0.6111561059951782) ? ( (Feature_44 <= 1.6692100763320923) ? ( (Feature_15 <= 0.9708277881145477) ? ( (Feature_94 <= -1.621713638305664) ? ( 4 ) : ( (Feature_27 <= -2.2659579515457153) ? ( 6 ) : ( 7 ) ) ) : ( (Feature_75 <= 0.3124377280473709) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_99 <= -0.3222829457372427) ? ( 12 ) : ( (Feature_0 <= 0.4392481744289398) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_33 <= -0.31368252635002136) ? ( (Feature_67 <= 1.2143447399139404) ? ( 18 ) : ( (Feature_45 <= 0.17234395071864128) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_38 <= -0.8088268935680389) ? ( (Feature_91 <= -0.5887814164161682) ? ( 24 ) : ( 25 ) ) : ( (Feature_88 <= 0.273276109714061) ? ( (Feature_51 <= -3.0600167512893677) ? ( 28 ) : ( 29 ) ) : ( (Feature_72 <= -0.6026551425457001) ? ( 31 ) : ( 32 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_12 namespace SubModel_13 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 1.0, 0.0, 0.0 }} , { 3 , {0.0, 0.0, 1.0, 0.0 }} , { 7 , {1.0, 0.0, 0.0, 0.0 }} , { 8 , {0.0, 1.0, 0.0, 0.0 }} , { 11 , {0.0, 0.0, 0.0, 1.0 }} , { 12 , {0.4, 0.6, 0.0, 0.0 }} , { 13 , {0.0, 0.0, 1.0, 0.0 }} , { 17 , {0.0, 0.0, 0.0, 1.0 }} , { 18 , {0.0, 0.0, 1.0, 0.0 }} , { 20 , {0.0, 1.0, 0.0, 0.0 }} , { 21 , {1.0, 0.0, 0.0, 0.0 }} , { 24 , {0.0, 0.0, 0.0, 1.0 }} , { 25 , {0.0, 0.8, 0.0, 0.2 }} , { 26 , {1.0, 0.0, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_99 <= -2.194583535194397) ? ( 2 ) : ( 3 ) ) : ( (Feature_20 <= -0.08544048853218555) ? ( (Feature_92 <= 0.16372115537524223) ? ( (Feature_41 <= 1.1139306724071503) ? ( 7 ) : ( 8 ) ) : ( (Feature_22 <= 0.12712760269641876) ? ( (Feature_83 <= 0.04717770963907242) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) : ( (Feature_19 <= -0.5648867189884186) ? ( (Feature_68 <= -0.43200263381004333) ? ( (Feature_23 <= 0.18997395038604736) ? ( 17 ) : ( 18 ) ) : ( (Feature_6 <= 1.6022411584854126) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_78 <= 1.8294076323509216) ? ( (Feature_94 <= 0.11547934566624463) ? ( 24 ) : ( 25 ) ) : ( 26 ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_13 namespace SubModel_14 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 4 , {0.0, 1.0, 0.0, 0.0 }} , { 5 , {0.0, 0.0, 1.0, 0.0 }} , { 8 , {0.0, 0.0, 0.0, 1.0 }} , { 9 , {0.0, 0.0, 1.0, 0.0 }} , { 10 , {0.0, 1.0, 0.0, 0.0 }} , { 13 , {0.0, 1.0, 0.0, 0.0 }} , { 14 , {1.0, 0.0, 0.0, 0.0 }} , { 15 , {0.0, 0.0, 0.0, 1.0 }} , { 18 , {0.0, 1.0, 0.0, 0.0 }} , { 20 , {0.0, 0.0, 0.0, 1.0 }} , { 21 , {1.0, 0.0, 0.0, 0.0 }} , { 23 , {0.0, 0.0, 0.0, 1.0 }} , { 26 , {0.0, 1.0, 0.0, 0.0 }} , { 27 , {1.0, 0.0, 0.0, 0.0 }} , { 29 , {0.0, 0.0, 1.0, 0.0 }} , { 30 , {0.0, 1.0, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_78 <= -0.5283965766429901) ? ( (Feature_10 <= 0.3236100971698761) ? ( (Feature_44 <= -0.010307437914889306) ? ( (Feature_51 <= -2.8441089391708374) ? ( 4 ) : ( 5 ) ) : ( (Feature_10 <= -0.5565105974674225) ? ( (Feature_90 <= 0.7287018746137619) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) ) : ( (Feature_84 <= -1.0485740900039673) ? ( (Feature_85 <= 0.9519887706264853) ? ( 13 ) : ( 14 ) ) : ( 15 ) ) ) : ( (Feature_72 <= -0.9955059289932251) ? ( (Feature_50 <= -0.025953032076358795) ? ( 18 ) : ( (Feature_70 <= 1.5127062797546387) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_68 <= -1.1216784715652466) ? ( 23 ) : ( (Feature_63 <= 1.0354410409927368) ? ( (Feature_24 <= -1.6794065833091736) ? ( 26 ) : ( 27 ) ) : ( (Feature_42 <= -0.2587735503911972) ? ( 29 ) : ( 30 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_14 namespace SubModel_15 { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1, 2, 3 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 2 , {0.0, 0.0, 1.0, 0.0 }} , { 3 , {0.0, 1.0, 0.0, 0.0 }} , { 7 , {1.0, 0.0, 0.0, 0.0 }} , { 8 , {0.0, 1.0, 0.0, 0.0 }} , { 10 , {0.0, 1.0, 0.0, 0.0 }} , { 12 , {0.0, 0.0, 0.0, 1.0 }} , { 13 , {1.0, 0.0, 0.0, 0.0 }} , { 15 , {0.0, 1.0, 0.0, 0.0 }} , { 18 , {0.0, 1.0, 0.0, 0.0 }} , { 19 , {0.3333333333333333, 0.0, 0.5, 0.16666666666666666 }} , { 21 , {0.0, 0.0, 0.038461538461538464, 0.9615384615384616 }} , { 22 , {0.5, 0.5, 0.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_44 <= -2.0734068751335144) ? ( (Feature_48 <= 0.9457052946090698) ? ( 2 ) : ( 3 ) ) : ( (Feature_29 <= 0.022716662992024794) ? ( (Feature_9 <= -0.41657423973083496) ? ( (Feature_96 <= 1.575301468372345) ? ( 7 ) : ( 8 ) ) : ( (Feature_50 <= -1.501459538936615) ? ( 10 ) : ( (Feature_90 <= 0.12944400310516357) ? ( 12 ) : ( 13 ) ) ) ) : ( (Feature_8 <= -1.0347691178321838) ? ( 15 ) : ( (Feature_56 <= -3.686617374420166) ? ( (Feature_18 <= -0.11845160275697708) ? ( 18 ) : ( 19 ) ) : ( (Feature_88 <= 1.3707586526870728) ? ( 21 ) : ( 22 ) ) ) ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any(), std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ], lNodeValue [ 2 ], lNodeValue [ 3 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace SubModel_15 std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Score_2", "Score_3", "Proba_0", "Proba_1", "Proba_2", "Proba_3", "LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); std::vector<tTable> lTreeScores = { SubModel_0::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_1::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_2::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_3::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_4::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_5::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_6::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_7::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_8::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_9::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_10::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_11::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_12::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_13::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_14::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99), SubModel_15::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99) }; tTable lAggregatedTable = aggregate_bag_scores(lTreeScores, {"Proba", "Score"}); tTable lTable = lAggregatedTable; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace int main() { score_csv_file("outputs/ml2cpp-demo/datasets/FourClass_100.csv"); return 0; }
146.695765
2,839
0.70979
antoinecarme
ebf8fca698458856c4deef95982dd656690d4c50
1,682
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/any/cons/nontrivial.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/any/cons/nontrivial.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/20_util/any/cons/nontrivial.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// Copyright (C) 2015-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-options "-std=gnu++17" } #include <any> #include <testsuite_hooks.h> struct LocationAware { LocationAware() { } ~LocationAware() { VERIFY(self == this); } LocationAware(const LocationAware&) { } LocationAware& operator=(const LocationAware&) { return *this; } LocationAware(LocationAware&&) noexcept { } LocationAware& operator=(LocationAware&&) noexcept { return *this; } void* const self = this; }; static_assert(std::is_nothrow_move_constructible<LocationAware>::value, ""); static_assert(!std::is_trivially_copyable<LocationAware>::value, ""); using std::any; void test01() { LocationAware l; any a = l; } void test02() { LocationAware l; any a = l; any b = a; { any tmp = std::move(a); a = std::move(b); b = std::move(tmp); } } void test03() { LocationAware l; any a = l; any b = a; swap(a, b); } int main() { test01(); test02(); test03(); }
22.131579
76
0.684304
best08618
ebfd9f52b69f35ceb865206a613f9465517e9389
1,166
cpp
C++
AeSys/EoSelectCmd.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
1
2020-09-07T07:06:19.000Z
2020-09-07T07:06:19.000Z
AeSys/EoSelectCmd.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
null
null
null
AeSys/EoSelectCmd.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
2
2019-10-24T00:36:58.000Z
2020-09-30T16:45:56.000Z
#include "stdafx.h" #include "EoSelectCmd.h" #include "AeSysDoc.h" #include "AeSysView.h" #include <DbCommandContext.h> const OdString CommandSelect::groupName() const { return L"AeSys"; } const OdString CommandSelect::Name() { return L"SELECT"; } const OdString CommandSelect::globalName() const { return Name(); } void CommandSelect::execute(OdEdCommandContext* commandContext) { OdDbCommandContextPtr CommandContext(commandContext); OdDbDatabaseDocPtr Database {CommandContext->database()}; auto Document {Database->Document()}; auto View {Document->GetViewer()}; if (View == nullptr) { throw OdEdCancel(); } Document->OnEditClearSelection(); Document->UpdateAllViews(nullptr); auto UserIo {CommandContext->dbUserIO()}; UserIo->setPickfirst(nullptr); const auto SelectOptions {OdEd::kSelLeaveHighlighted | OdEd::kSelAllowEmpty}; try { OdDbSelectionSetPtr SelectionSet {UserIo->select(L"", SelectOptions, View->EditorObject().GetWorkingSelectionSet())}; View->EditorObject().SetWorkingSelectionSet(SelectionSet); } catch (const OdError&) { throw OdEdCancel(); } View->EditorObject().SelectionSetChanged(); Database->pageObjects(); }
28.439024
119
0.756432
terry-texas-us
ebff4a602701e56f0b58baaa1bb4b01018aa66f6
2,177
cpp
C++
dali-toolkit/public-api/controls/buttons/button.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
dali-toolkit/public-api/controls/buttons/button.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
dali-toolkit/public-api/controls/buttons/button.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2020 Samsung Electronics 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. * */ // CLASS HEADER #include <dali-toolkit/public-api/controls/buttons/button.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/public-api/object/property-map.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/buttons/button-impl.h> #include <dali-toolkit/public-api/controls/image-view/image-view.h> #include <dali-toolkit/public-api/visuals/text-visual-properties.h> namespace Dali { namespace Toolkit { Button::Button() { } Button::Button(const Button& button) = default; Button::Button(Button&& rhs) = default; Button& Button::operator=(const Button& button) = default; Button& Button::operator=(Button&& rhs) = default; Button::~Button() { } Button Button::DownCast(BaseHandle handle) { return Control::DownCast<Button, Internal::Button>(handle); } Button::ButtonSignalType& Button::PressedSignal() { return Dali::Toolkit::GetImplementation(*this).PressedSignal(); } Button::ButtonSignalType& Button::ReleasedSignal() { return Dali::Toolkit::GetImplementation(*this).ReleasedSignal(); } Button::ButtonSignalType& Button::ClickedSignal() { return Dali::Toolkit::GetImplementation(*this).ClickedSignal(); } Button::ButtonSignalType& Button::StateChangedSignal() { return Dali::Toolkit::GetImplementation(*this).StateChangedSignal(); } Button::Button(Internal::Button& implementation) : Control(implementation) { } Button::Button(Dali::Internal::CustomActor* internal) : Control(internal) { VerifyCustomActorPointer<Internal::Button>(internal); } } // namespace Toolkit } // namespace Dali
24.460674
75
0.748277
dalihub
23035442399b2d186798f79ffc59cc97b8bd9617
2,473
cpp
C++
src/lib/spirent_pga/scalar/checksum.cpp
ronanjs/openperf
55b759e399254547f8a6590b2e19cb47232265b7
[ "Apache-2.0" ]
null
null
null
src/lib/spirent_pga/scalar/checksum.cpp
ronanjs/openperf
55b759e399254547f8a6590b2e19cb47232265b7
[ "Apache-2.0" ]
null
null
null
src/lib/spirent_pga/scalar/checksum.cpp
ronanjs/openperf
55b759e399254547f8a6590b2e19cb47232265b7
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <cstdint> #include <numeric> #include <arpa/inet.h> #include "spirent_pga/common/headers.h" namespace scalar { inline uint32_t fold64(uint64_t sum) { sum = (sum >> 32) + (sum & 0xffffffff); sum += sum >> 32; return (static_cast<uint32_t>(sum)); } inline uint16_t fold32(uint32_t sum) { sum = (sum >> 16) + (sum & 0xffff); sum += sum >> 16; return (static_cast<uint16_t>(sum)); } void checksum_ipv4_headers(const uint8_t* ipv4_header_ptrs[], uint16_t count, uint32_t checksums[]) { std::transform(ipv4_header_ptrs, ipv4_header_ptrs + count, checksums, [](const uint8_t* ptr) { auto header = reinterpret_cast<const pga::headers::ipv4*>(ptr); uint64_t sum = header->data[0]; sum += header->data[1]; sum += header->data[2]; sum += header->data[3]; sum += header->data[4]; uint16_t csum = fold32(fold64(sum)); return (csum == 0xffff ? csum : (0xffff ^ csum)); }); } void checksum_ipv4_pseudoheaders(const uint8_t* ipv4_header_ptrs[], uint16_t count, uint32_t checksums[]) { std::transform( ipv4_header_ptrs, ipv4_header_ptrs + count, checksums, [](const uint8_t* ptr) { auto ipv4 = reinterpret_cast<const pga::headers::ipv4*>(ptr); auto pheader = pga::headers::ipv4_pseudo{ .src_address = ipv4->src_address, .dst_address = ipv4->dst_address, .zero = 0, .protocol = ipv4->protocol, .length = htons(static_cast<uint16_t>( ntohs(ipv4->length) - sizeof(pga::headers::ipv4)))}; uint64_t sum = pheader.data[0]; sum += pheader.data[1]; sum += pheader.data[2]; return (fold32(fold64(sum))); }); } uint32_t checksum_data_aligned(const uint32_t data[], uint16_t length) { uint64_t sum = std::accumulate( data, data + length, uint64_t{0}, [](const auto& left, const auto& right) { return (left + right); }); return (fold64(sum)); } } // namespace scalar
29.094118
76
0.506672
ronanjs
2309266fc602812e006f7a648963a6e9df1d4005
637
hpp
C++
test/include/cjdb/test/functional/rangecmp/is_equivalence.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
4
2019-03-02T01:09:07.000Z
2019-10-16T15:46:21.000Z
test/include/cjdb/test/functional/rangecmp/is_equivalence.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
5
2018-12-16T13:47:32.000Z
2019-10-13T01:27:11.000Z
test/include/cjdb/test/functional/rangecmp/is_equivalence.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
3
2020-06-08T18:27:28.000Z
2021-03-27T17:49:46.000Z
// Copyright (c) Christopher Di Bella. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #ifndef CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP #define CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP #include "cjdb/test/constexpr_check.hpp" #include "cjdb/test/functional/rangecmp/is_partial_equivalence.hpp" #include "cjdb/test/functional/rangecmp/is_reflexive.hpp" #define CHECK_IS_EQUIVALENCE(r, a, b, c) \ { \ CHECK_IS_PARTIAL_EQUIVALENCE(r, a, b, c); \ CHECK_IS_REFLEXIVE(r, a); \ } #endif // CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
35.388889
67
0.715856
cjdb
230a0b7c9d8bde4d8d0586c8a1610b8e9de5b569
8,913
cpp
C++
ros/src/computing/perception/detection/lidar_detector/packages/lidar_apollo_cnn_seg_detect/nodes/cnn_segmentation.cpp
baharkhabbazan/autoware
4285b539199af172faadba92bed887fdbb225472
[ "Apache-2.0" ]
20
2019-05-21T06:14:17.000Z
2021-11-03T04:36:09.000Z
ros/src/computing/perception/detection/lidar_detector/packages/lidar_apollo_cnn_seg_detect/nodes/cnn_segmentation.cpp
anhnv3991/autoware
d5b2ed9dc309193c8a2a7c77a2b6c88104c28328
[ "Apache-2.0" ]
18
2019-04-08T16:09:37.000Z
2019-06-05T15:24:40.000Z
ros/src/computing/perception/detection/lidar_detector/packages/lidar_apollo_cnn_seg_detect/nodes/cnn_segmentation.cpp
anhnv3991/autoware
d5b2ed9dc309193c8a2a7c77a2b6c88104c28328
[ "Apache-2.0" ]
8
2019-04-28T13:15:18.000Z
2021-06-03T07:05:16.000Z
/* * Copyright 2018-2019 Autoware Foundation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cnn_segmentation.h" CNNSegmentation::CNNSegmentation() : nh_() { } bool CNNSegmentation::init() { std::string proto_file; std::string weight_file; ros::NodeHandle private_node_handle("~");//to receive args if (private_node_handle.getParam("network_definition_file", proto_file)) { ROS_INFO("[%s] network_definition_file: %s", __APP_NAME__, proto_file.c_str()); } else { ROS_INFO("[%s] No Network Definition File was received. Finishing execution.", __APP_NAME__); return false; } if (private_node_handle.getParam("pretrained_model_file", weight_file)) { ROS_INFO("[%s] Pretrained Model File: %s", __APP_NAME__, weight_file.c_str()); } else { ROS_INFO("[%s] No Pretrained Model File was received. Finishing execution.", __APP_NAME__); return false; } private_node_handle.param<std::string>("points_src", topic_src_, "points_raw"); ROS_INFO("[%s] points_src: %s", __APP_NAME__, topic_src_.c_str()); private_node_handle.param<double>("range", range_, 60.); ROS_INFO("[%s] Pretrained Model File: %.2f", __APP_NAME__, range_); private_node_handle.param<double>("score_threshold", score_threshold_, 0.6); ROS_INFO("[%s] score_threshold: %.2f", __APP_NAME__, score_threshold_); private_node_handle.param<int>("width", width_, 512); ROS_INFO("[%s] width: %d", __APP_NAME__, width_); private_node_handle.param<int>("height", height_, 512); ROS_INFO("[%s] height: %d", __APP_NAME__, height_); private_node_handle.param<bool>("use_gpu", use_gpu_, false); ROS_INFO("[%s] use_gpu: %d", __APP_NAME__, use_gpu_); private_node_handle.param<int>("gpu_device_id", gpu_device_id_, 0); ROS_INFO("[%s] gpu_device_id: %d", __APP_NAME__, gpu_device_id_); /// Instantiate Caffe net if (!use_gpu_) { caffe::Caffe::set_mode(caffe::Caffe::CPU); } else { caffe::Caffe::SetDevice(gpu_device_id_); caffe::Caffe::set_mode(caffe::Caffe::GPU); caffe::Caffe::DeviceQuery(); } caffe_net_.reset(new caffe::Net<float>(proto_file, caffe::TEST)); caffe_net_->CopyTrainedLayersFrom(weight_file); std::string instance_pt_blob_name = "instance_pt"; instance_pt_blob_ = caffe_net_->blob_by_name(instance_pt_blob_name); CHECK(instance_pt_blob_ != nullptr) << "`" << instance_pt_blob_name << "` layer required"; std::string category_pt_blob_name = "category_score"; category_pt_blob_ = caffe_net_->blob_by_name(category_pt_blob_name); CHECK(category_pt_blob_ != nullptr) << "`" << category_pt_blob_name << "` layer required"; std::string confidence_pt_blob_name = "confidence_score"; confidence_pt_blob_ = caffe_net_->blob_by_name(confidence_pt_blob_name); CHECK(confidence_pt_blob_ != nullptr) << "`" << confidence_pt_blob_name << "` layer required"; std::string height_pt_blob_name = "height_pt"; height_pt_blob_ = caffe_net_->blob_by_name(height_pt_blob_name); CHECK(height_pt_blob_ != nullptr) << "`" << height_pt_blob_name << "` layer required"; std::string feature_blob_name = "data"; feature_blob_ = caffe_net_->blob_by_name(feature_blob_name); CHECK(feature_blob_ != nullptr) << "`" << feature_blob_name << "` layer required"; std::string class_pt_blob_name = "class_score"; class_pt_blob_ = caffe_net_->blob_by_name(class_pt_blob_name); CHECK(class_pt_blob_ != nullptr) << "`" << class_pt_blob_name << "` layer required"; cluster2d_.reset(new Cluster2D()); if (!cluster2d_->init(height_, width_, range_)) { ROS_ERROR("[%s] Fail to Initialize cluster2d for CNNSegmentation", __APP_NAME__); return false; } feature_generator_.reset(new FeatureGenerator()); if (!feature_generator_->init(feature_blob_.get())) { ROS_ERROR("[%s] Fail to Initialize feature generator for CNNSegmentation", __APP_NAME__); return false; } return true; } bool CNNSegmentation::segment(const pcl::PointCloud<pcl::PointXYZI>::Ptr &pc_ptr, const pcl::PointIndices &valid_idx, autoware_msgs::DetectedObjectArray &objects) { int num_pts = static_cast<int>(pc_ptr->points.size()); if (num_pts == 0) { ROS_INFO("[%s] Empty point cloud.", __APP_NAME__); return true; } feature_generator_->generate(pc_ptr); // network forward process caffe_net_->Forward(); #ifndef USE_CAFFE_GPU // caffe::Caffe::set_mode(caffe::Caffe::CPU); #else // int gpu_id = 0; // caffe::Caffe::SetDevice(gpu_id); // caffe::Caffe::set_mode(caffe::Caffe::GPU); // caffe::Caffe::DeviceQuery(); #endif // clutser points and construct segments/objects float objectness_thresh = 0.5; bool use_all_grids_for_clustering = true; cluster2d_->cluster(*category_pt_blob_, *instance_pt_blob_, pc_ptr, valid_idx, objectness_thresh, use_all_grids_for_clustering); cluster2d_->filter(*confidence_pt_blob_, *height_pt_blob_); cluster2d_->classify(*class_pt_blob_); float confidence_thresh = score_threshold_; float height_thresh = 0.5; int min_pts_num = 3; cluster2d_->getObjects(confidence_thresh, height_thresh, min_pts_num, objects, message_header_); return true; } void CNNSegmentation::test_run() { std::string in_pcd_file = "uscar_12_1470770225_1470770492_1349.pcd"; pcl::PointCloud<pcl::PointXYZI>::Ptr in_pc_ptr(new pcl::PointCloud<pcl::PointXYZI>); pcl::io::loadPCDFile(in_pcd_file, *in_pc_ptr); pcl::PointIndices valid_idx; auto &indices = valid_idx.indices; indices.resize(in_pc_ptr->size()); std::iota(indices.begin(), indices.end(), 0); autoware_msgs::DetectedObjectArray objects; init(); segment(in_pc_ptr, valid_idx, objects); } void CNNSegmentation::run() { init(); points_sub_ = nh_.subscribe(topic_src_, 1, &CNNSegmentation::pointsCallback, this); points_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("/detection/lidar_detector/points_cluster", 1); objects_pub_ = nh_.advertise<autoware_msgs::DetectedObjectArray>("/detection/lidar_detector/objects", 1); ROS_INFO("[%s] Ready. Waiting for data...", __APP_NAME__); } void CNNSegmentation::pointsCallback(const sensor_msgs::PointCloud2 &msg) { std::chrono::system_clock::time_point start, end; start = std::chrono::system_clock::now(); pcl::PointCloud<pcl::PointXYZI>::Ptr in_pc_ptr(new pcl::PointCloud<pcl::PointXYZI>); pcl::fromROSMsg(msg, *in_pc_ptr); pcl::PointIndices valid_idx; auto &indices = valid_idx.indices; indices.resize(in_pc_ptr->size()); std::iota(indices.begin(), indices.end(), 0); message_header_ = msg.header; autoware_msgs::DetectedObjectArray objects; objects.header = message_header_; segment(in_pc_ptr, valid_idx, objects); pubColoredPoints(objects); objects_pub_.publish(objects); end = std::chrono::system_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); } void CNNSegmentation::pubColoredPoints(const autoware_msgs::DetectedObjectArray &objects_array) { pcl::PointCloud<pcl::PointXYZRGB> colored_cloud; for (size_t object_i = 0; object_i < objects_array.objects.size(); object_i++) { // std::cout << "objct i" << object_i << std::endl; pcl::PointCloud<pcl::PointXYZI> object_cloud; pcl::fromROSMsg(objects_array.objects[object_i].pointcloud, object_cloud); int red = (object_i) % 256; int green = (object_i * 7) % 256; int blue = (object_i * 13) % 256; for (size_t i = 0; i < object_cloud.size(); i++) { // std::cout << "point i" << i << "/ size: "<<object_cloud.size() << std::endl; pcl::PointXYZRGB colored_point; colored_point.x = object_cloud[i].x; colored_point.y = object_cloud[i].y; colored_point.z = object_cloud[i].z; colored_point.r = red; colored_point.g = green; colored_point.b = blue; colored_cloud.push_back(colored_point); } } sensor_msgs::PointCloud2 output_colored_cloud; pcl::toROSMsg(colored_cloud, output_colored_cloud); output_colored_cloud.header = message_header_; points_pub_.publish(output_colored_cloud); }
34.546512
107
0.693481
baharkhabbazan
230bed5b01f64f1cb1089f71ac503d8567d45205
13,004
cpp
C++
src/reactive/http/request.cpp
ReactiveFramework/ReactiveFramework
c986f67cca10789e7a85e5a226c0cf7abb642698
[ "MIT" ]
null
null
null
src/reactive/http/request.cpp
ReactiveFramework/ReactiveFramework
c986f67cca10789e7a85e5a226c0cf7abb642698
[ "MIT" ]
null
null
null
src/reactive/http/request.cpp
ReactiveFramework/ReactiveFramework
c986f67cca10789e7a85e5a226c0cf7abb642698
[ "MIT" ]
1
2021-09-07T11:08:28.000Z
2021-09-07T11:08:28.000Z
/** * Reactive * * (c) 2015-2016 Axel Etcheverry * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include <string> #include <reactive/http/request.hpp> namespace reactive { namespace http { int request::on_message_begin(http_parser* parser_) { //request& r = *(static_cast<request*>(parser_->data)); //r.setComplete(false); //r.setHeadersComplete(false); return 0; } int request::on_message_complete(http_parser* parser_) { //request& r = *static_cast<request*>(parser_->data); //r.setComplete(true); // Force the parser to stop after the request is parsed so clients // can process the request (or response). This is to properly // handle HTTP/1.1 pipelined requests. //http_parser_pause(parser_, 1); return 0; } int request::on_header_field(http_parser* parser_, const char* data_, std::size_t size_) { request& r = *static_cast<request*>(parser_->data); if (!r.getCurrentValue().empty()) { process_header(r, r.getCurrentField(), r.getCurrentValue()); r.getCurrentField().clear(); r.getCurrentValue().clear(); } r.getCurrentField().append(data_, size_); return 0; } int request::on_header_value(http_parser* parser_, const char* data_, std::size_t size_) { request& r = *static_cast<request*>(parser_->data); r.getCurrentValue().append(data_, size_); return 0; } int request::on_headers_complete(http_parser* parser_) { request& r = *(static_cast<request*>(parser_->data)); if (!r.getCurrentValue().empty()) { process_header(r, r.getCurrentField(), r.getCurrentValue()); r.getCurrentField().clear(); r.getCurrentValue().clear(); } //r.setHeadersComplete(true); // Force the parser to stop after the headers are parsed so clients // can process the request (or response). This is to properly // handle HTTP/1.1 pipelined requests. //http_parser_pause(parser_, 1); return 0; } int request::on_url(http_parser* parser_, const char* data_, std::size_t size_) { std::string path; std::string query; bool is_path = true; for (std::size_t i = 0; i < size_; ++i) { char chr = data_[i]; if (is_path) { if (chr == '?') { is_path = false; continue; } path += chr; } else { query += chr; } } request& r = *static_cast<request*>(parser_->data); r.getUrl().setPath(path); if (!query.empty()) { r.getUrl().setQuery(query); } return 0; } int request::on_body(http_parser* parser_, const char* data_, std::size_t size_) { static_cast<request*>(parser_->data)->getContent().append(data_, size_); return 0; } void request::process_header(request& request_, const std::string& field_, const std::string& value_) { if (field_ == "Host") { request_.getUrl().setHost(value_); } else if (field_ == "User-Agent") { request_.setUserAgent(value_); } else if (field_ == "Cookie") { //@TODO convert this code in state machine parser std::vector<std::string> cookies; reactive::string::split(REACTIVE_HTTP_COOKIE_SEPARATOR, value_, cookies); for (std::size_t i = 0; i < cookies.size(); ++i) { std::vector<std::string> cookie_string; reactive::string::split("=", cookies.at(i), cookie_string); cookie_t cookie; cookie.name = reactive::uri::decode(cookie_string[0]); cookie.value = reactive::uri::decode(cookie_string[1]); cookie_string.clear(); request_.getCookies().add(cookie); } cookies.clear(); } else if (field_ == "X-Forwarded-For") { process_ip(request_, value_); } else if (field_ == "X-Client") { process_ip(request_, value_); } else if (field_ == "Content-Type") { request_.setContentType(value_); } request_.getHeaders().add(field_, value_); } void request::process_ip(request& request_, const std::string& ip_) { request_.info.by_proxy = true; request_.info.proxy_ip_version = request_.info.ip_version; request_.info.proxy_ip = request_.info.ip; request_.info.proxy_port = request_.info.port; std::size_t pos = ip_.find(","); request_.info.ip = ip_; if (pos != std::string::npos) { request_.info.ip = ip_.substr(0, pos); } try { boost::asio::ip::address ip_version = boost::asio::ip::address::from_string(request_.info.ip); if (ip_version.is_v4()) { request_.info.ip_version = reactive::net::ip::IPV4; } else if (ip_version.is_v6()) { request_.info.ip_version = reactive::net::ip::IPV6; } } catch (std::exception& e) { request_.info.ip_version = reactive::net::ip::UNDEFINED; //request_.info.by_proxy = false; } // In this process we have no port information request_.info.port.clear(); } request::request() { reset(); memset(&m_settings, 0, sizeof(m_settings)); // Setting state machine callbacks m_settings.on_message_begin = &request::on_message_begin; m_settings.on_message_complete = &request::on_message_complete; m_settings.on_header_field = &request::on_header_field; m_settings.on_header_value = &request::on_header_value; m_settings.on_headers_complete = &request::on_headers_complete; m_settings.on_url = &request::on_url; m_settings.on_body = &request::on_body; memset(&m_parser, 0, sizeof(m_parser)); http_parser_init(&m_parser, HTTP_REQUEST); m_parser.data = this; } request::~request() { // clear headers list getHeaders().clear(); // clear cookies list m_cookies.clear(); } void request::reset() { info.reset(); m_useragent = REACTIVE_HTTP_REQUEST_USER_AGENT; setVersion(protocol::VERSION_11); m_method = protocol::METHOD_GET; // Resetting content and its type setContent(""); m_content_type = ""; // unused undocumented variables //m_complete = false; //m_headers_complete = false; m_query.clear(); m_body.clear(); } std::size_t request::parse(const char* data_, std::size_t size_) { std::size_t parsed = 0; if (size_ > 0) { parsed = http_parser_execute(&m_parser, &m_settings, data_, size_); //if (parsed < size_) // LIMIT in reading is 80x1024 } //const http_errno errno = static_cast<http_errno>(m_parser.http_errno); // The 'on_message_complete' and 'on_headers_complete' callbacks fail // on purpose to force the parser to stop between pipelined requests. // This allows the clients to reliably detect the end of headers and // the end of the message. Make sure the parser is always unpaused // for the next call to 'feed'. /*if (herrno == HPE_PAUSED) { http_parser_pause(&m_parser, 0); }*/ /*if (used < size_) { if (herrno == HPE_PAUSED) { // Make sure the byte that triggered the pause // after the headers is properly processed. if (!m_complete) { used += http_parser_execute(&m_parser, &m_settings, data_+used, 1); } } else { throw (error(herrno)); } }*/ m_method = std::string(http_method_str((http_method)m_parser.method)); setVersion(std::to_string(m_parser.http_major) + "." + std::to_string(m_parser.http_minor)); if (!m_url.getQuery().empty()) { m_query.parse(m_url.getQuery()); } if (m_content_type == "application/x-www-form-urlencoded") { m_body.parse(getContent()); } return parsed; } bool request::hasQueryArgument(const std::string& key_) const { return m_query.has(key_); } bool request::hasBodyArgument(const std::string& key_) const { return m_body.has(key_); } bool request::shouldKeepAlive() const { return (http_should_keep_alive(const_cast<http_parser*>(&m_parser)) != 0); } const cookie_bag& request::getCookies() const { return m_cookies; } cookie_bag& request::getCookies() { return m_cookies; } void request::setMethod(const std::string& method_) { m_method = method_; } const std::string& request::getMethod() const { return m_method; } void request::setUserAgent(const std::string& useragent_) { m_useragent = useragent_; } const std::string& request::getUserAgent() const { return m_useragent; } void request::setUrl(reactive::uri::url& url_) { m_url = url_; } void request::setUrl(const std::string& url_) { m_url = reactive::uri::url(url_); } const reactive::uri::url& request::getUrl() const { return m_url; } reactive::uri::url& request::getUrl() { return m_url; } void request::setContentType(const std::string& type_) { std::size_t pos = type_.find(";"); if (pos != std::string::npos) { m_content_type = type_.substr(0, pos); } else { m_content_type = type_; } getHeaders().add("Content-Type", m_content_type); } /** * Get content type * * @return The string of content type */ const std::string& request::getContentType() const { return m_content_type; } bool request::isXmlHttpRequest() const { if (getHeaders().has("X-Requested-With") && getHeaders().get("X-Requested-With").value == "XMLHttpRequest") { return true; } return false; } reactive::uri::query request::getData() const { return m_body; } std::string request::toString() const { header_bag headers = getHeaders(); headers.add("Host", m_url.toString(reactive::uri::url::HOST | reactive::uri::url::PORT)); if (!headers.has("Cache-Control")) { headers.add("Cache-Control", "max-age=0"); } if (!headers.has("Accept")) { headers.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); } if (!headers.has("User-Agent")) { headers.add("User-Agent", m_useragent); } if (!headers.has("Accept-Charset")) { headers.add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"); } std::string reqstr = m_method + " " + m_url.toString(reactive::uri::url::PATH | reactive::uri::url::QUERY) + " HTTP/" + getVersion() + protocol::CRLF; // --- Constructing the cookie string std::string full_cookies; std::size_t count_cookie = m_cookies.size(); for (std::size_t i = 0; i < count_cookie; ++i) { std::string cookie; cookie.append(reactive::uri::encode(m_cookies.at(i).name)); cookie.append("="); cookie.append(reactive::uri::encode(m_cookies.at(i).value)); if (i != (count_cookie - 1)) { cookie.append(REACTIVE_HTTP_COOKIE_SEPARATOR); } full_cookies.append(cookie); } // --- Using the cookie string to build the header if (!full_cookies.empty()) { headers.add("Cookie", full_cookies); } // In HTTP/1.1 the default connection type is Keep-Alive // while it is not fully supported in HTTP/1.0 it does not matter. // // Anyway this default header is set during connection and not here //headers.add("Connection", "Keep-Alive"); reqstr.append(headers.toString() + protocol::CRLF); if (!getContent().empty()) { reqstr.append(getContent()); } return reqstr; } } // end of http namespace } // end of reactive namespace
28.208243
117
0.556521
ReactiveFramework
230d73f8f945d97a3783cedc26ae2c87222cc557
1,548
hpp
C++
include/boost/simd/constant/definition/thousand.hpp
nickporubsky/boost-simd-clone
b81dfcd9d6524a131ea714f1eebb5bb75adddcc7
[ "BSL-1.0" ]
5
2018-02-20T11:21:12.000Z
2019-11-12T13:45:09.000Z
include/boost/simd/constant/definition/thousand.hpp
nickporubsky/boost-simd-clone
b81dfcd9d6524a131ea714f1eebb5bb75adddcc7
[ "BSL-1.0" ]
null
null
null
include/boost/simd/constant/definition/thousand.hpp
nickporubsky/boost-simd-clone
b81dfcd9d6524a131ea714f1eebb5bb75adddcc7
[ "BSL-1.0" ]
2
2017-11-17T15:30:36.000Z
2018-03-01T02:06:25.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_CONSTANT_DEFINITION_THOUSAND_HPP_INCLUDED #define BOOST_SIMD_CONSTANT_DEFINITION_THOUSAND_HPP_INCLUDED #include <boost/simd/config.hpp> #include <boost/simd/detail/brigand.hpp> #include <boost/simd/detail/dispatch.hpp> #include <boost/simd/detail/constant_traits.hpp> #include <boost/simd/detail/dispatch/function/make_callable.hpp> #include <boost/simd/detail/dispatch/hierarchy/functions.hpp> #include <boost/simd/detail/dispatch/as.hpp> namespace boost { namespace simd { namespace tag { struct thousand_ : boost::dispatch::constant_value_<thousand_> { BOOST_DISPATCH_MAKE_CALLABLE(ext,thousand_,boost::dispatch::constant_value_<thousand_>); BOOST_SIMD_REGISTER_CONSTANT(1000, 0x447a0000UL, 0x408f400000000000ULL); }; } namespace ext { BOOST_DISPATCH_FUNCTION_DECLARATION(tag, thousand_) } namespace detail { BOOST_DISPATCH_CALLABLE_DEFINITION(tag::thousand_,thousand); } template<typename T> BOOST_FORCEINLINE auto Thousand() BOOST_NOEXCEPT_DECLTYPE(detail::thousand( boost::dispatch::as_<T>{})) { return detail::thousand( boost::dispatch::as_<T>{} ); } } } #endif
30.352941
100
0.663437
nickporubsky
231844adbf30c001bf10c931c6edabf567b8d2d1
5,669
cpp
C++
Code/BBearEditor/Engine/Utils/BBUtils.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
1
2021-09-01T08:19:34.000Z
2021-09-01T08:19:34.000Z
Code/BBearEditor/Engine/Utils/BBUtils.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/Utils/BBUtils.cpp
lishangdian/BBearEditor-2.0
1f4b463ef756ed36cc15d10abae822efc400c4d7
[ "MIT" ]
null
null
null
#include "BBUtils.h" #include <QDir> #include <QProcess> #include "FileSystem/BBFileListWidget.h" #include <GL/gl.h> QString BBConstant::BB_NAME_PROJECT = ""; QString BBConstant::BB_PATH_PROJECT = ""; // there is no / at the end QString BBConstant::BB_PATH_PROJECT_ENGINE = ""; QString BBConstant::BB_PATH_PROJECT_USER = ""; QString BBConstant::BB_NAME_FILE_SYSTEM_USER = "contents"; QString BBConstant::BB_NAME_FILE_SYSTEM_ENGINE = "engine"; QString BBConstant::BB_NAME_OVERVIEW_MAP = "overview map.jpg"; QString BBConstant::BB_NAME_DEFAULT_SCENE = "new scene.bbscene"; QString BBConstant::BB_NAME_DEFAULT_MATERIAL = "new material.bbmtl"; QVector3D BBConstant::m_Red = QVector3D(0.937255f, 0.378431f, 0.164706f); QVector4D BBConstant::m_RedTransparency = QVector4D(0.937255f, 0.378431f, 0.164706f, 0.7f); QVector3D BBConstant::m_Green = QVector3D(0.498039f, 0.827451f, 0.25098f); QVector4D BBConstant::m_GreenTransparency = QVector4D(0.498039f, 0.827451f, 0.25098f, 0.7f); QVector3D BBConstant::m_Blue = QVector3D(0.341176f, 0.662745f, 1.0f); QVector4D BBConstant::m_BlueTransparency = QVector4D(0.341176f, 0.662745f, 1.0f, 0.7f); QVector3D BBConstant::m_Yellow = QVector3D(1.0f, 1.0f, 0.305882f); QVector3D BBConstant::m_Gray = QVector3D(0.8f, 0.8f, 0.8f); QVector4D BBConstant::m_GrayTransparency = QVector4D(0.8f, 0.8f, 0.8f, 0.7f); //QVector3D BBConstant::m_Red = QVector3D(0.909804f, 0.337255f, 0.333333f); //QVector4D BBConstant::m_RedTransparency = QVector4D(0.909804f, 0.337255f, 0.333333f, 0.5f); //QVector3D BBConstant::m_Green = QVector3D(0.356863f, 0.729412f, 0.619608f); //QVector4D BBConstant::m_GreenTransparency = QVector4D(0.356863f, 0.729412f, 0.619608f, 0.5f); //QVector3D BBConstant::m_Blue = QVector3D(0.384314f, 0.631373f, 0.847059f); //QVector4D BBConstant::m_BlueTransparency = QVector4D(0.384314f, 0.631373f, 0.847059f, 0.5f); //QVector3D BBConstant::m_Yellow = QVector3D(0.847059f, 0.603922f, 0.309804f); QVector3D BBConstant::m_OrangeRed = QVector3D(0.909804f, 0.337255f, 0.333333f); char *BBUtils::loadFileContent(const char *filePath, int &nFileSize) { FILE *pFile = NULL; char *pData = NULL; // Read files by binary mode // path.toLatin1().data(); will cause Chinese garbled do{ pFile = fopen(filePath, "rb"); BB_PROCESS_ERROR(pFile); // Seek the pointer to the end of the file BB_PROCESS_ERROR(BB_SUCCEEDED(fseek(pFile, 0, SEEK_END))); // Get the size of the file size_t length = ftell(pFile); BB_PROCESS_ERROR(length); // Seek to the beginning of the file BB_PROCESS_ERROR(BB_SUCCEEDED(fseek(pFile, 0, SEEK_SET))); // +1 Terminator pData = new char[length + 1]; BB_PROCESS_ERROR(pData); // 1*length is the size of the file to be read BB_PROCESS_ERROR(fread(pData, 1, length, pFile)); // Terminator pData[length] = 0; nFileSize = length; }while(0); if (pFile) fclose(pFile); return pData; } bool BBUtils::saveToFile(const char *pFilePath, void *pBuffer, int nSize) { FILE *pFile = fopen(pFilePath, "wb"); BB_PROCESS_ERROR_RETURN_FALSE(pFile); fwrite(pBuffer, sizeof(char), nSize, pFile); fclose(pFile); return true; } unsigned char* BBUtils::decodeBMP(unsigned char *pBmpFileData, int &nWidth, int &nHeight) { // Is it a bitmap file if (0x4D42 == *((unsigned short*)pBmpFileData)) { int nPixelDataOffset = *((int*)(pBmpFileData + 10)); nWidth = *((int*)(pBmpFileData + 18)); nHeight = *((int*)(pBmpFileData + 22)); unsigned char *pPixelData = pBmpFileData + nPixelDataOffset; // be saved as BGR, but opengl support RGB, exchange B with R // bmp does not support alpha for (int i = 0; i < nWidth * nHeight * 3; i += 3) { unsigned char temp = pPixelData[i]; pPixelData[i] = pPixelData[i + 2]; pPixelData[i + 2] = temp; } return pPixelData; } return nullptr; } QString BBUtils::getBaseName(const QString &name) { return name.mid(0, name.lastIndexOf('.')); } QString BBUtils::getPathRelativeToExecutionDirectory(const QString &absolutePath) { QDir dir(QDir::currentPath()); return dir.relativeFilePath(absolutePath); } unsigned int BBUtils::getBlendFunc(int nIndex) { unsigned int func = GL_ZERO; switch (nIndex) { case 0: func = GL_ZERO; break; case 1: func = GL_ONE; break; case 2: func = GL_SRC_COLOR; break; case 3: func = GL_ONE_MINUS_SRC_COLOR; break; case 4: func = GL_SRC_ALPHA; break; case 5: func = GL_ONE_MINUS_SRC_ALPHA; break; case 6: func = GL_DST_ALPHA; break; case 7: func = GL_ONE_MINUS_DST_ALPHA; break; default: break; } return func; } QString BBUtils::getBlendFuncName(unsigned int func) { QString name; switch (func) { case GL_ZERO: name = "GL_ZERO"; break; case GL_ONE: name = "GL_ONE"; break; case GL_SRC_COLOR: name = "GL_SRC_COLOR"; break; case GL_ONE_MINUS_SRC_COLOR: name = "GL_ONE_MINUS_SRC_COLOR"; break; case GL_SRC_ALPHA: name = "GL_SRC_ALPHA"; break; case GL_ONE_MINUS_SRC_ALPHA: name = "GL_ONE_MINUS_SRC_ALPHA"; break; case GL_DST_ALPHA: name = "GL_DST_ALPHA"; break; case GL_ONE_MINUS_DST_ALPHA: name = "GL_ONE_MINUS_DST_ALPHA"; break; default: break; } return name; }
30.978142
95
0.652672
lishangdian
231bebc432243dd3f9569ff093363b854aa9edd8
8,492
cpp
C++
Sources/Display/Font/font.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/Display/Font/font.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
Sources/Display/Font/font.cpp
ValtoFrameworks/ClanLib
2d6b59386ce275742653b354a1daab42cab7cb3e
[ "Linux-OpenIB" ]
null
null
null
/* ** ClanLib SDK ** Copyright (c) 1997-2016 The ClanLib Team ** ** 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. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl */ #include "Display/precomp.h" #include "API/Display/Font/font.h" #include "API/Display/Font/font_metrics.h" #include "API/Display/Font/font_description.h" #include "API/Display/TargetProviders/graphic_context_provider.h" #include "API/Core/IOData/path_help.h" #include "API/Core/Text/string_help.h" #include "API/Core/Text/string_format.h" #include "API/Core/Text/utf8_reader.h" #include "API/Display/2D/canvas.h" #include "API/Display/Resources/display_cache.h" #include "font_impl.h" namespace clan { Font::Font() { } Font::Font(FontFamily &font_family, float height) { font_family.throw_if_null(); FontDescription desc; desc.set_height(height); *this = Font(font_family, desc); } Font::Font(FontFamily &font_family, const FontDescription &desc) { impl = std::make_shared<Font_Impl>(font_family, desc); } Font::Font(const std::string &typeface_name, float height) { FontDescription desc; desc.set_height(height); *this = Font(typeface_name, desc); } Font::Font(const std::string &typeface_name, const FontDescription &desc) { FontFamily font_family(typeface_name); *this = Font(font_family, desc); } Font::Font(const FontDescription &desc, const std::string &ttf_filename) { std::string path = PathHelp::get_fullpath(ttf_filename, PathHelp::path_type_file); std::string new_filename = PathHelp::get_filename(ttf_filename, PathHelp::path_type_file); FileSystem vfs(path); FontFamily font_family(new_filename); font_family.add(desc, new_filename, vfs); impl = std::make_shared<Font_Impl>(font_family, desc); } Font::Font(const FontDescription &desc, const std::string &ttf_filename, FileSystem fs) { std::string new_filename = PathHelp::get_filename(ttf_filename, PathHelp::path_type_file); FontFamily font_family(new_filename); font_family.add(desc, ttf_filename, fs); impl = std::make_shared<Font_Impl>(font_family, desc); } Font::Font(Canvas &canvas, const std::string &typeface_name, Sprite &sprite, const std::string &glyph_list, float spacelen, bool monospace, const FontMetrics &metrics) { FontDescription desc; desc.set_height(metrics.get_height()); FontFamily font_family(typeface_name); font_family.add(canvas, sprite, glyph_list, spacelen, monospace, metrics); impl = std::make_shared<Font_Impl>(font_family, desc); } Resource<Font> Font::resource(Canvas &canvas, const std::string &family_name, const FontDescription &desc, const ResourceManager &resources) { return DisplayCache::get(resources).get_font(canvas, family_name, desc); } void Font::throw_if_null() const { if (!impl) throw Exception("Font is null"); } void Font::set_height(float value) { if (impl) impl->set_height(value); } void Font::set_weight(FontWeight value) { if (impl) impl->set_weight(value); } void Font::set_line_height(float height) { if (impl) impl->set_line_height(height); } void Font::set_style(FontStyle style) { if (impl) impl->set_style(style); } void Font::set_scalable(float height_threshold) { if (impl) impl->set_scalable(height_threshold); } GlyphMetrics Font::get_metrics(Canvas &canvas, unsigned int glyph) const { if (impl) return impl->get_metrics(canvas, glyph); return GlyphMetrics(); } GlyphMetrics Font::measure_text(Canvas &canvas, const std::string &string) const { if (impl) return impl->measure_text(canvas, string); return GlyphMetrics(); } size_t Font::clip_from_left(Canvas &canvas, const std::string &text, float width) const { float x = 0.0f; UTF8_Reader reader(text.data(), text.length()); while (!reader.is_end()) { unsigned int glyph = reader.get_char(); GlyphMetrics char_abc = get_metrics(canvas, glyph); if (x + char_abc.advance.width > width) return reader.get_position(); x += char_abc.advance.width; reader.next(); } return text.size(); } size_t Font::clip_from_right(Canvas &canvas, const std::string &text, float width) const { float x = 0.0f; UTF8_Reader reader(text.data(), text.length()); reader.set_position(text.length()); while (reader.get_position() != 0) { reader.prev(); unsigned int glyph = reader.get_char(); GlyphMetrics char_abc = get_metrics(canvas, glyph); if (x + char_abc.advance.width > width) { reader.next(); return reader.get_position(); } x += char_abc.advance.width; } return 0; } void Font::draw_text(Canvas &canvas, const Pointf &position, const std::string &text, const Colorf &color) { if (impl) { impl->draw_text(canvas, position, text, color); } } std::string Font::get_clipped_text(Canvas &canvas, const Sizef &box_size, const std::string &text, const std::string &ellipsis_text) const { std::string out_string; out_string.reserve(text.length()); if (impl) { Pointf pos; FontMetrics fm = get_font_metrics(canvas); float descent = fm.get_descent(); float line_spacing = fm.get_line_height(); std::vector<std::string> lines = StringHelp::split_text(text, "\n", false); for (std::vector<std::string>::size_type i = 0; i < lines.size(); i++) { if (i == 0 || pos.y + descent < box_size.height) { Sizef size = measure_text(canvas, lines[i]).bbox_size; if (pos.x + size.width <= box_size.width) { if (!out_string.empty()) out_string += "\n"; out_string += lines[i]; } else { Sizef ellipsis = measure_text(canvas, ellipsis_text).bbox_size; int seek_start = 0; int seek_end = lines[i].size(); int seek_center = (seek_start + seek_end) / 2; UTF8_Reader utf8_reader(lines[i].data(), lines[i].length()); while (true) { utf8_reader.set_position(seek_center); utf8_reader.move_to_leadbyte(); if (seek_center != utf8_reader.get_position()) utf8_reader.next(); seek_center = utf8_reader.get_position(); if (seek_center == seek_end) break; utf8_reader.set_position(seek_start); utf8_reader.next(); if (utf8_reader.get_position() == seek_end) break; Sizef text_size = measure_text(canvas, lines[i].substr(0, seek_center)).bbox_size; if (pos.x + text_size.width + ellipsis.width >= box_size.width) seek_end = seek_center; else seek_start = seek_center; seek_center = (seek_start + seek_end) / 2; } if (!out_string.empty()) out_string += "\n"; out_string += lines[i].substr(0, seek_center) + ellipsis_text; } pos.y += line_spacing; } } } return out_string; } FontMetrics Font::get_font_metrics(Canvas &canvas) const { if (impl) return impl->get_font_metrics(canvas); return FontMetrics(); } int Font::get_character_index(Canvas &canvas, const std::string &text, const Pointf &point) const { if (impl) return impl->get_character_index(canvas, text, point); return 0; } std::vector<Rectf> Font::get_character_indices(Canvas &canvas, const std::string &text) const { if (impl) return impl->get_character_indices(canvas, text); return std::vector<Rectf>(); } FontHandle *Font::get_handle(Canvas &canvas) { if (impl) return impl->get_handle(canvas); return nullptr; } FontHandle::~FontHandle() { } FontDescription Font::get_description() const { if (impl) return impl->get_description(); return FontDescription(); } }
26.788644
168
0.693005
ValtoFrameworks
2322c13f90bef22a89b54712c0a482e5fa3f524d
736
hpp
C++
include/Player.hpp
esweet431/Cnake
faaaea177d26070fd6c1cd664222d4041ecc7bec
[ "MIT" ]
3
2019-10-15T04:16:29.000Z
2019-10-19T03:55:39.000Z
include/Player.hpp
esweet431/Cnake
faaaea177d26070fd6c1cd664222d4041ecc7bec
[ "MIT" ]
5
2019-05-16T06:59:48.000Z
2019-10-13T06:09:59.000Z
include/Player.hpp
esweet431/Cnake
faaaea177d26070fd6c1cd664222d4041ecc7bec
[ "MIT" ]
2
2020-02-14T18:27:35.000Z
2021-07-08T20:41:21.000Z
#pragma once #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <vector> #include <mutex> enum Direction { Up, Right, Down, Left }; class Player : public sf::Drawable { public: // Constructor Player(const std::map<std::string, sf::Texture>&, std::mutex*); // Destructor ~Player(); // Setters void processKeys(sf::Keyboard::Key); // Getters sf::Vector2f getHeadPos(); // Processors void movePlayer(); void addPart(); bool safeCheck(sf::RectangleShape&, sf::Text&, sf::Sound&, sf::Sound&); private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::vector<sf::RectangleShape> snakeBody; Direction m_dir; Direction m_lastDir; std::mutex* mu; int playerScore; };
19.368421
76
0.702446
esweet431
2323218e955ff7679ccea944280d0866e90fd87d
21,503
cpp
C++
src/assembler/RhsAssembler.cpp
ldXiao/polyfem
d4103af16979ff67d461a9ebe46a14bbc4dc8c7c
[ "MIT" ]
null
null
null
src/assembler/RhsAssembler.cpp
ldXiao/polyfem
d4103af16979ff67d461a9ebe46a14bbc4dc8c7c
[ "MIT" ]
null
null
null
src/assembler/RhsAssembler.cpp
ldXiao/polyfem
d4103af16979ff67d461a9ebe46a14bbc4dc8c7c
[ "MIT" ]
null
null
null
#include <polyfem/RhsAssembler.hpp> #include <polyfem/BoundarySampler.hpp> #include <polyfem/LinearSolver.hpp> // #include <polyfem/UIState.hpp> #include <polyfem/Logger.hpp> #include <Eigen/Sparse> #ifdef USE_TBB #include <tbb/parallel_for.h> #include <tbb/task_scheduler_init.h> #include <tbb/enumerable_thread_specific.h> #endif #include <iostream> #include <map> #include <memory> namespace polyfem { namespace { class LocalThreadScalarStorage { public: double val; ElementAssemblyValues vals; LocalThreadScalarStorage() { val = 0; } }; } RhsAssembler::RhsAssembler(const Mesh &mesh, const int n_basis, const int size, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const std::string &formulation, const Problem &problem) : mesh_(mesh), n_basis_(n_basis), size_(size), bases_(bases), gbases_(gbases), formulation_(formulation), problem_(problem) { } void RhsAssembler::assemble(Eigen::MatrixXd &rhs, const double t) const { rhs = Eigen::MatrixXd::Zero(n_basis_ * size_, 1); if(!problem_.is_rhs_zero()) { Eigen::MatrixXd rhs_fun; const int n_elements = int(bases_.size()); ElementAssemblyValues vals; for(int e = 0; e < n_elements; ++e) { vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]); const Quadrature &quadrature = vals.quadrature; problem_.rhs(formulation_, vals.val, t, rhs_fun); for(int d = 0; d < size_; ++d) rhs_fun.col(d) = rhs_fun.col(d).array() * vals.det.array() * quadrature.weights.array(); const int n_loc_bases_ = int(vals.basis_values.size()); for(int i = 0; i < n_loc_bases_; ++i) { const AssemblyValues &v = vals.basis_values[i]; for(int d = 0; d < size_; ++d) { const double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum(); for(std::size_t ii = 0; ii < v.global.size(); ++ii) rhs(v.global[ii].index*size_+d) += rhs_value * v.global[ii].val; } } } } } void RhsAssembler::initial_solution(Eigen::MatrixXd &sol) const { time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_solution(pts, val);}, sol); } void RhsAssembler::initial_velocity(Eigen::MatrixXd &sol) const { time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_velocity(pts, val);}, sol); } void RhsAssembler::initial_acceleration(Eigen::MatrixXd &sol) const { time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_acceleration(pts, val);}, sol); } void RhsAssembler::time_bc(const std::function<void(const Eigen::MatrixXd&, Eigen::MatrixXd&)> &fun,Eigen::MatrixXd &sol) const { sol = Eigen::MatrixXd::Zero(n_basis_ * size_, 1); Eigen::MatrixXd loc_sol; const int n_elements = int(bases_.size()); ElementAssemblyValues vals; for(int e = 0; e < n_elements; ++e) { vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]); const Quadrature &quadrature = vals.quadrature; //problem_.initial_solution(vals.val, loc_sol); fun(vals.val, loc_sol); for(int d = 0; d < size_; ++d) loc_sol.col(d) = loc_sol.col(d).array() * vals.det.array() * quadrature.weights.array(); const int n_loc_bases_ = int(vals.basis_values.size()); for(int i = 0; i < n_loc_bases_; ++i) { const AssemblyValues &v = vals.basis_values[i]; for(int d = 0; d < size_; ++d) { const double sol_value = (loc_sol.col(d).array() * v.val.array()).sum(); for(std::size_t ii = 0; ii < v.global.size(); ++ii) sol(v.global[ii].index*size_+d) += sol_value * v.global[ii].val; } } } } void RhsAssembler::set_bc( const std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &df, const std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &nf, const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs) const { const int n_el=int(bases_.size()); Eigen::MatrixXd uv, samples, gtmp, rhs_fun; Eigen::VectorXi global_primitive_ids; int index = 0; std::vector<int> indices; indices.reserve(n_el*10); // std::map<int, int> global_index_to_col; long total_size = 0; Eigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_); is_boundary.setConstant(false); Eigen::VectorXi global_index_to_col(n_basis_); global_index_to_col.setConstant(-1); const int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension(); // assert((bounday_nodes.size()/actual_dim)*actual_dim == bounday_nodes.size()); for(int b : bounday_nodes) is_boundary[b/actual_dim] = true; for(const auto &lb : local_boundary) { const int e = lb.element_id(); bool has_samples = sample_boundary(lb, resolution, true, uv, samples, global_primitive_ids); if(!has_samples) continue; const ElementBases &bs = bases_[e]; const int n_local_bases = int(bs.bases.size()); total_size += samples.rows(); for(int j = 0; j < n_local_bases; ++j) { const Basis &b=bs.bases[j]; for(std::size_t ii = 0; ii < b.global().size(); ++ii) { //pt found // if(std::find(bounday_nodes.begin(), bounday_nodes.end(), size_ * b.global()[ii].index) != bounday_nodes.end()) if(is_boundary[b.global()[ii].index]) { //if(global_index_to_col.find( b.global()[ii].index ) == global_index_to_col.end()) if(global_index_to_col(b.global()[ii].index) == -1) { // global_index_to_col[b.global()[ii].index] = index++; global_index_to_col(b.global()[ii].index) = index++; indices.push_back(b.global()[ii].index); assert(indices.size() == size_t(index)); } } } } } // Eigen::MatrixXd global_mat = Eigen::MatrixXd::Zero(total_size, indices.size()); Eigen::MatrixXd global_rhs = Eigen::MatrixXd::Zero(total_size, size_); const long buffer_size = total_size * long(indices.size()); std::vector< Eigen::Triplet<double> > entries, entries_t; // entries.reserve(buffer_size); // entries_t.reserve(buffer_size); index = 0; int global_counter = 0; Eigen::MatrixXd mapped; std::vector<AssemblyValues> tmp_val; for(const auto &lb : local_boundary) { const int e = lb.element_id(); bool has_samples = sample_boundary(lb, resolution, false, uv, samples, global_primitive_ids); if(!has_samples) continue; const ElementBases &bs = bases_[e]; const ElementBases &gbs = gbases_[e]; const int n_local_bases = int(bs.bases.size()); gbs.eval_geom_mapping(samples, mapped); bs.evaluate_bases(samples, tmp_val); for(int j = 0; j < n_local_bases; ++j) { const Basis &b=bs.bases[j]; const auto &tmp = tmp_val[j].val; for(std::size_t ii = 0; ii < b.global().size(); ++ii) { // auto item = global_index_to_col.find(b.global()[ii].index); // if(item != global_index_to_col.end()){ auto item = global_index_to_col(b.global()[ii].index); if(item != -1){ for(int k = 0; k < int(tmp.size()); ++k) { // entries.push_back(Eigen::Triplet<double>(global_counter+k, item->second, tmp(k, j) * b.global()[ii].val)); // entries_t.push_back(Eigen::Triplet<double>(item->second, global_counter+k, tmp(k, j) * b.global()[ii].val)); entries.push_back(Eigen::Triplet<double>(global_counter+k, item, tmp(k) * b.global()[ii].val)); entries_t.push_back(Eigen::Triplet<double>(item, global_counter+k, tmp(k) * b.global()[ii].val)); } // global_mat.block(global_counter, item->second, tmp.size(), 1) = tmp; } } } // problem_.bc(mesh_, global_primitive_ids, mapped, t, rhs_fun); df(global_primitive_ids, uv, mapped, rhs_fun); global_rhs.block(global_counter, 0, rhs_fun.rows(), rhs_fun.cols()) = rhs_fun; global_counter += rhs_fun.rows(); //UIState::ui_state().debug_data().add_points(mapped, Eigen::MatrixXd::Constant(1, 3, 0)); //Eigen::MatrixXd asd(mapped.rows(), 3); //asd.col(0)=mapped.col(0); //asd.col(1)=mapped.col(1); //asd.col(2)=rhs_fun; //UIState::ui_state().debug_data().add_points(asd, Eigen::MatrixXd::Constant(1, 3, 0)); } assert(global_counter == total_size); if(total_size > 0) { const double mmin = global_rhs.minCoeff(); const double mmax = global_rhs.maxCoeff(); if(fabs(mmin) < 1e-8 && fabs(mmax) < 1e-8) { // std::cout<<"is all zero, skipping"<<std::endl; for(size_t i = 0; i < indices.size(); ++i){ for(int d = 0; d < size_; ++d){ if(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end()) rhs(indices[i]*size_+d) = 0; } } } else { StiffnessMatrix mat(int(total_size), int(indices.size())); mat.setFromTriplets(entries.begin(), entries.end()); StiffnessMatrix mat_t(int(indices.size()), int(total_size)); mat_t.setFromTriplets(entries_t.begin(), entries_t.end()); StiffnessMatrix A = mat_t * mat; Eigen::MatrixXd b = mat_t * global_rhs; Eigen::MatrixXd coeffs(b.rows(), b.cols()); json params = { {"mtype", -2}, // matrix type for Pardiso (2 = SPD) // {"max_iter", 0}, // for iterative solvers // {"tolerance", 1e-9}, // for iterative solvers }; // auto solver = LinearSolver::create("", ""); auto solver = LinearSolver::create(LinearSolver::defaultSolver(), LinearSolver::defaultPrecond()); solver->setParameters(params); solver->analyzePattern(A); solver->factorize(A); for(long i = 0; i < b.cols(); ++i){ solver->solve(b.col(i), coeffs.col(i)); } logger().trace("RHS solve error {}", (A*coeffs-b).norm()); for(long i = 0; i < coeffs.rows(); ++i){ for(int d = 0; d < size_; ++d){ if(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end()) rhs(indices[i]*size_+d) = coeffs(i, d); } } } } //Neumann Eigen::MatrixXd points; Eigen::VectorXd weights; ElementAssemblyValues vals; for(const auto &lb : local_neumann_boundary) { const int e = lb.element_id(); bool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids); if(!has_samples) continue; const ElementBases &gbs = gbases_[e]; const ElementBases &bs = bases_[e]; vals.compute(e, mesh_.is_volume(), points, bs, gbs); // problem_.neumann_bc(mesh_, global_primitive_ids, vals.val, t, rhs_fun); nf(global_primitive_ids, uv, vals.val, rhs_fun); // UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(0,1,0)); for(int d = 0; d < size_; ++d) rhs_fun.col(d) = rhs_fun.col(d).array() * weights.array(); for(int i = 0; i < lb.size(); ++i) { const int primitive_global_id = lb.global_primitive_id(i); const auto nodes = bs.local_nodes_for_primitive(primitive_global_id, mesh_); for(long n = 0; n < nodes.size(); ++n) { // const auto &b = bs.bases[nodes(n)]; const AssemblyValues &v = vals.basis_values[nodes(n)]; for(int d = 0; d < size_; ++d) { const double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum(); for(size_t g = 0; g < v.global.size(); ++g) { const int g_index = v.global[g].index*size_+d; const bool is_neumann = std::find(bounday_nodes.begin(), bounday_nodes.end(), g_index ) == bounday_nodes.end(); if(is_neumann){ rhs(g_index) += rhs_value * v.global[g].val; // UIState::ui_state().debug_data().add_points(v.global[g].node, Eigen::RowVector3d(1,0,0)); } // else // std::cout<<"skipping "<<g_index<<" "<<rhs_value * v.global[g].val<<std::endl; } } } } } } void RhsAssembler::set_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const { set_bc( [&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.bc(mesh_, global_ids, uv, pts, t, val);}, [&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_bc(mesh_, global_ids, uv, pts, t, val);}, local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs); } void RhsAssembler::set_velocity_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const { set_bc( [&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.velocity_bc(mesh_, global_ids, uv, pts, t, val);}, [&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_velocity_bc(mesh_, global_ids, uv, pts, t, val);}, local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs); } void RhsAssembler::set_acceleration_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const { set_bc( [&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.acceleration_bc(mesh_, global_ids, uv, pts, t, val);}, [&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_acceleration_bc(mesh_, global_ids, uv, pts, t, val);}, local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs); } void RhsAssembler::compute_energy_grad(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, const Eigen::MatrixXd &final_rhs, const double t, Eigen::MatrixXd &rhs) const { if(problem_.is_linear_in_time()){ if(problem_.is_time_dependent()) rhs = final_rhs; else rhs = final_rhs * t; } else { assemble(rhs, t); rhs *= -1; set_bc(local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs, t); } } double RhsAssembler::compute_energy(const Eigen::MatrixXd &displacement, const std::vector< LocalBoundary > &local_neumann_boundary, const int resolution, const double t) const { Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_); double res = 0; Eigen::MatrixXd forces; if(!problem_.is_rhs_zero()) { #ifdef USE_TBB typedef tbb::enumerable_thread_specific< LocalThreadScalarStorage > LocalStorage; LocalStorage storages((LocalThreadScalarStorage())); #else LocalThreadScalarStorage loc_storage; #endif const int n_bases = int(bases_.size()); #ifdef USE_TBB tbb::parallel_for( tbb::blocked_range<int>(0, n_bases), [&](const tbb::blocked_range<int> &r) { LocalStorage::reference loc_storage = storages.local(); for (int e = r.begin(); e != r.end(); ++e) { #else for(int e=0; e < n_bases; ++e) { #endif ElementAssemblyValues &vals = loc_storage.vals; vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]); const Quadrature &quadrature = vals.quadrature; const Eigen::VectorXd da = vals.det.array() * quadrature.weights.array(); problem_.rhs(formulation_, vals.val, t, forces); assert(forces.rows() == da.size()); assert(forces.cols() == size_); for(long p = 0; p < da.size(); ++p) { local_displacement.setZero(); for(size_t i = 0; i < vals.basis_values.size(); ++i) { const auto &bs = vals.basis_values[i]; assert(bs.val.size() == da.size()); const double b_val = bs.val(p); for(int d = 0; d < size_; ++d) { for(std::size_t ii = 0; ii < bs.global.size(); ++ii) { local_displacement(d) += (bs.global[ii].val * b_val) * displacement(bs.global[ii].index*size_ + d); } } } for(int d = 0; d < size_; ++d) loc_storage.val += forces(p, d) * local_displacement(d) * da(p); // res += forces(p, d) * local_displacement(d) * da(p); } #ifdef USE_TBB }}); #else } #endif #ifdef USE_TBB for (LocalStorage::iterator i = storages.begin(); i != storages.end(); ++i) { res += i->val; } #else res = loc_storage.val; #endif } ElementAssemblyValues vals; //Neumann Eigen::MatrixXd points, uv; Eigen::VectorXd weights; Eigen::VectorXi global_primitive_ids; for(const auto &lb : local_neumann_boundary) { const int e = lb.element_id(); bool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids); if(!has_samples) continue; const ElementBases &gbs = gbases_[e]; const ElementBases &bs = bases_[e]; vals.compute(e, mesh_.is_volume(), points, bs, gbs); problem_.neumann_bc(mesh_, global_primitive_ids, uv, vals.val, t, forces); // UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(1,0,0)); for(long p = 0; p < weights.size(); ++p) { local_displacement.setZero(); for(size_t i = 0; i < vals.basis_values.size(); ++i) { const auto &vv = vals.basis_values[i]; assert(vv.val.size() == weights.size()); const double b_val = vv.val(p); for(int d = 0; d < size_; ++d) { for(std::size_t ii = 0; ii < vv.global.size(); ++ii) { local_displacement(d) += (vv.global[ii].val * b_val) * displacement(vv.global[ii].index*size_ + d); } } } for(int d = 0; d < size_; ++d) res -= forces(p, d) * local_displacement(d) * weights(p); } } return res; } bool RhsAssembler::boundary_quadrature(const LocalBoundary &local_boundary, const int order, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids) const { uv.resize(0, 0); points.resize(0, 0); weights.resize(0); global_primitive_ids.resize(0); for(int i = 0; i < local_boundary.size(); ++i) { const int gid = local_boundary.global_primitive_id(i); Eigen::MatrixXd tmp_p, tmp_uv; Eigen::VectorXd tmp_w; switch(local_boundary.type()) { case BoundaryType::TriLine: BoundarySampler::quadrature_for_tri_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break; case BoundaryType::QuadLine: BoundarySampler::quadrature_for_quad_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break; case BoundaryType::Quad: BoundarySampler::quadrature_for_quad_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break; case BoundaryType::Tri: BoundarySampler::quadrature_for_tri_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break; case BoundaryType::Invalid: assert(false); break; default: assert(false); } uv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols()); uv.bottomRows(tmp_uv.rows()) = tmp_uv; points.conservativeResize(points.rows() + tmp_p.rows(), tmp_p.cols()); points.bottomRows(tmp_p.rows()) = tmp_p; weights.conservativeResize(weights.rows() + tmp_w.rows(), tmp_w.cols()); weights.bottomRows(tmp_w.rows()) = tmp_w; global_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp_p.rows()); global_primitive_ids.bottomRows(tmp_p.rows()).setConstant(gid); } assert(uv.rows() == global_primitive_ids.size()); assert(points.rows() == global_primitive_ids.size()); assert(weights.size() == global_primitive_ids.size()); return true; } bool RhsAssembler::sample_boundary(const LocalBoundary &local_boundary, const int n_samples, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples, Eigen::VectorXi &global_primitive_ids) const { uv.resize(0, 0); samples.resize(0, 0); global_primitive_ids.resize(0); for(int i = 0; i < local_boundary.size(); ++i) { Eigen::MatrixXd tmp, tmp_uv; switch(local_boundary.type()) { case BoundaryType::TriLine: BoundarySampler::sample_parametric_tri_edge(local_boundary[i], n_samples, tmp_uv, tmp); break; case BoundaryType::QuadLine: BoundarySampler::sample_parametric_quad_edge(local_boundary[i], n_samples, tmp_uv, tmp); break; case BoundaryType::Quad: BoundarySampler::sample_parametric_quad_face(local_boundary[i], n_samples, tmp_uv, tmp); break; case BoundaryType::Tri: BoundarySampler::sample_parametric_tri_face(local_boundary[i], n_samples, tmp_uv, tmp); break; case BoundaryType::Invalid: assert(false); break; default: assert(false); } uv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols()); uv.bottomRows(tmp_uv.rows()) = tmp_uv; samples.conservativeResize(samples.rows() + tmp.rows(), tmp.cols()); samples.bottomRows(tmp.rows()) = tmp; global_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp.rows()); global_primitive_ids.bottomRows(tmp.rows()).setConstant(local_boundary.global_primitive_id(i)); } assert(uv.rows() == global_primitive_ids.size()); assert(samples.rows() == global_primitive_ids.size()); return true; } }
34.794498
290
0.668837
ldXiao
2325a5a23508c0d5cb259beb42feeaea35917197
5,274
cpp
C++
src/FrenetOptimalTrajectory/fot_wrapper.cpp
erdos-project/frenet-optimal-trajectory-planner
ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b
[ "Apache-2.0" ]
null
null
null
src/FrenetOptimalTrajectory/fot_wrapper.cpp
erdos-project/frenet-optimal-trajectory-planner
ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b
[ "Apache-2.0" ]
null
null
null
src/FrenetOptimalTrajectory/fot_wrapper.cpp
erdos-project/frenet-optimal-trajectory-planner
ba0cb5662a0e2ea668b1c2b2951c0f6b84f44f5b
[ "Apache-2.0" ]
1
2020-03-07T01:49:50.000Z
2020-03-07T01:49:50.000Z
#include "FrenetOptimalTrajectory.h" #include "FrenetPath.h" #include "py_cpp_struct.h" #include "CubicSpline2D.h" #include "utils.h" #include <stddef.h> #include <vector> using namespace std; // C++ wrapper to expose the FrenetOptimalTrajectory class to python extern "C" { // Compute the frenet optimal trajectory given initial conditions // in frenet space. // // Arguments: // fot_ic (FrenetInitialConditions *): // struct ptr containing relevant initial conditions to compute // Frenet Optimal Trajectory // fot_hp (FrenetHyperparameters *): // struct ptr containing relevant hyperparameters to compute // Frenet Optimal Trajectory // x_path, y_path, speeds (double *): // ptr to storage arrays for Frenet Optimal Trajectory // params (double *): // ptr to store initial conditions for debugging // // Returns: // 1 if successful, 0 if failure // Also stores the Frenet Optimal Trajectory into x_path, y_path, // speeds if it exists void run_fot( FrenetInitialConditions *fot_ic, FrenetHyperparameters *fot_hp, FrenetReturnValues *fot_rv ) { FrenetOptimalTrajectory fot = FrenetOptimalTrajectory(fot_ic, fot_hp); FrenetPath* best_frenet_path = fot.getBestPath(); if (best_frenet_path && !best_frenet_path->x.empty()){ fot_rv->success = 1; fot_rv->path_length = std::min(best_frenet_path->x.size(), MAX_PATH_LENGTH); for (size_t i = 0; i < fot_rv->path_length; i++) { fot_rv->x_path[i] = best_frenet_path->x[i]; fot_rv->y_path[i] = best_frenet_path->y[i]; fot_rv->speeds[i] = best_frenet_path->s_d[i]; fot_rv->ix[i] = best_frenet_path->ix[i]; fot_rv->iy[i] = best_frenet_path->iy[i]; fot_rv->iyaw[i] = best_frenet_path->iyaw[i]; fot_rv->d[i] = best_frenet_path->d[i]; fot_rv->s[i] = best_frenet_path->s[i]; fot_rv->speeds_x[i] = cos(best_frenet_path->yaw[i]) * fot_rv->speeds[i]; fot_rv->speeds_y[i] = sin(best_frenet_path->yaw[i]) * fot_rv->speeds[i]; } // store info for debug fot_rv->params[0] = best_frenet_path->s[1]; fot_rv->params[1] = best_frenet_path->s_d[1]; fot_rv->params[2] = best_frenet_path->d[1]; fot_rv->params[3] = best_frenet_path->d_d[1]; fot_rv->params[4] = best_frenet_path->d_dd[1]; // store costs for logging fot_rv->costs[0] = best_frenet_path->c_lateral_deviation; fot_rv->costs[1] = best_frenet_path->c_lateral_velocity; fot_rv->costs[2] = best_frenet_path->c_lateral_acceleration; fot_rv->costs[3] = best_frenet_path->c_lateral_jerk; fot_rv->costs[4] = best_frenet_path->c_lateral; fot_rv->costs[5] = best_frenet_path->c_longitudinal_acceleration; fot_rv->costs[6] = best_frenet_path->c_longitudinal_jerk; fot_rv->costs[7] = best_frenet_path->c_time_taken; fot_rv->costs[8] = best_frenet_path->c_end_speed_deviation; fot_rv->costs[9] = best_frenet_path->c_longitudinal; fot_rv->costs[10] = best_frenet_path->c_inv_dist_to_obstacles; fot_rv->costs[11] = best_frenet_path->cf; } } // Convert the initial conditions from cartesian space to frenet space void to_frenet_initial_conditions( double s0, double x, double y, double vx, double vy, double forward_speed, double* xp, double* yp, int np, double* initial_conditions ) { vector<double> wx (xp, xp + np); vector<double> wy (yp, yp + np); CubicSpline2D* csp = new CubicSpline2D(wx, wy); // get distance from car to spline and projection double s = csp->find_s(x, y, s0); double distance = norm(csp->calc_x(s) - x, csp->calc_y(s) - y); tuple<double, double> bvec ((csp->calc_x(s) - x) / distance, (csp->calc_y(s) - y) / distance); // normal spline vector double x0 = csp->calc_x(s0); double y0 = csp->calc_y(s0); double x1 = csp->calc_x(s0 + 2); double y1 = csp->calc_y(s0 + 2); // unit vector orthog. to spline tuple<double, double> tvec (y1-y0, -(x1-x0)); as_unit_vector(tvec); // compute tangent / normal car vectors tuple<double, double> fvec (vx, vy); as_unit_vector(fvec); // get initial conditions in frenet frame initial_conditions[0] = s; // current longitudinal position s initial_conditions[1] = forward_speed; // speed [m/s] // lateral position c_d [m] initial_conditions[2] = copysign(distance, dot(tvec, bvec)); // lateral speed c_d_d [m/s] initial_conditions[3] = -forward_speed * dot(tvec, fvec); initial_conditions[4] = 0.0; // lateral acceleration c_d_dd [m/s^2] // TODO: add lateral acceleration when CARLA 9.7 is patched (IMU) delete csp; } }
42.532258
88
0.595184
erdos-project
23288f4a73b963314c78ee1f635d01b952a59ca0
151
cpp
C++
archive/1/cukierki.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
2
2019-05-04T09:37:09.000Z
2019-05-22T18:07:28.000Z
archive/1/cukierki.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
archive/1/cukierki.cpp
Aleshkev/algoritmika
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef int I; int main() { string s; cin >> s; cout << s << s << '\n'; return 0; }
9.4375
27
0.503311
Aleshkev
232c1992a0b985e0771a9358e9884746096939f4
1,617
cc
C++
lib/lf/geometry/point.cc
Pascal-So/lehrfempp
e2716e914169eec7ee59e822ea3ab303143eacd1
[ "MIT" ]
null
null
null
lib/lf/geometry/point.cc
Pascal-So/lehrfempp
e2716e914169eec7ee59e822ea3ab303143eacd1
[ "MIT" ]
null
null
null
lib/lf/geometry/point.cc
Pascal-So/lehrfempp
e2716e914169eec7ee59e822ea3ab303143eacd1
[ "MIT" ]
null
null
null
#include "point.h" namespace lf::geometry { Eigen::MatrixXd Point::Global(const Eigen::MatrixXd& local) const { LF_ASSERT_MSG(local.rows() == 0, "local.rows() != 0"); return coord_.replicate(1, local.cols()); } // NOLINTNEXTLINE(misc-unused-parameters) Eigen::MatrixXd Point::Jacobian(const Eigen::MatrixXd& local) const { return Eigen::MatrixXd::Zero(DimGlobal(), 0); } Eigen::MatrixXd Point::JacobianInverseGramian( const Eigen::MatrixXd& local) const { // NOLINT(misc-unused-parameters) LF_VERIFY_MSG(false, "JacobianInverseGramian undefined for points."); } Eigen::VectorXd Point::IntegrationElement(const Eigen::MatrixXd& local) const { return Eigen::VectorXd::Ones(local.cols()); } std::unique_ptr<Geometry> Point::SubGeometry(dim_t codim, dim_t i) const { if (codim == 0 && i == 0) { return std::make_unique<Point>(coord_); } LF_VERIFY_MSG(false, "codim or i out of bounds."); } std::vector<std::unique_ptr<Geometry>> Point::ChildGeometry( const RefinementPattern& ref_pattern, lf::base::dim_t codim) const { LF_VERIFY_MSG(codim == 0, "Only codim = 0 allowed for a point"); std::vector<std::unique_ptr<Geometry>> child_geo_uptrs{}; LF_VERIFY_MSG(ref_pattern.RefEl() == lf::base::RefEl::kPoint(), "ref_patern.RefEl() = " << ref_pattern.RefEl().ToString()); LF_VERIFY_MSG(ref_pattern.noChildren(0) == 1, "ref_pattern.noChildren() = " << ref_pattern.noChildren(0)); // The only way to "refine" a point is to copy it child_geo_uptrs.push_back(std::make_unique<Point>(coord_)); return child_geo_uptrs; } } // namespace lf::geometry
36.75
79
0.700062
Pascal-So
232ccb1bb40892f5b0a04510fd9b37b06e65cc55
27,849
cpp
C++
FlexEngine/src/Window/GLFWWindowWrapper.cpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
762
2017-11-07T23:40:58.000Z
2022-03-31T16:03:22.000Z
FlexEngine/src/Window/GLFWWindowWrapper.cpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
5
2018-03-13T14:41:06.000Z
2020-11-01T12:02:29.000Z
FlexEngine/src/Window/GLFWWindowWrapper.cpp
ajweeks/Rendering-Engine
fe0f2cdb44a067fec875110572b3b91f5f4c659c
[ "MIT" ]
43
2017-11-17T11:22:37.000Z
2022-03-14T01:51:19.000Z
#include "stdafx.hpp" #include "Window/GLFWWindowWrapper.hpp" #include "FlexEngine.hpp" #include "Editor.hpp" #if COMPILE_OPEN_GL #include "Graphics/GL/GLHelpers.hpp" #endif #include "Graphics/Renderer.hpp" #include "Helpers.hpp" #include "InputManager.hpp" #include "Platform/Platform.hpp" #include "Window/Monitor.hpp" namespace flex { std::array<bool, MAX_JOYSTICK_COUNT> g_JoysticksConnected; GLFWWindowWrapper::GLFWWindowWrapper(const std::string& title) : Window(title) { m_LastNonFullscreenWindowMode = WindowMode::WINDOWED; } GLFWWindowWrapper::~GLFWWindowWrapper() { } void GLFWWindowWrapper::Initialize() { glfwSetErrorCallback(GLFWErrorCallback); if (!glfwInit()) { PrintError("Failed to initialize glfw! Exiting...\n"); exit(EXIT_FAILURE); return; } { i32 maj, min, rev; glfwGetVersion(&maj, &min, &rev); Print("GLFW v%d.%d.%d\n", maj, min, rev); } i32 numJoysticksConnected = 0; for (i32 i = 0; i < MAX_JOYSTICK_COUNT; ++i) { g_JoysticksConnected[i] = (glfwJoystickPresent(i) == GLFW_TRUE); if (g_JoysticksConnected[i]) { ++numJoysticksConnected; } } if (numJoysticksConnected > 0) { Print("%i joysticks connected on bootup\n", numJoysticksConnected); } g_EngineInstance->mainProcessID = Platform::GetCurrentProcessID(); // TODO: Look into supporting system-DPI awareness //SetProcessDPIAware(); } void GLFWWindowWrapper::PostInitialize() { PROFILE_AUTO("GLFWWindowWrapper PostInitialize"); // TODO: Set window location/size based on previous session (load from disk) glfwGetWindowSize(m_Window, &m_LastWindowedSize.x, &m_LastWindowedSize.y); glfwGetWindowPos(m_Window, &m_LastWindowedPos.x, &m_LastWindowedPos.y); } void GLFWWindowWrapper::Destroy() { if (m_Window) { m_Window = nullptr; } } void GLFWWindowWrapper::Create(const glm::vec2i& size, const glm::vec2i& pos) { InitFromConfig(); if (m_bMoveConsoleToOtherMonitor) { Platform::MoveConsole(); } // Only use parameters if values weren't set through config file if (m_Size.x == 0) { m_Size = size; m_Position = pos; } m_FrameBufferSize = m_Size; m_LastWindowedSize = m_Size; m_StartingPosition = m_Position; m_LastWindowedPos = m_Position; // Don't hide window when losing focus in Windowed Fullscreen glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_TRUE); glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE); if (g_bOpenGLEnabled) { #if COMPILE_OPEN_GL && DEBUG glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); #endif // DEBUG glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API); } else if (g_bVulkanEnabled) { glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); } if (m_bMaximized) { glfwWindowHint(GLFW_MAXIMIZED, 1); } GLFWmonitor* monitor = NULL; if (m_CurrentWindowMode == WindowMode::FULLSCREEN) { monitor = glfwGetPrimaryMonitor(); } m_Window = glfwCreateWindow(m_Size.x, m_Size.y, m_TitleString.c_str(), monitor, NULL); if (!m_Window) { PrintError("Failed to create glfw Window! Exiting...\n"); glfwTerminate(); // TODO: Try creating a window manually here exit(EXIT_FAILURE); } glfwSetWindowUserPointer(m_Window, this); SetUpCallbacks(); i32 monitorCount; GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); // If previously the window was on an additional monitor that is no longer present, // move the window to the primary monitor if (monitorCount == 1) { const GLFWvidmode* vidMode = glfwGetVideoMode(monitors[0]); i32 monitorWidth = vidMode->width; i32 monitorHeight = vidMode->height; if (m_StartingPosition.x < 0) { m_StartingPosition.x = 100; } else if (m_StartingPosition.x > monitorWidth) { m_StartingPosition.x = 100; } if (m_StartingPosition.y < 0) { m_StartingPosition.y = 100; } else if (m_StartingPosition.y > monitorHeight) { m_StartingPosition.y = 100; } } glfwSetWindowPos(m_Window, m_StartingPosition.x, m_StartingPosition.y); glfwFocusWindow(m_Window); m_bHasFocus = true; } void GLFWWindowWrapper::RetrieveMonitorInfo() { GLFWmonitor* monitor = glfwGetPrimaryMonitor(); if (!monitor) { i32 count; glfwGetMonitors(&count); PrintError("Failed to find primary monitor!\n"); PrintError("%d monitors found\n", count); return; } const GLFWvidmode* vidMode = glfwGetVideoMode(monitor); if (!vidMode) { PrintError("Failed to get monitor's video mode!\n"); return; } assert(g_Monitor); // Monitor must be created before calling RetrieveMonitorInfo! g_Monitor->width = vidMode->width; g_Monitor->height = vidMode->height; g_Monitor->redBits = vidMode->redBits; g_Monitor->greenBits = vidMode->greenBits; g_Monitor->blueBits = vidMode->blueBits; g_Monitor->refreshRate = vidMode->refreshRate; // 25.4mm = 1 inch i32 widthMM, heightMM; glfwGetMonitorPhysicalSize(monitor, &widthMM, &heightMM); g_Monitor->DPI = glm::vec2(vidMode->width / (widthMM / 25.4f), vidMode->height / (heightMM / 25.4f)); glfwGetMonitorContentScale(monitor, &g_Monitor->contentScaleX, &g_Monitor->contentScaleY); } void GLFWWindowWrapper::SetUpCallbacks() { if (!m_Window) { PrintError("SetUpCallbacks was called before m_Window was set!\n"); return; } glfwSetKeyCallback(m_Window, GLFWKeyCallback); glfwSetCharCallback(m_Window, GLFWCharCallback); glfwSetMouseButtonCallback(m_Window, GLFWMouseButtonCallback); glfwSetCursorPosCallback(m_Window, GLFWCursorPosCallback); glfwSetScrollCallback(m_Window, GLFWScrollCallback); glfwSetWindowSizeCallback(m_Window, GLFWWindowSizeCallback); glfwSetFramebufferSizeCallback(m_Window, GLFWFramebufferSizeCallback); glfwSetWindowFocusCallback(m_Window, GLFWWindowFocusCallback); glfwSetWindowPosCallback(m_Window, GLFWWindowPosCallback); // TODO: Only enable in editor builds glfwSetDropCallback(m_Window, GLFWDropCallback); glfwSetJoystickCallback(GLFWJoystickCallback); glfwSetMonitorCallback(GLFWMointorCallback); } void GLFWWindowWrapper::SetFrameBufferSize(i32 width, i32 height) { m_FrameBufferSize = glm::vec2i(width, height); m_Size = m_FrameBufferSize; if (g_Renderer) { g_Renderer->OnWindowSizeChanged(width, height); } } void GLFWWindowWrapper::SetSize(i32 width, i32 height) { glfwSetWindowSize(m_Window, width, height); OnSizeChanged(width, height); } void GLFWWindowWrapper::OnSizeChanged(i32 width, i32 height) { m_Size = glm::vec2i(width, height); m_FrameBufferSize = m_Size; if (m_CurrentWindowMode == WindowMode::WINDOWED) { m_LastWindowedSize = m_Size; } if (g_Renderer) { g_Renderer->OnWindowSizeChanged(width, height); } } void GLFWWindowWrapper::SetPosition(i32 newX, i32 newY) { if (m_Window) { glfwSetWindowPos(m_Window, newX, newY); } else { m_StartingPosition = { newX, newY }; } OnPositionChanged(newX, newY); } void GLFWWindowWrapper::OnPositionChanged(i32 newX, i32 newY) { m_Position = { newX, newY }; if (m_CurrentWindowMode == WindowMode::WINDOWED) { m_LastWindowedPos = m_Position; } } void GLFWWindowWrapper::PollEvents() { glfwPollEvents(); } void GLFWWindowWrapper::SetCursorPos(const glm::vec2& newCursorPos) { glfwSetCursorPos(m_Window, newCursorPos.x, newCursorPos.y); } void GLFWWindowWrapper::SetCursorMode(CursorMode mode) { if (m_CursorMode != mode) { Window::SetCursorMode(mode); i32 glfwCursorMode = 0; switch (mode) { case CursorMode::NORMAL: glfwCursorMode = GLFW_CURSOR_NORMAL; break; case CursorMode::HIDDEN: glfwCursorMode = GLFW_CURSOR_HIDDEN; break; case CursorMode::DISABLED: glfwCursorMode = GLFW_CURSOR_DISABLED; break; case CursorMode::_NONE: default: PrintError("Unhandled cursor mode passed to GLFWWindowWrapper::SetCursorMode: %i\n", (i32)mode); break; } glfwSetInputMode(m_Window, GLFW_CURSOR, glfwCursorMode); // Enable raw motion when cursor disabled for smoother camera controls if (glfwCursorMode == GLFW_CURSOR_DISABLED) { if (glfwRawMouseMotionSupported()) { glfwSetInputMode(m_Window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE); } } } } void GLFWWindowWrapper::SetWindowMode(WindowMode mode, bool bForce) { if (bForce || m_CurrentWindowMode != mode) { m_CurrentWindowMode = mode; GLFWmonitor* monitor = glfwGetPrimaryMonitor(); if (!monitor) { PrintError("Failed to find primary monitor! Can't set window mode\n"); return; } const GLFWvidmode* videoMode = glfwGetVideoMode(monitor); if (!videoMode) { PrintError("Failed to get monitor's video mode! Can't set window mode\n"); return; } switch (mode) { case WindowMode::FULLSCREEN: { glfwSetWindowMonitor(m_Window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate); } break; case WindowMode::WINDOWED_FULLSCREEN: { glfwSetWindowMonitor(m_Window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate); m_LastNonFullscreenWindowMode = WindowMode::WINDOWED_FULLSCREEN; } break; case WindowMode::WINDOWED: { assert(m_LastWindowedSize.x != 0 && m_LastWindowedSize.y != 0); if (m_LastWindowedPos.y == 0) { // When in windowed mode a y position of 0 means the title bar isn't // visible. This will occur if the app launched in fullscreen since // the last y position to never have been set to a valid value. m_LastWindowedPos.y = 40; } glfwSetWindowMonitor(m_Window, nullptr, m_LastWindowedPos.x, m_LastWindowedPos.y, m_LastWindowedSize.x, m_LastWindowedSize.y, videoMode->refreshRate); m_LastNonFullscreenWindowMode = WindowMode::WINDOWED; } break; case WindowMode::_NONE: default: { PrintError("Unhandled window mode: %u\n", (u32)mode); } break; } } } void GLFWWindowWrapper::ToggleFullscreen(bool bForce) { if (m_CurrentWindowMode == WindowMode::FULLSCREEN) { assert(m_LastNonFullscreenWindowMode == WindowMode::WINDOWED || m_LastNonFullscreenWindowMode == WindowMode::WINDOWED_FULLSCREEN); SetWindowMode(m_LastNonFullscreenWindowMode, bForce); } else { SetWindowMode(WindowMode::FULLSCREEN, bForce); } } void GLFWWindowWrapper::Maximize() { glfwMaximizeWindow(m_Window); } void GLFWWindowWrapper::Iconify() { glfwIconifyWindow(m_Window); } void GLFWWindowWrapper::Update() { Window::Update(); if (glfwWindowShouldClose(m_Window)) { g_EngineInstance->Stop(); return; } GLFWgamepadstate gamepad0State; static bool bPrevP0JoystickPresent = false; if (glfwGetGamepadState(0, &gamepad0State) == GLFW_TRUE) { g_InputManager->UpdateGamepadState(0, gamepad0State.axes, gamepad0State.buttons); bPrevP0JoystickPresent = true; } else { if (bPrevP0JoystickPresent) { g_InputManager->ClearGampadInput(0); bPrevP0JoystickPresent = false; } } GLFWgamepadstate gamepad1State; static bool bPrevP1JoystickPresent = false; if (glfwGetGamepadState(1, &gamepad1State) == GLFW_TRUE) { g_InputManager->UpdateGamepadState(1, gamepad1State.axes, gamepad1State.buttons); bPrevP1JoystickPresent = true; } else { if (bPrevP1JoystickPresent) { g_InputManager->ClearGampadInput(1); bPrevP1JoystickPresent = false; } } } GLFWwindow* GLFWWindowWrapper::GetWindow() const { return m_Window; } const char* GLFWWindowWrapper::GetClipboardText() { return glfwGetClipboardString(m_Window); } void GLFWWindowWrapper::SetClipboardText(const char* text) { glfwSetClipboardString(m_Window, text); } void GLFWWindowWrapper::SetWindowTitle(const std::string& title) { glfwSetWindowTitle(m_Window, title.c_str()); } void GLFWWindowWrapper::SetMousePosition(glm::vec2 mousePosition) { glfwSetCursorPos(m_Window, (double)mousePosition.x, (double)mousePosition.y); } glm::vec2 GLFWWindowWrapper::GetMousePosition() { double posX, posY; glfwGetCursorPos(m_Window, &posX, &posY); return glm::vec2((real)posX, (real)posY); } void GLFWErrorCallback(i32 error, const char* description) { PrintError("GLFW Error: %i: %s\n", error, description); } void GLFWKeyCallback(GLFWwindow* glfwWindow, i32 key, i32 scancode, i32 action, i32 mods) { FLEX_UNUSED(scancode); Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); const KeyAction inputAction = GLFWActionToInputManagerAction(action); const KeyCode inputKey = GLFWKeyToInputManagerKey(key); const i32 inputMods = GLFWModsToInputManagerMods(mods); window->KeyCallback(inputKey, inputAction, inputMods); } void GLFWCharCallback(GLFWwindow* glfwWindow, u32 character) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); window->CharCallback(character); } void GLFWMouseButtonCallback(GLFWwindow* glfwWindow, i32 button, i32 action, i32 mods) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); const KeyAction inputAction = GLFWActionToInputManagerAction(action); const i32 inputMods = GLFWModsToInputManagerMods(mods); const MouseButton mouseButton = GLFWButtonToInputManagerMouseButton(button); window->MouseButtonCallback(mouseButton, inputAction, inputMods); } void GLFWWindowFocusCallback(GLFWwindow* glfwWindow, i32 focused) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); window->WindowFocusCallback(focused); } void GLFWWindowPosCallback(GLFWwindow* glfwWindow, i32 newX, i32 newY) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); window->WindowPosCallback(newX, newY); } void GLFWCursorPosCallback(GLFWwindow* glfwWindow, double x, double y) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); window->CursorPosCallback(x, y); } void GLFWScrollCallback(GLFWwindow* glfwWindow, double xoffset, double yoffset) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); window->ScrollCallback(xoffset, yoffset); } void GLFWWindowSizeCallback(GLFWwindow* glfwWindow, i32 width, i32 height) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); bool bMaximized = (glfwGetWindowAttrib(glfwWindow, GLFW_MAXIMIZED) == GLFW_TRUE); bool bIconified = (glfwGetWindowAttrib(glfwWindow, GLFW_ICONIFIED) == GLFW_TRUE); window->WindowSizeCallback(width, height, bMaximized, bIconified); } void GLFWFramebufferSizeCallback(GLFWwindow* glfwWindow, i32 width, i32 height) { Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)); window->FrameBufferSizeCallback(width, height); } void GLFWDropCallback(GLFWwindow* glfwWindow, int count, const char** paths) { g_Editor->OnDragDrop(count, paths); glfwFocusWindow(glfwWindow); } void GLFWJoystickCallback(i32 JID, i32 event) { if (JID > MAX_JOYSTICK_COUNT) { PrintWarn("Unhandled joystick connection event, JID out of range: %i\n", JID); return; } if (event == GLFW_CONNECTED) { Print("Joystick %i connected\n", JID); } else if (event == GLFW_DISCONNECTED) { Print("Joystick %i disconnected\n", JID); } g_JoysticksConnected[(u32)JID] = (event == GLFW_CONNECTED); } void GLFWMointorCallback(GLFWmonitor* monitor, int event) { i32 w, h; glfwGetMonitorPhysicalSize(monitor, &w, &h); if (event == GLFW_CONNECTED) { Print("Monitor connected: %s, %dmm x %dmm\n", glfwGetMonitorName(monitor), w, h); } else { Print("Monitor disconnected: %s, %dmm x %dmm\n", glfwGetMonitorName(monitor), w, h); } } KeyAction GLFWActionToInputManagerAction(i32 glfwAction) { KeyAction inputAction = KeyAction::_NONE; switch (glfwAction) { case GLFW_PRESS: inputAction = KeyAction::KEY_PRESS; break; case GLFW_REPEAT: inputAction = KeyAction::KEY_REPEAT; break; case GLFW_RELEASE: inputAction = KeyAction::KEY_RELEASE; break; case -1: break; // We don't care about events GLFW can't handle default: PrintError("Unhandled glfw action passed to GLFWActionToInputManagerAction in GLFWWIndowWrapper: %i\n", glfwAction); } return inputAction; } KeyCode GLFWKeyToInputManagerKey(i32 glfwKey) { KeyCode inputKey = KeyCode::_NONE; switch (glfwKey) { case GLFW_KEY_SPACE: inputKey = KeyCode::KEY_SPACE; break; case GLFW_KEY_APOSTROPHE: inputKey = KeyCode::KEY_APOSTROPHE; break; case GLFW_KEY_COMMA: inputKey = KeyCode::KEY_COMMA; break; case GLFW_KEY_MINUS: inputKey = KeyCode::KEY_MINUS; break; case GLFW_KEY_PERIOD: inputKey = KeyCode::KEY_PERIOD; break; case GLFW_KEY_SLASH: inputKey = KeyCode::KEY_SLASH; break; case GLFW_KEY_0: inputKey = KeyCode::KEY_0; break; case GLFW_KEY_1: inputKey = KeyCode::KEY_1; break; case GLFW_KEY_2: inputKey = KeyCode::KEY_2; break; case GLFW_KEY_3: inputKey = KeyCode::KEY_3; break; case GLFW_KEY_4: inputKey = KeyCode::KEY_4; break; case GLFW_KEY_5: inputKey = KeyCode::KEY_5; break; case GLFW_KEY_6: inputKey = KeyCode::KEY_6; break; case GLFW_KEY_7: inputKey = KeyCode::KEY_7; break; case GLFW_KEY_8: inputKey = KeyCode::KEY_8; break; case GLFW_KEY_9: inputKey = KeyCode::KEY_9; break; case GLFW_KEY_SEMICOLON: inputKey = KeyCode::KEY_SEMICOLON; break; case GLFW_KEY_EQUAL: inputKey = KeyCode::KEY_EQUAL; break; case GLFW_KEY_A: inputKey = KeyCode::KEY_A; break; case GLFW_KEY_B: inputKey = KeyCode::KEY_B; break; case GLFW_KEY_C: inputKey = KeyCode::KEY_C; break; case GLFW_KEY_D: inputKey = KeyCode::KEY_D; break; case GLFW_KEY_E: inputKey = KeyCode::KEY_E; break; case GLFW_KEY_F: inputKey = KeyCode::KEY_F; break; case GLFW_KEY_G: inputKey = KeyCode::KEY_G; break; case GLFW_KEY_H: inputKey = KeyCode::KEY_H; break; case GLFW_KEY_I: inputKey = KeyCode::KEY_I; break; case GLFW_KEY_J: inputKey = KeyCode::KEY_J; break; case GLFW_KEY_K: inputKey = KeyCode::KEY_K; break; case GLFW_KEY_L: inputKey = KeyCode::KEY_L; break; case GLFW_KEY_M: inputKey = KeyCode::KEY_M; break; case GLFW_KEY_N: inputKey = KeyCode::KEY_N; break; case GLFW_KEY_O: inputKey = KeyCode::KEY_O; break; case GLFW_KEY_P: inputKey = KeyCode::KEY_P; break; case GLFW_KEY_Q: inputKey = KeyCode::KEY_Q; break; case GLFW_KEY_R: inputKey = KeyCode::KEY_R; break; case GLFW_KEY_S: inputKey = KeyCode::KEY_S; break; case GLFW_KEY_T: inputKey = KeyCode::KEY_T; break; case GLFW_KEY_U: inputKey = KeyCode::KEY_U; break; case GLFW_KEY_V: inputKey = KeyCode::KEY_V; break; case GLFW_KEY_W: inputKey = KeyCode::KEY_W; break; case GLFW_KEY_X: inputKey = KeyCode::KEY_X; break; case GLFW_KEY_Y: inputKey = KeyCode::KEY_Y; break; case GLFW_KEY_Z: inputKey = KeyCode::KEY_Z; break; case GLFW_KEY_LEFT_BRACKET: inputKey = KeyCode::KEY_LEFT_BRACKET; break; case GLFW_KEY_BACKSLASH: inputKey = KeyCode::KEY_BACKSLASH; break; case GLFW_KEY_RIGHT_BRACKET: inputKey = KeyCode::KEY_RIGHT_BRACKET; break; case GLFW_KEY_GRAVE_ACCENT: inputKey = KeyCode::KEY_GRAVE_ACCENT; break; case GLFW_KEY_WORLD_1: inputKey = KeyCode::KEY_WORLD_1; break; case GLFW_KEY_WORLD_2: inputKey = KeyCode::KEY_WORLD_2; break; case GLFW_KEY_ESCAPE: inputKey = KeyCode::KEY_ESCAPE; break; case GLFW_KEY_ENTER: inputKey = KeyCode::KEY_ENTER; break; case GLFW_KEY_TAB: inputKey = KeyCode::KEY_TAB; break; case GLFW_KEY_BACKSPACE: inputKey = KeyCode::KEY_BACKSPACE; break; case GLFW_KEY_INSERT: inputKey = KeyCode::KEY_INSERT; break; case GLFW_KEY_DELETE: inputKey = KeyCode::KEY_DELETE; break; case GLFW_KEY_RIGHT: inputKey = KeyCode::KEY_RIGHT; break; case GLFW_KEY_LEFT: inputKey = KeyCode::KEY_LEFT; break; case GLFW_KEY_DOWN: inputKey = KeyCode::KEY_DOWN; break; case GLFW_KEY_UP: inputKey = KeyCode::KEY_UP; break; case GLFW_KEY_PAGE_UP: inputKey = KeyCode::KEY_PAGE_UP; break; case GLFW_KEY_PAGE_DOWN: inputKey = KeyCode::KEY_PAGE_DOWN; break; case GLFW_KEY_HOME: inputKey = KeyCode::KEY_HOME; break; case GLFW_KEY_END: inputKey = KeyCode::KEY_END; break; case GLFW_KEY_CAPS_LOCK: inputKey = KeyCode::KEY_CAPS_LOCK; break; case GLFW_KEY_SCROLL_LOCK: inputKey = KeyCode::KEY_SCROLL_LOCK; break; case GLFW_KEY_NUM_LOCK: inputKey = KeyCode::KEY_NUM_LOCK; break; case GLFW_KEY_PRINT_SCREEN: inputKey = KeyCode::KEY_PRINT_SCREEN; break; case GLFW_KEY_PAUSE: inputKey = KeyCode::KEY_PAUSE; break; case GLFW_KEY_F1: inputKey = KeyCode::KEY_F1; break; case GLFW_KEY_F2: inputKey = KeyCode::KEY_F2; break; case GLFW_KEY_F3: inputKey = KeyCode::KEY_F3; break; case GLFW_KEY_F4: inputKey = KeyCode::KEY_F4; break; case GLFW_KEY_F5: inputKey = KeyCode::KEY_F5; break; case GLFW_KEY_F6: inputKey = KeyCode::KEY_F6; break; case GLFW_KEY_F7: inputKey = KeyCode::KEY_F7; break; case GLFW_KEY_F8: inputKey = KeyCode::KEY_F8; break; case GLFW_KEY_F9: inputKey = KeyCode::KEY_F9; break; case GLFW_KEY_F10: inputKey = KeyCode::KEY_F10; break; case GLFW_KEY_F11: inputKey = KeyCode::KEY_F11; break; case GLFW_KEY_F12: inputKey = KeyCode::KEY_F12; break; case GLFW_KEY_F13: inputKey = KeyCode::KEY_F13; break; case GLFW_KEY_F14: inputKey = KeyCode::KEY_F14; break; case GLFW_KEY_F15: inputKey = KeyCode::KEY_F15; break; case GLFW_KEY_F16: inputKey = KeyCode::KEY_F16; break; case GLFW_KEY_F17: inputKey = KeyCode::KEY_F17; break; case GLFW_KEY_F18: inputKey = KeyCode::KEY_F18; break; case GLFW_KEY_F19: inputKey = KeyCode::KEY_F19; break; case GLFW_KEY_F20: inputKey = KeyCode::KEY_F20; break; case GLFW_KEY_F21: inputKey = KeyCode::KEY_F21; break; case GLFW_KEY_F22: inputKey = KeyCode::KEY_F22; break; case GLFW_KEY_F23: inputKey = KeyCode::KEY_F23; break; case GLFW_KEY_F24: inputKey = KeyCode::KEY_F24; break; case GLFW_KEY_F25: inputKey = KeyCode::KEY_F25; break; case GLFW_KEY_KP_0: inputKey = KeyCode::KEY_KP_0; break; case GLFW_KEY_KP_1: inputKey = KeyCode::KEY_KP_1; break; case GLFW_KEY_KP_2: inputKey = KeyCode::KEY_KP_2; break; case GLFW_KEY_KP_3: inputKey = KeyCode::KEY_KP_3; break; case GLFW_KEY_KP_4: inputKey = KeyCode::KEY_KP_4; break; case GLFW_KEY_KP_5: inputKey = KeyCode::KEY_KP_5; break; case GLFW_KEY_KP_6: inputKey = KeyCode::KEY_KP_6; break; case GLFW_KEY_KP_7: inputKey = KeyCode::KEY_KP_7; break; case GLFW_KEY_KP_8: inputKey = KeyCode::KEY_KP_8; break; case GLFW_KEY_KP_9: inputKey = KeyCode::KEY_KP_9; break; case GLFW_KEY_KP_DECIMAL: inputKey = KeyCode::KEY_KP_DECIMAL; break; case GLFW_KEY_KP_DIVIDE: inputKey = KeyCode::KEY_KP_DIVIDE; break; case GLFW_KEY_KP_MULTIPLY: inputKey = KeyCode::KEY_KP_MULTIPLY; break; case GLFW_KEY_KP_SUBTRACT: inputKey = KeyCode::KEY_KP_SUBTRACT; break; case GLFW_KEY_KP_ADD: inputKey = KeyCode::KEY_KP_ADD; break; case GLFW_KEY_KP_ENTER: inputKey = KeyCode::KEY_KP_ENTER; break; case GLFW_KEY_KP_EQUAL: inputKey = KeyCode::KEY_KP_EQUAL; break; case GLFW_KEY_LEFT_SHIFT: inputKey = KeyCode::KEY_LEFT_SHIFT; break; case GLFW_KEY_LEFT_CONTROL: inputKey = KeyCode::KEY_LEFT_CONTROL; break; case GLFW_KEY_LEFT_ALT: inputKey = KeyCode::KEY_LEFT_ALT; break; case GLFW_KEY_LEFT_SUPER: inputKey = KeyCode::KEY_LEFT_SUPER; break; case GLFW_KEY_RIGHT_SHIFT: inputKey = KeyCode::KEY_RIGHT_SHIFT; break; case GLFW_KEY_RIGHT_CONTROL: inputKey = KeyCode::KEY_RIGHT_CONTROL; break; case GLFW_KEY_RIGHT_ALT: inputKey = KeyCode::KEY_RIGHT_ALT; break; case GLFW_KEY_RIGHT_SUPER: inputKey = KeyCode::KEY_RIGHT_SUPER; break; case GLFW_KEY_MENU: inputKey = KeyCode::KEY_MENU; break; case -1: break; // We don't care about events GLFW can't handle default: PrintError("Unhandled glfw key passed to GLFWKeyToInputManagerKey in GLFWWIndowWrapper: %i\n", glfwKey); break; } return inputKey; } i32 GLFWModsToInputManagerMods(i32 glfwMods) { i32 inputMods = 0; if (glfwMods & GLFW_MOD_SHIFT) inputMods |= (i32)InputModifier::SHIFT; if (glfwMods & GLFW_MOD_ALT) inputMods |= (i32)InputModifier::ALT; if (glfwMods & GLFW_MOD_CONTROL) inputMods |= (i32)InputModifier::CONTROL; if (glfwMods & GLFW_MOD_SUPER) inputMods |= (i32)InputModifier::SUPER; if (glfwMods & GLFW_MOD_CAPS_LOCK) inputMods |= (i32)InputModifier::CAPS_LOCK; if (glfwMods & GLFW_MOD_NUM_LOCK) inputMods |= (i32)InputModifier::NUM_LOCK; return inputMods; } MouseButton GLFWButtonToInputManagerMouseButton(i32 glfwButton) { MouseButton inputMouseButton = MouseButton::_NONE; switch (glfwButton) { case GLFW_MOUSE_BUTTON_1: inputMouseButton = MouseButton::MOUSE_BUTTON_1; break; case GLFW_MOUSE_BUTTON_2: inputMouseButton = MouseButton::MOUSE_BUTTON_2; break; case GLFW_MOUSE_BUTTON_3: inputMouseButton = MouseButton::MOUSE_BUTTON_3; break; case GLFW_MOUSE_BUTTON_4: inputMouseButton = MouseButton::MOUSE_BUTTON_4; break; case GLFW_MOUSE_BUTTON_5: inputMouseButton = MouseButton::MOUSE_BUTTON_5; break; case GLFW_MOUSE_BUTTON_6: inputMouseButton = MouseButton::MOUSE_BUTTON_6; break; case GLFW_MOUSE_BUTTON_7: inputMouseButton = MouseButton::MOUSE_BUTTON_7; break; case GLFW_MOUSE_BUTTON_8: inputMouseButton = MouseButton::MOUSE_BUTTON_8; break; case -1: break; // We don't care about events GLFW can't handle default: PrintError("Unhandled glfw button passed to GLFWButtonToInputManagerMouseButton in GLFWWIndowWrapper: %i\n", glfwButton); break; } return inputMouseButton; } #if defined(_WINDOWS) && COMPILE_OPEN_GL void WINAPI glDebugOutput(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam) { FLEX_UNUSED(userParam); FLEX_UNUSED(length); // Ignore insignificant error/warning codes and notification messages if (id == 131169 || id == 131185 || id == 131218 || id == 131204 || severity == GL_DEBUG_SEVERITY_NOTIFICATION) { return; } PrintError("-----------------------------------------\n"); PrintError("GL Debug message (%u): %s\n", id, message); switch (source) { case GL_DEBUG_SOURCE_API: PrintError("Source: API"); break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM: PrintError("Source: Window System"); break; case GL_DEBUG_SOURCE_SHADER_COMPILER: PrintError("Source: Shader Compiler"); break; case GL_DEBUG_SOURCE_THIRD_PARTY: PrintError("Source: Third Party"); break; case GL_DEBUG_SOURCE_APPLICATION: PrintError("Source: Application"); break; case GL_DEBUG_SOURCE_OTHER: PrintError("Source: Other"); break; } PrintError("\n"); switch (type) { case GL_DEBUG_TYPE_ERROR: PrintError("Type: Error"); break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: PrintError("Type: Deprecated Behaviour"); break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: PrintError("Type: Undefined Behaviour"); break; case GL_DEBUG_TYPE_PORTABILITY: PrintError("Type: Portability"); break; case GL_DEBUG_TYPE_PERFORMANCE: PrintError("Type: Performance"); break; case GL_DEBUG_TYPE_MARKER: PrintError("Type: Marker"); break; case GL_DEBUG_TYPE_PUSH_GROUP: PrintError("Type: Push Group"); break; case GL_DEBUG_TYPE_POP_GROUP: PrintError("Type: Pop Group"); break; case GL_DEBUG_TYPE_OTHER: PrintError("Type: Other"); break; } PrintError("\n"); switch (severity) { case GL_DEBUG_SEVERITY_HIGH: PrintError("Severity: high"); break; case GL_DEBUG_SEVERITY_MEDIUM: PrintError("Severity: medium"); break; case GL_DEBUG_SEVERITY_LOW: PrintError("Severity: low"); break; //case GL_DEBUG_SEVERITY_NOTIFICATION: PrintError("Severity: notification"); break; } PrintError("\n-----------------------------------------\n"); } #endif } // namespace flex
32.6483
154
0.738016
ajweeks
2331e0219ab4482e80e287d213ad0093d02a0677
505
hpp
C++
libraries/chain/include/graphene/chain/protocol/cyva.hpp
cyvasia/cyva
e98b26abfe8e96d0e1470626b0a525d44f9372a9
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/protocol/cyva.hpp
cyvasia/cyva
e98b26abfe8e96d0e1470626b0a525d44f9372a9
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/protocol/cyva.hpp
cyvasia/cyva
e98b26abfe8e96d0e1470626b0a525d44f9372a9
[ "MIT" ]
null
null
null
/* (c) 2018 CYVA. For details refer to LICENSE */ #pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/protocol/types.hpp> #include <graphene/chain/protocol/asset.hpp> #include <boost/preprocessor/seq/seq.hpp> #include <fc/reflect/reflect.hpp> #include <fc/crypto/ripemd160.hpp> #include <fc/time.hpp> #include <stdint.h> #include <vector> #include <utility> #include <cyva/encrypt/crypto_types.hpp> namespace graphene { namespace chain { } } // graphene::chain
18.703704
49
0.732673
cyvasia
23329fe028bb17c96abe4e83ff364e332119b8e4
5,297
cpp
C++
src/systemcmds/tests/test_List.cpp
a093050472/PX4-Auotopilot
177da1f92324dcb98b23643b73cfe5cb342ba32f
[ "BSD-3-Clause" ]
8
2017-12-02T15:00:44.000Z
2022-03-29T15:09:12.000Z
src/systemcmds/tests/test_List.cpp
a093050472/PX4-Auotopilot
177da1f92324dcb98b23643b73cfe5cb342ba32f
[ "BSD-3-Clause" ]
4
2020-11-07T12:08:43.000Z
2021-06-18T15:16:17.000Z
src/systemcmds/tests/test_List.cpp
a093050472/PX4-Auotopilot
177da1f92324dcb98b23643b73cfe5cb342ba32f
[ "BSD-3-Clause" ]
20
2020-07-09T03:11:03.000Z
2021-12-21T13:01:18.000Z
/**************************************************************************** * * Copyright (C) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * 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. * ****************************************************************************/ /** * @file test_List.cpp * Tests the List container. */ #include <unit_test.h> #include <containers/List.hpp> #include <float.h> #include <math.h> class testContainer : public ListNode<testContainer *> { public: int i{0}; }; class ListTest : public UnitTest { public: virtual bool run_tests(); bool test_add(); bool test_remove(); bool test_range_based_for(); }; bool ListTest::run_tests() { ut_run_test(test_add); ut_run_test(test_remove); ut_run_test(test_range_based_for); return (_tests_failed == 0); } bool ListTest::test_add() { List<testContainer *> list1; // size should be 0 initially ut_compare("size initially 0", list1.size(), 0); ut_assert_true(list1.empty()); // insert 100 for (int i = 0; i < 100; i++) { testContainer *t = new testContainer(); t->i = i; list1.add(t); ut_compare("size increasing with i", list1.size(), i + 1); ut_assert_true(!list1.empty()); } // verify full size (100) ut_assert_true(list1.size() == 100); int i = 99; for (auto t : list1) { // verify all elements were inserted in order ut_compare("stored i", i, t->i); i--; } // delete all elements list1.clear(); // verify list has been cleared ut_assert_true(list1.empty()); ut_compare("size 0", list1.size(), 0); return true; } bool ListTest::test_remove() { List<testContainer *> list1; // size should be 0 initially ut_compare("size initially 0", list1.size(), 0); ut_assert_true(list1.empty()); // insert 100 for (int i = 0; i < 100; i++) { testContainer *t = new testContainer(); t->i = i; list1.add(t); ut_compare("size increasing with i", list1.size(), i + 1); ut_assert_true(!list1.empty()); } // verify full size (100) ut_assert_true(list1.size() == 100); // test removing elements for (int remove_i = 0; remove_i < 100; remove_i++) { // find node with i == remove_i testContainer *removed = nullptr; for (auto t : list1) { if (t->i == remove_i) { ut_assert_true(list1.remove(t)); removed = t; } } delete removed; // iterate list again to verify removal for (auto t : list1) { ut_assert_true(t->i != remove_i); } ut_assert_true(list1.size() == 100 - remove_i - 1); } // list should now be empty ut_assert_true(list1.empty()); ut_compare("size 0", list1.size(), 0); // delete all elements (should be safe on empty list) list1.clear(); // verify list has been cleared ut_assert_true(list1.empty()); ut_compare("size 0", list1.size(), 0); return true; } bool ListTest::test_range_based_for() { List<testContainer *> list1; // size should be 0 initially ut_compare("size initially 0", list1.size(), 0); ut_assert_true(list1.empty()); // insert 100 elements in order for (int i = 99; i >= 0; i--) { testContainer *t = new testContainer(); t->i = i; list1.add(t); ut_assert_true(!list1.empty()); } // first element should be 0 ut_compare("first 0", list1.getHead()->i, 0); // verify all elements were inserted in order int i = 0; auto t1 = list1.getHead(); while (t1 != nullptr) { ut_compare("check count", i, t1->i); t1 = t1->getSibling(); i++; } // verify full size (100) ut_compare("size check", list1.size(), 100); i = 0; for (auto t2 : list1) { ut_compare("range based for i", i, t2->i); i++; } // verify full size (100) ut_compare("size check", list1.size(), 100); // delete all elements list1.clear(); // verify list has been cleared ut_assert_true(list1.empty()); ut_compare("size check", list1.size(), 0); return true; } ut_declare_test_c(test_List, ListTest)
23.86036
78
0.664338
a093050472
233764cf02f1b169af3957995c73a1e2e68fe63e
2,524
cpp
C++
YorozuyaGSLib/source/CChatStealSystem.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/CChatStealSystem.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/CChatStealSystem.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <CChatStealSystem.hpp> START_ATF_NAMESPACE CChatStealSystem::CChatStealSystem() { using org_ptr = void (WINAPIV*)(struct CChatStealSystem*); (org_ptr(0x1403f86a0L))(this); }; void CChatStealSystem::ctor_CChatStealSystem() { using org_ptr = void (WINAPIV*)(struct CChatStealSystem*); (org_ptr(0x1403f86a0L))(this); }; struct CChatStealSystem* CChatStealSystem::Instance() { using org_ptr = struct CChatStealSystem* (WINAPIV*)(); return (org_ptr(0x140094f00L))(); }; void CChatStealSystem::SendStealMsg(struct CPlayer* pPlayer, char byChatType, unsigned int dwSenderSerial, char* pwszSender, char byRaceCode, char* pwszMessage) { using org_ptr = void (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*, char, unsigned int, char*, char, char*); (org_ptr(0x1403f8a30L))(this, pPlayer, byChatType, dwSenderSerial, pwszSender, byRaceCode, pwszMessage); }; bool CChatStealSystem::SetGm(struct CPlayer* pGM) { using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*); return (org_ptr(0x1403f88b0L))(this, pGM); }; bool CChatStealSystem::SetTargetInfoFromBoss(char byType, char byRaceCode) { using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char); return (org_ptr(0x1403f8870L))(this, byType, byRaceCode); }; bool CChatStealSystem::SetTargetInfoFromCharacter(char byType, char* szCharName) { using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char*); return (org_ptr(0x1403f87c0L))(this, byType, szCharName); }; bool CChatStealSystem::SetTargetInfoFromRace(char byType, char byRaceCode) { using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char); return (org_ptr(0x1403f8830L))(this, byType, byRaceCode); }; void CChatStealSystem::StealChatMsg(struct CPlayer* pPlayer, char byChatType, char* szChatMsg) { using org_ptr = void (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*, char, char*); (org_ptr(0x1403f8900L))(this, pPlayer, byChatType, szChatMsg); }; CChatStealSystem::~CChatStealSystem() { using org_ptr = void (WINAPIV*)(struct CChatStealSystem*); (org_ptr(0x1403f8700L))(this); }; void CChatStealSystem::dtor_CChatStealSystem() { using org_ptr = void (WINAPIV*)(struct CChatStealSystem*); (org_ptr(0x1403f8700L))(this); }; END_ATF_NAMESPACE
41.377049
164
0.679477
lemkova
2339012f9340b23c94e09b688a3a0df9cd2b7d85
3,145
cpp
C++
src/io/nanopolish_fast5_processor.cpp
Yufeng98/nanopolish
1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2
[ "MIT" ]
439
2015-03-11T15:23:41.000Z
2022-03-31T14:24:20.000Z
src/io/nanopolish_fast5_processor.cpp
Yufeng98/nanopolish
1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2
[ "MIT" ]
917
2015-03-11T18:28:58.000Z
2022-03-30T23:11:15.000Z
src/io/nanopolish_fast5_processor.cpp
Yufeng98/nanopolish
1c6ce4d041d461b6a95baff8099cc7e11bb5a8a2
[ "MIT" ]
177
2015-04-22T23:50:53.000Z
2022-03-25T06:41:35.000Z
//--------------------------------------------------------- // Copyright 2016 Ontario Institute for Cancer Research // Written by Jared Simpson (jared.simpson@oicr.on.ca) //--------------------------------------------------------- // // nanopolish_fast5_processor -- framework for iterating // over a collection of fast5 files and performing some // action on each read in parallel // #include "nanopolish_fast5_processor.h" #include "nanopolish_common.h" #include "nanopolish_fast5_io.h" #include <assert.h> #include <omp.h> #include <vector> Fast5Processor::Fast5Processor(const ReadDB& read_db, const int num_threads, const int batch_size) : m_num_threads(num_threads), m_batch_size(batch_size) { m_fast5s = read_db.get_unique_fast5s(); } Fast5Processor::Fast5Processor(const std::string& fast5_file, const int num_threads, const int batch_size) : m_num_threads(num_threads), m_batch_size(batch_size) { m_fast5s.push_back(fast5_file); } Fast5Processor::~Fast5Processor() { } void Fast5Processor::parallel_run(fast5_processor_work_function func) { // store number of threads so we can restore it after we're done int prev_num_threads = omp_get_num_threads(); omp_set_num_threads(m_num_threads); for(size_t i = 0; i < m_fast5s.size(); ++i) { fast5_file f5_file = fast5_open(m_fast5s[i]); if(!fast5_is_open(f5_file)) { continue; } std::vector<Fast5Data> fast5_data; std::vector<std::string> reads = fast5_get_multi_read_groups(f5_file); for(size_t j = 0; j < reads.size(); j++) { // groups have names like "read_<uuid>" // we're only interested in the uuid bit assert(reads[j].find("read_") == 0); std::string read_name = reads[j].substr(5); Fast5Data data; data.is_valid = true; data.read_name = read_name; // metadata data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name); data.experiment_type = fast5_get_experiment_type(f5_file, read_name); // raw data data.channel_params = fast5_get_channel_params(f5_file, read_name); data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params); data.start_time = fast5_get_start_time(f5_file, read_name); fast5_data.push_back(data); } fast5_close(f5_file); // run in parallel #pragma omp parallel for schedule(dynamic) for(size_t j = 0; j < fast5_data.size(); ++j) { func(fast5_data[j]); } // destroy fast5 data for(size_t j = 0; j < fast5_data.size(); ++j) { free(fast5_data[j].rt.raw); fast5_data[j].rt.raw = NULL; } fast5_data.clear(); } // restore number of threads omp_set_num_threads(prev_num_threads); }
33.105263
85
0.575199
Yufeng98
233b9832a92c5b20230f771ad0ada6e425ffa32f
1,305
cpp
C++
leetcode/problems/medium/784-letter-case-permutation.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/784-letter-case-permutation.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/784-letter-case-permutation.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Letter Case Permutation https://leetcode.com/problems/letter-case-permutation/ Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create. You can return the output in any order. Example 1: Input: S = "a1b2" Output: ["a1b2","a1B2","A1b2","A1B2"] Example 2: Input: S = "3z4" Output: ["3z4","3Z4"] Example 3: Input: S = "12345" Output: ["12345"] Example 4: Input: S = "0" Output: ["0"] Constraints: S will be a string with length between 1 and 12. S will consist only of letters or digits. */ class Solution { public: void backtrack(string &s, int i, vector<string> &ans) { if(i == s.size()) { ans.push_back(s); return; } // handle letter / digit backtrack(s, i + 1, ans); if(isalpha(s[i])) { // A: 1 0000 0001 // a: 1 0010 0001 // Z: 1 0001 1010 // z: 1 0011 1010 // a -> A / A -> a s[i] ^= (1 << 5); // A -> a / a -> A backtrack(s, i + 1, ans); } } vector<string> letterCasePermutation(string S) { vector<string> ans; backtrack(S, 0, ans); return ans; } };
21.75
115
0.544828
wingkwong
233dbdcd6e0bdebc9558c82e25aff45d1cf28385
18,563
hpp
C++
viennacl/linalg/direct_solve.hpp
bollig/viennacl
6dac70e558ed42abe63d8c5bfd08465aafeda859
[ "MIT" ]
1
2020-09-21T08:33:10.000Z
2020-09-21T08:33:10.000Z
viennacl/linalg/direct_solve.hpp
bollig/viennacl
6dac70e558ed42abe63d8c5bfd08465aafeda859
[ "MIT" ]
null
null
null
viennacl/linalg/direct_solve.hpp
bollig/viennacl
6dac70e558ed42abe63d8c5bfd08465aafeda859
[ "MIT" ]
null
null
null
#ifndef VIENNACL_LINALG_DIRECT_SOLVE_HPP_ #define VIENNACL_LINALG_DIRECT_SOLVE_HPP_ /* ========================================================================= Copyright (c) 2010-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. Portions of this software are copyright by UChicago Argonne, LLC. ----------------- ViennaCL - The Vienna Computing Library ----------------- Project Head: Karl Rupp rupp@iue.tuwien.ac.at (A list of authors and contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ============================================================================= */ /** @file viennacl/linalg/direct_solve.hpp @brief Implementations of dense direct solvers are found here. */ #include "viennacl/forwards.h" #include "viennacl/meta/enable_if.hpp" #include "viennacl/vector.hpp" #include "viennacl/matrix.hpp" #include "viennacl/linalg/host_based/direct_solve.hpp" #ifdef VIENNACL_WITH_OPENCL #include "viennacl/linalg/opencl/direct_solve.hpp" #endif #ifdef VIENNACL_WITH_CUDA #include "viennacl/linalg/cuda/direct_solve.hpp" #endif namespace viennacl { namespace linalg { // // A \ B: // /** @brief Direct inplace solver for dense triangular systems. Matlab notation: A \ B * * @param A The system matrix * @param B The matrix of row vectors, where the solution is directly written to */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value >::type inplace_solve(const M1 & A, M2 & B, SOLVERTAG) { assert( (viennacl::traits::size1(A) == viennacl::traits::size2(A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)")); assert( (viennacl::traits::size1(A) == viennacl::traits::size1(B)) && bool("Size check failed in inplace_solve(): size1(A) != size1(B)")); switch (viennacl::traits::handle(A).get_active_handle_id()) { case viennacl::MAIN_MEMORY: viennacl::linalg::host_based::inplace_solve(A, B, SOLVERTAG()); break; #ifdef VIENNACL_WITH_OPENCL case viennacl::OPENCL_MEMORY: viennacl::linalg::opencl::inplace_solve(A, B, SOLVERTAG()); break; #endif #ifdef VIENNACL_WITH_CUDA case viennacl::CUDA_MEMORY: viennacl::linalg::cuda::inplace_solve(A, B, SOLVERTAG()); break; #endif default: throw "not implemented"; } } /** @brief Direct inplace solver for dense triangular systems with transposed right hand side * * @param A The system matrix * @param proxy_B The transposed matrix of row vectors, where the solution is directly written to */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value >::type inplace_solve(const M1 & A, matrix_expression< const M2, const M2, op_trans> proxy_B, SOLVERTAG) { assert( (viennacl::traits::size1(A) == viennacl::traits::size2(A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)")); assert( (viennacl::traits::size1(A) == viennacl::traits::size1(proxy_B)) && bool("Size check failed in inplace_solve(): size1(A) != size1(B^T)")); switch (viennacl::traits::handle(A).get_active_handle_id()) { case viennacl::MAIN_MEMORY: viennacl::linalg::host_based::inplace_solve(A, proxy_B, SOLVERTAG()); break; #ifdef VIENNACL_WITH_OPENCL case viennacl::OPENCL_MEMORY: viennacl::linalg::opencl::inplace_solve(A, proxy_B, SOLVERTAG()); break; #endif #ifdef VIENNACL_WITH_CUDA case viennacl::CUDA_MEMORY: viennacl::linalg::cuda::inplace_solve(A, proxy_B, SOLVERTAG()); break; #endif default: throw "not implemented"; } } //upper triangular solver for transposed lower triangular matrices /** @brief Direct inplace solver for dense triangular systems that stem from transposed triangular systems * * @param proxy_A The system matrix proxy * @param B The matrix holding the load vectors, where the solution is directly written to */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value >::type inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A, M2 & B, SOLVERTAG) { assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size2(proxy_A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)")); assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size1(B)) && bool("Size check failed in inplace_solve(): size1(A^T) != size1(B)")); switch (viennacl::traits::handle(proxy_A.lhs()).get_active_handle_id()) { case viennacl::MAIN_MEMORY: viennacl::linalg::host_based::inplace_solve(proxy_A, B, SOLVERTAG()); break; #ifdef VIENNACL_WITH_OPENCL case viennacl::OPENCL_MEMORY: viennacl::linalg::opencl::inplace_solve(proxy_A, B, SOLVERTAG()); break; #endif #ifdef VIENNACL_WITH_CUDA case viennacl::CUDA_MEMORY: viennacl::linalg::cuda::inplace_solve(proxy_A, B, SOLVERTAG()); break; #endif default: throw "not implemented"; } } /** @brief Direct inplace solver for dense transposed triangular systems with transposed right hand side. Matlab notation: A' \ B' * * @param proxy_A The system matrix proxy * @param proxy_B The matrix holding the load vectors, where the solution is directly written to */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value >::type inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A, matrix_expression< const M2, const M2, op_trans> proxy_B, SOLVERTAG) { assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size2(proxy_A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)")); assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size1(proxy_B)) && bool("Size check failed in inplace_solve(): size1(A^T) != size1(B^T)")); switch (viennacl::traits::handle(proxy_A.lhs()).get_active_handle_id()) { case viennacl::MAIN_MEMORY: viennacl::linalg::host_based::inplace_solve(proxy_A, proxy_B, SOLVERTAG()); break; #ifdef VIENNACL_WITH_OPENCL case viennacl::OPENCL_MEMORY: viennacl::linalg::opencl::inplace_solve(proxy_A, proxy_B, SOLVERTAG()); break; #endif #ifdef VIENNACL_WITH_CUDA case viennacl::CUDA_MEMORY: viennacl::linalg::cuda::inplace_solve(proxy_A, proxy_B, SOLVERTAG()); break; #endif default: throw "not implemented"; } } // // A \ b // template <typename M1, typename V1, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_vector<V1>::value >::type inplace_solve(const M1 & mat, V1 & vec, SOLVERTAG) { assert( (mat.size1() == vec.size()) && bool("Size check failed in inplace_solve(): size1(A) != size(b)")); assert( (mat.size2() == vec.size()) && bool("Size check failed in inplace_solve(): size2(A) != size(b)")); switch (viennacl::traits::handle(mat).get_active_handle_id()) { case viennacl::MAIN_MEMORY: viennacl::linalg::host_based::inplace_solve(mat, vec, SOLVERTAG()); break; #ifdef VIENNACL_WITH_OPENCL case viennacl::OPENCL_MEMORY: viennacl::linalg::opencl::inplace_solve(mat, vec, SOLVERTAG()); break; #endif #ifdef VIENNACL_WITH_CUDA case viennacl::CUDA_MEMORY: viennacl::linalg::cuda::inplace_solve(mat, vec, SOLVERTAG()); break; #endif default: throw "not implemented"; } } /** @brief Direct inplace solver for dense upper triangular systems that stem from transposed lower triangular systems * * @param proxy The system matrix proxy * @param vec The load vector, where the solution is directly written to */ template <typename M1, typename V1, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_vector<V1>::value >::type inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy, V1 & vec, SOLVERTAG) { assert( (proxy.lhs().size1() == vec.size()) && bool("Size check failed in inplace_solve(): size1(A) != size(b)")); assert( (proxy.lhs().size2() == vec.size()) && bool("Size check failed in inplace_solve(): size2(A) != size(b)")); switch (viennacl::traits::handle(proxy.lhs()).get_active_handle_id()) { case viennacl::MAIN_MEMORY: viennacl::linalg::host_based::inplace_solve(proxy, vec, SOLVERTAG()); break; #ifdef VIENNACL_WITH_OPENCL case viennacl::OPENCL_MEMORY: viennacl::linalg::opencl::inplace_solve(proxy, vec, SOLVERTAG()); break; #endif #ifdef VIENNACL_WITH_CUDA case viennacl::CUDA_MEMORY: viennacl::linalg::cuda::inplace_solve(proxy, vec, SOLVERTAG()); break; #endif default: throw "not implemented"; } } /////////////////// general wrappers for non-inplace solution ////////////////////// namespace detail { template <typename T> struct extract_embedded_type { typedef T type; }; template <typename T> struct extract_embedded_type< matrix_range<T> > { typedef T type; }; template <typename T> struct extract_embedded_type< matrix_slice<T> > { typedef T type; }; template <typename T> struct extract_embedded_type< vector_range<T> > { typedef T type; }; template <typename T> struct extract_embedded_type< vector_slice<T> > { typedef T type; }; } /** @brief Convenience functions for C = solve(A, B, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve() * * @param A The system matrix * @param B The matrix of load vectors * @param tag Dispatch tag */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value, typename detail::extract_embedded_type<M2>::type >::type solve(const M1 & A, const M2 & B, SOLVERTAG tag) { typedef typename detail::extract_embedded_type<M2>::type MatrixType; // do an inplace solve on the result vector: MatrixType result(B); inplace_solve(A, result, tag); return result; } ////////// /** @brief Convenience functions for C = solve(A, B^T, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve() * * @param A The system matrix * @param proxy The transposed load vector * @param tag Dispatch tag */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value, typename detail::extract_embedded_type<M2>::type >::type solve(const M1 & A, const matrix_expression< const M2, const M2, op_trans> & proxy, SOLVERTAG tag) { typedef typename detail::extract_embedded_type<M2>::type MatrixType; // do an inplace solve on the result vector: MatrixType result(proxy); inplace_solve(A, result, tag); return result; } /** @brief Convenience functions for result = solve(mat, vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve() * * @param mat The system matrix * @param vec The load vector * @param tag Dispatch tag */ template<typename M1, typename V1, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_vector<V1>::value, typename detail::extract_embedded_type<V1>::type >::type solve(const M1 & mat, const V1 & vec, SOLVERTAG const & tag) { // do an inplace solve on the result vector: typename detail::extract_embedded_type<V1>::type result(vec); inplace_solve(mat, result, tag); return result; } ///////////// transposed system matrix: /** @brief Convenience functions for result = solve(trans(mat), B, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve() * * @param proxy The transposed system matrix proxy * @param B The matrix of load vectors * @param tag Dispatch tag */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value, typename detail::extract_embedded_type<M2>::type >::type solve(const matrix_expression< const M1, const M1, op_trans> & proxy, const M2 & B, SOLVERTAG tag) { typedef typename detail::extract_embedded_type<M2>::type MatrixType; // do an inplace solve on the result vector: MatrixType result(B); inplace_solve(proxy, result, tag); return result; } /** @brief Convenience functions for result = solve(trans(mat), vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve() * * @param proxy_A The transposed system matrix proxy * @param proxy_B The transposed matrix of load vectors, where the solution is directly written to * @param tag Dispatch tag */ template <typename M1, typename M2, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_matrix<M2>::value, typename detail::extract_embedded_type<M2>::type >::type solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A, const matrix_expression< const M2, const M2, op_trans> & proxy_B, SOLVERTAG tag) { typedef typename detail::extract_embedded_type<M2>::type MatrixType; // do an inplace solve on the result vector: MatrixType result(proxy_B); inplace_solve(proxy_A, result, tag); return result; } /** @brief Convenience functions for result = solve(trans(mat), vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve() * * @param proxy The transposed system matrix proxy * @param vec The load vector, where the solution is directly written to * @param tag Dispatch tag */ template<typename M1, typename V1, typename SOLVERTAG> typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value && viennacl::is_any_dense_nonstructured_vector<V1>::value, typename detail::extract_embedded_type<V1>::type >::type solve(const matrix_expression< const M1, const M1, op_trans> & proxy, const V1 & vec, SOLVERTAG const & tag) { // do an inplace solve on the result vector: typename detail::extract_embedded_type<V1>::type result(vec); inplace_solve(proxy, result, tag); return result; } } } #endif
39.495745
164
0.575661
bollig
2342b0b19f851d7dda2cc6af31c32e3b1163ec82
15,043
cpp
C++
src/content_loader.cpp
adct-the-experimenter/DTL-Dungeon-Editor
6e97f56effbec3923b85bf5753b408aec10f863f
[ "BSD-3-Clause" ]
null
null
null
src/content_loader.cpp
adct-the-experimenter/DTL-Dungeon-Editor
6e97f56effbec3923b85bf5753b408aec10f863f
[ "BSD-3-Clause" ]
null
null
null
src/content_loader.cpp
adct-the-experimenter/DTL-Dungeon-Editor
6e97f56effbec3923b85bf5753b408aec10f863f
[ "BSD-3-Clause" ]
null
null
null
#include "content_loader.h" #include "pugixml.hpp" #include <iostream> #include <string> #include "globalvariables.h" #include "sprite.h" enemy_content_map enemyContentMap; void SetEnemyContentFromEnemyDirXMLFile(std::string xml_enemy_scripts_file_dir, std::string xml_enemy_scripts_file_path) { // Create empty XML document within memory pugi::xml_document doc; // Load XML file into memory // Remark: to fully read declaration entries you have to specify // "pugi::parse_declaration" pugi::xml_parse_result result = doc.load_file(xml_enemy_scripts_file_path.c_str(), pugi::parse_default); if (!result) { std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset; return; } pugi::xml_node enemyDirRoot = doc.child("EnemyDirRoot"); size_t iterator = 0; //go through each tile type in tiles node for (pugi::xml_node enemyNode = enemyDirRoot.first_child(); enemyNode; enemyNode = enemyNode.next_sibling()) { std::string valName = enemyNode.attribute("name").value(); std::string valFilepath = enemyNode.attribute("scriptfilepath").value(); std::string valMediaDir = enemyNode.attribute("mediaDir").value(); std::string valXMLDefFilepath = enemyNode.attribute("xmldefpath").value(); //assuming file paths in xml file is set relative to xml filepath itself std::string filepath = xml_enemy_scripts_file_dir + "/" + valFilepath; std::cout << "file read:" << filepath << std::endl; std::string mediaDir = xml_enemy_scripts_file_dir + "/" + valMediaDir; std::string xml_def_fp = xml_enemy_scripts_file_dir + "/" + valXMLDefFilepath; EnemyContent ec; ec.name = valName; ec.script_filepath = filepath; ec.mediaDir = mediaDir; ec.xml_def_filepath = xml_def_fp; std::pair<std::string,EnemyContent> thisEnemyContentPair (valName,ec); enemyContentMap.insert (thisEnemyContentPair); iterator++; } } void LoadContentFromXMLFiles() { std::string xml_enemy_scripts_file_dir = DATADIR_STR + "/EnemyPacks"; std::string xml_enemy_scripts_file_path = xml_enemy_scripts_file_dir + "/enemy_directory.xml"; SetEnemyContentFromEnemyDirXMLFile(xml_enemy_scripts_file_dir,xml_enemy_scripts_file_path); } bool loadScriptedEnemyVisualMedia(std::string xml_file_path,std::string xml_file_dir, LTexture* cTexture, std::vector <SDL_Rect> &walk_clips, SDL_Renderer* gRenderer ) { // Create empty XML document within memory pugi::xml_document doc; // Load XML file into memory // Remark: to fully read declaration entries you have to specify // "pugi::parse_declaration" pugi::xml_parse_result result = doc.load_file(xml_file_path.c_str(), pugi::parse_default); if (!result) { std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset; return false; } pugi::xml_node root = doc.child("EnemyRoot"); std::string cTexFilePath = xml_file_dir + "/" + root.child("Texture").attribute("path").value(); //initialize texture if(!cTexture->loadFromFile(cTexFilePath.c_str(),gRenderer) ) { std::cout << "scripted enemy image loading failed! \n"; std::cout << "filepath:" << cTexFilePath << std::endl; return false; } else { std::string valString; //set size of walk clips vector valString = root.child("WalkClips").child("clip_num").attribute("number").value(); size_t clipsNum = atoi(valString.c_str()); walk_clips.resize(clipsNum); //set width and height of each uniform clips valString = root.child("WalkClips").child("clip_width").attribute("width").value(); std::int8_t width = atoi(valString.c_str()); valString = root.child("WalkClips").child("clip_height").attribute("height").value(); std::int8_t height = atoi(valString.c_str()); SDL_Rect clip; clip.w = width; clip.h = height; valString = root.child("WalkClips").child("UP_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_1] = clip; valString = root.child("WalkClips").child("UP_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_2] = clip; valString = root.child("WalkClips").child("UP_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_3] = clip; valString = root.child("WalkClips").child("UP_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_4] = clip; valString = root.child("WalkClips").child("UP_LEFT_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_LEFT_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_LEFT_1] = clip; valString = root.child("WalkClips").child("UP_LEFT_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_LEFT_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_LEFT_2] = clip; valString = root.child("WalkClips").child("UP_LEFT_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_LEFT_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_LEFT_3] = clip; valString = root.child("WalkClips").child("UP_LEFT_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_LEFT_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_LEFT_4] = clip; valString = root.child("WalkClips").child("LEFT_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("LEFT_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::LEFT_1] = clip; valString = root.child("WalkClips").child("LEFT_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("LEFT_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::LEFT_2] = clip; valString = root.child("WalkClips").child("LEFT_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("LEFT_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::LEFT_3] = clip; valString = root.child("WalkClips").child("LEFT_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("LEFT_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::LEFT_4] = clip; valString = root.child("WalkClips").child("DOWN_LEFT_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_LEFT_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_LEFT_1] = clip; valString = root.child("WalkClips").child("DOWN_LEFT_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_LEFT_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_LEFT_2] = clip; valString = root.child("WalkClips").child("DOWN_LEFT_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_LEFT_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_LEFT_3] = clip; valString = root.child("WalkClips").child("DOWN_LEFT_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_LEFT_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_LEFT_4] = clip; valString = root.child("WalkClips").child("DOWN_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_1] = clip; valString = root.child("WalkClips").child("DOWN_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_2] = clip; valString = root.child("WalkClips").child("UP_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_3] = clip; valString = root.child("WalkClips").child("DOWN_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_4] = clip; valString = root.child("WalkClips").child("RIGHT_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("RIGHT_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::RIGHT_1] = clip; valString = root.child("WalkClips").child("RIGHT_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("RIGHT_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::RIGHT_2] = clip; valString = root.child("WalkClips").child("RIGHT_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("RIGHT_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::RIGHT_3] = clip; valString = root.child("WalkClips").child("RIGHT_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("RIGHT_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::RIGHT_4] = clip; valString = root.child("WalkClips").child("DOWN_RIGHT_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_RIGHT_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_RIGHT_1] = clip; valString = root.child("WalkClips").child("DOWN_RIGHT_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_RIGHT_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_RIGHT_2] = clip; valString = root.child("WalkClips").child("DOWN_RIGHT_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_RIGHT_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_RIGHT_3] = clip; valString = root.child("WalkClips").child("DOWN_RIGHT_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("DOWN_RIGHT_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::DOWN_RIGHT_4] = clip; valString = root.child("WalkClips").child("UP_RIGHT_1").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_RIGHT_1").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_RIGHT_1] = clip; valString = root.child("WalkClips").child("UP_RIGHT_2").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_RIGHT_2").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_RIGHT_2] = clip; valString = root.child("WalkClips").child("UP_RIGHT_3").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_RIGHT_3").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_RIGHT_3] = clip; valString = root.child("WalkClips").child("UP_RIGHT_4").attribute("x").value(); clip.x = atoi(valString.c_str());; valString = root.child("WalkClips").child("UP_RIGHT_4").attribute("y").value(); clip.y = atoi(valString.c_str());; walk_clips[Sprite::UP_RIGHT_4] = clip; } return true; } void freeScriptedEnemyVisualMedia(LTexture* cTexture) { if(cTexture != nullptr) { cTexture = nullptr; } } bool setEnemyTypeAttributes(EnemyContent* thisEnemyContent, std::string xml_file_path) { // Create empty XML document within memory pugi::xml_document doc; // Load XML file into memory // Remark: to fully read declaration entries you have to specify // "pugi::parse_declaration" pugi::xml_parse_result result = doc.load_file(xml_file_path.c_str(), pugi::parse_default); if (!result) { std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset; return false; } pugi::xml_node root = doc.child("EnemyRoot"); std::string healthStr = root.child("Attributes").attribute("health").value(); std::string speedStr = root.child("Attributes").attribute("speed").value(); thisEnemyContent->health = std::stoi(healthStr); thisEnemyContent->speed = std::stof(speedStr); return true; }
42.85755
109
0.62082
adct-the-experimenter
2347f795da7678007632158d192f842b7f34764e
31,446
cpp
C++
dbmanager.cpp
svasighi/UMIS
4d930bbc6749e92ce1b8889bf8556ec3c68f50e0
[ "MIT" ]
1
2020-01-08T19:57:08.000Z
2020-01-08T19:57:08.000Z
dbmanager.cpp
svasighi/UMIS
4d930bbc6749e92ce1b8889bf8556ec3c68f50e0
[ "MIT" ]
null
null
null
dbmanager.cpp
svasighi/UMIS
4d930bbc6749e92ce1b8889bf8556ec3c68f50e0
[ "MIT" ]
null
null
null
#include "dbmanager.h" #include <QDir> #include <QFile> #include <QMessageBox> #include <math.h> DbManager::DbManager() { m_db = QSqlDatabase::addDatabase("QSQLITE", "Connection"); QString db_path = QDir::currentPath(); db_path = db_path + QString("/university.db"); m_db.setDatabaseName(db_path); if (m_db.isOpen()) { QMessageBox msgBox; qDebug() << "opened"; } else { if (!m_db.open()) qDebug() << m_db.lastError(); } } DbManager::~DbManager() { if (m_db.isOpen()) { m_db.close(); } } bool DbManager::deleteProfessor(int username) { if (ProfessorExist(username)) { QSqlQuery query(m_db); query.prepare("DELETE FROM professors WHERE username = (:username)"); query.bindValue(":username", username); bool success = query.exec(); if (!success) { qDebug() << "removeProf error: " << query.lastError(); return false; } return true; } } Professor* DbManager::getProfessor(int username) { QSqlQuery query(m_db); query.prepare("SELECT * FROM professors WHERE username = :username "); query.bindValue(":username", username); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch professors"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int username = username; QString password = query.value(2).toString(); QString firstname = query.value(3).toString(); QString lastname = query.value(4).toString(); int departmentcode = query.value(5).toInt(); int groupcode = query.value(6).toInt(); QString object_type = query.value(7).toString(); int is_supervisor = query.value(8).toInt(); int degree = query.value(9).toInt(); if (object_type == "faculty") { Faculty* ProfessorTemp = new Faculty(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); return dynamic_cast<Professor*> (ProfessorTemp); } else if (object_type == "adjunctprofessor") { AdjunctProfessor* ProfessorTemp = new AdjunctProfessor(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode); return dynamic_cast<Professor*> (ProfessorTemp); } else if (object_type == "groupmanager") { GroupManager* ProfessorTemp = new GroupManager(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); return dynamic_cast<Professor*> (ProfessorTemp); } else if (object_type == "departmentacademicassistant") { // } else if (object_type == "departmenthead") { DepartmentHead* ProfessorTemp = new DepartmentHead(username, lastname.toStdString(), password.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); return dynamic_cast<Professor*> (ProfessorTemp); } } } bool DbManager::addProfessor(int username, const QString& password, const QString& firstname, const QString& lastname, const int& departmentcode, const int& groupcode, const QString& object_type, const int& is_supervisor, const int& degree) { bool success = false; QSqlQuery query(m_db); query.prepare("INSERT INTO professors (username,password,firstname,lastname,departmentcode,groupcode,object_type,is_supervisor,degree) VALUES (:username,:password,:firstname,:lastname,:departmentcode,:groupcode,:object_type,:is_supervisor,:degree)"); query.bindValue(":username", username); query.bindValue(":password", QString(QCryptographicHash::hash((password.toUtf8()), QCryptographicHash::Md5).toHex())); query.bindValue(":firstname", firstname); query.bindValue(":lastname", lastname); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); query.bindValue(":object_type", object_type); query.bindValue(":is_supervisor", is_supervisor); query.bindValue(":degree", degree); if (query.exec()) { success = true; } else { qDebug() << "addProfessor error: " << query.lastError(); } return success; } bool DbManager::ProfessorExist(int username) { QSqlQuery query(m_db); query.prepare("SELECT username FROM professors WHERE username = (:username)"); query.bindValue(":username", username); if (query.exec()) { if (query.next()) { return true; } } return false; } std::vector<Professor*> DbManager::allProfessors(void) { std::vector<Professor*> professors; QSqlQuery query(m_db); query.prepare("SELECT username, password, firstname, lastname, departmentcode, groupcode, object_type, is_supervisor, degree FROM professors"); while (query.next()) { int username = query.value(0).toInt(); QString password = query.value(1).toString(); QString firstname = query.value(2).toString(); QString lastname = query.value(3).toString(); int departmentcode = query.value(4).toInt(); int groupcode = query.value(5).toInt(); QString object_type = query.value(6).toString(); int is_supervisor = query.value(7).toInt(); int degree = query.value(8).toInt(); if (object_type == "adjunctprofessor") { AdjunctProfessor* adjunct = new AdjunctProfessor(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode); professors.push_back(adjunct); } else if (object_type == "faculty") { Faculty* faculty = new Faculty(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); faculty->setDegree(query.value(1).toInt()); if (query.value(0).toInt()) faculty->setAsSupervisor(true); professors.push_back(faculty); } else if (object_type == "groupmanager") { GroupManager* groupmanager = new GroupManager(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); groupmanager->setDegree(query.value(1).toInt()); if (query.value(0).toInt()) groupmanager->setAsSupervisor(); professors.push_back(groupmanager); } else if (object_type == "departmentacademicassistant") { /* DepartmentAcademicAssistant* departmentacademicassistant = new DepartmentAcademicAssistant(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); departmentacademicassistant->setDegree(query.value(1).toInt()); if(query.value(0).toInt()) departmentacademicassistant->setAsSupervisor(); professors.push_back(departmentacademicassistant); */ } else if (object_type == "departmenthead") { DepartmentHead* departmenthead = new DepartmentHead(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree); departmenthead->setDegree(query.value(1).toInt()); if (query.value(0).toInt()) departmenthead->setAsSupervisor(); professors.push_back(departmenthead); } } return professors; } Student* DbManager::getStudent(int username) { QSqlQuery query(m_db); query.prepare("SELECT * FROM students WHERE username = :username "); query.bindValue(":username", username); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch students"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int username = username; QString password = query.value(2).toString(); QString firstname = query.value(3).toString(); QString lastname = query.value(4).toString(); int departmentcode = query.value(5).toInt(); int groupcode = query.value(6).toInt(); int type = query.value(7).toInt(); QString field = query.value(8).toString(); Student* StudentTemp = new Student(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, type, field.toStdString(), groupcode); return StudentTemp; } } bool DbManager::addStudent(int username, const QString& password, const QString& firstname, const QString& lastname, const int& departmentcode, const int& groupcode, const int& type, const QString& field) { bool success = false; QSqlQuery query(m_db); query.prepare("INSERT INTO students (username, password, firstname, lastname, departmentcode, groupcode, type, field) VALUES (:username,:password,:firstname,:lastname,:departmentcode,:groupcode,:type,:field)"); query.bindValue(":username", username); query.bindValue(":password", QString(QCryptographicHash::hash((password.toUtf8()), QCryptographicHash::Md5).toHex())); query.bindValue(":firstname", firstname); query.bindValue(":lastname", lastname); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); query.bindValue(":type", type); query.bindValue(":field", field); if (query.exec()) { success = true; } else { qDebug() << "addProfessor error: " << query.lastError(); } return success; } bool DbManager::StudentExist(int username) { QSqlQuery query(m_db); query.prepare("SELECT username FROM students WHERE username = (:username)"); query.bindValue(":username", username); if (query.exec()) { if (query.next()) { return true; } } return false; } std::vector<Student*> DbManager::allStudents(void) { std::vector<Student*> students; QSqlQuery query(m_db); query.prepare("SELECT username, password, firstname,lastname, departmentcode, groupcode, type, field FROM students"); while (query.next()) { int username = query.value(1).toInt(); QString password = query.value(2).toString(); QString firstname = query.value(3).toString(); QString lastname = query.value(4).toString(); int departmentcode = query.value(5).toInt(); int groupcode = query.value(6).toInt(); int type = query.value(7).toInt(); QString field = query.value(8).toString(); Student* stu = new Student(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, type, field.toStdString(), groupcode); students.push_back(stu); } return students; } bool DbManager::addCourse(const int& departmentcode, const int& groupcode,const int& coursecode, const int& credit, const QString& name, const int& type) { bool success = false; QSqlQuery query(m_db); query.prepare("INSERT INTO courses (departmentcode, groupcode, coursecode, credit, name, type) VALUES (:departmentcode,:groupcode,:coursecode,:credit,:name,:type)"); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); query.bindValue(":coursecode", coursecode); query.bindValue(":credit", credit); query.bindValue(":name", name); query.bindValue(":type", type); if (query.exec()) { success = true; } else { qDebug() << "addCourse error: " << query.lastError(); } return success; } bool DbManager::courseExistByCode(int departmentcode,int groupcode ,int coursecode){ QSqlQuery query(m_db); query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode"); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); query.bindValue(":coursecode", coursecode); if (query.exec()) { if (query.next()) { return true; } } return false; } bool DbManager::deleteCourseByCode(int departmentcode,int groupcode ,int coursecode){ if (courseExistByCode(departmentcode ,groupcode ,coursecode)) { QSqlQuery query(m_db); query.prepare("DELETE FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode"); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); query.bindValue(":coursecode", coursecode); bool success = query.exec(); if (!success) { qDebug() << "removeCourse error: " << query.lastError(); return false; } return true; } } Course* DbManager::getCourseByCode(int departmentcode,int groupcode ,int coursecode){ QSqlQuery query(m_db); query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode"); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); query.bindValue(":coursecode", coursecode); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int departmentcode = query.value(1).toInt(); int groupcode = query.value(2).toInt(); int coursecode = query.value(3).toInt(); int credit = query.value(4).toInt(); QString name = query.value(5).toString(); int type = query.value(6).toInt(); Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type); return CourseTemp; } } std::vector<Course*> DbManager::allCourse(void){ std::vector<Course*> courses; QSqlQuery query(m_db); query.prepare("SELECT * FROM courses"); while (query.next()) { int departmentcode = query.value(1).toInt(); int groupcode = query.value(2).toInt(); int coursecode = query.value(3).toInt(); int credit = query.value(4).toInt(); QString name = query.value(5).toString(); int type = query.value(6).toInt(); Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type); courses.push_back(CourseTemp); } return courses; } std::vector<Course*> DbManager::getCourseByDepartment(int departmentcode){ std::vector<Course*> courses; QSqlQuery query(m_db); query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode"); query.bindValue(":departmentcode", departmentcode); while (query.next()) { int departmentcode = query.value(1).toInt(); int groupcode = query.value(2).toInt(); int coursecode = query.value(3).toInt(); int credit = query.value(4).toInt(); QString name = query.value(5).toString(); int type = query.value(6).toInt(); Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type); courses.push_back(CourseTemp); } return courses; } std::vector<Course*> DbManager::getCourseByGroup(int departmentcode , int groupcode){ std::vector<Course*> courses; QSqlQuery query(m_db); query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode "); query.bindValue(":departmentcode", departmentcode); query.bindValue(":groupcode", groupcode); while (query.next()) { int departmentcode = query.value(1).toInt(); int groupcode = query.value(2).toInt(); int coursecode = query.value(3).toInt(); int credit = query.value(4).toInt(); QString name = query.value(5).toString(); int type = query.value(6).toInt(); Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type); courses.push_back(CourseTemp); } return courses; } bool DbManager::addPresentedCourse(const int& course_id, const int& course_professor_id,const int& capacity, const int& enrolled_number, const int& waiting_number, const int& group_number, const int& term_number, std::vector<Course*> corequisit, std::vector<Course*> prerequisit) { QString prerequisit_string; for(int i = 0 ; i < prerequisit.size() ; i++) { prerequisit_string += prerequisit[i]->getCourseID() + ";"; } QString corequisit_string; for(int i = 0 ; i < corequisit.size() ; i++) { corequisit_string += corequisit[i]->getCourseID() + ";"; } bool success = false; QSqlQuery query(m_db); query.prepare("INSERT INTO presented_courses (course_id, course_professor_id, capacity, enrolled_number, waiting_number, group_number , term_number , corequisit , preriqisit) VALUES (:course_id,:course_professor_id,:capacity,:enrolled_number,:waiting_number,:group_number ,:term_number ,:corequisit ,:preriqisit)"); query.bindValue(":course_id", course_id); query.bindValue(":course_professor_id", course_professor_id); query.bindValue(":capacity", capacity); query.bindValue(":enrolled_number", enrolled_number); query.bindValue(":waiting_number", group_number); query.bindValue(":term_number", term_number); query.bindValue(":corequisit", corequisit_string.toUtf8()); query.bindValue(":prerequisit", prerequisit_string.toUtf8()); if (query.exec()) { success = true; } else { qDebug() << "addPresentedCourse error: " << query.lastError(); } return success; } bool DbManager::deletePresentedCourseByCode(const int& course_id ,const int& group_number,const int& term_number) { if (presentedCourseExistbyCode(course_id ,group_number ,term_number)) { QSqlQuery query(m_db); query.prepare("DELETE FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number"); query.bindValue(":course_id", course_id); query.bindValue(":group_number", group_number); query.bindValue(":term_number", term_number); bool success = query.exec(); if (!success) { qDebug() << "removePresentedCourse error: " << query.lastError(); return false; } return true; } } bool DbManager::presentedCourseExistbyCode(const int& course_id ,const int& group_number,const int& term_number) { QSqlQuery query(m_db); query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number"); query.bindValue(":course_id", course_id); query.bindValue(":group_number", group_number); query.bindValue(":term_number", term_number); if (query.exec()) { if (query.next()) { return true; } } return false; } PresentedCourse* DbManager::getPresentedCourseByCode(const int& course_id ,const int& group_number ,const int& term_number) { QSqlQuery query(m_db); query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number"); query.bindValue(":course_id", course_id); query.bindValue(":group_number", group_number); query.bindValue(":term_number", term_number); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int course_id = query.value(1).toInt(); int course_professor_id = query.value(2).toInt(); int capacity = query.value(3).toInt(); int enrolled_number = query.value(4).toInt(); int waiting_number = query.value(4).toInt(); int group_number = query.value(4).toInt(); int term_number = query.value(6).toInt(); int length = QString(course_id).length(); Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); Professor* professor_temp = getProfessor(course_professor_id); PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity); PresentedCourseTemp->setEnrolledNumber(enrolled_number); PresentedCourseTemp->setWaitingNumber(waiting_number); QStringList corequisit_list = query.value(5).toString().split(';'); QStringList prerequisit_list = query.value(5).toString().split(';'); for(int i =0 ; i < corequisit_list.count();i++) { int length = corequisit_list.at(i).length(); Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addCorequisite(coCoursTemp); } for(int i =0 ; i < prerequisit_list.count();i++) { int length = prerequisit_list.at(i).length(); Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addPrerequisite(preCoursTemp); } return PresentedCourseTemp; } } std::vector<PresentedCourse*> DbManager::allPresentedCourse(void){ std::vector<PresentedCourse*> presentedcourses; QSqlQuery query(m_db); query.prepare("SELECT * FROM presented_courses"); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int course_id = query.value(1).toInt(); int course_professor_id = query.value(2).toInt(); int capacity = query.value(3).toInt(); int enrolled_number = query.value(4).toInt(); int waiting_number = query.value(4).toInt(); int group_number = query.value(4).toInt(); int term_number = query.value(6).toInt(); int length = QString(course_id).length(); Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); Professor* professor_temp = getProfessor(course_professor_id); PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity); PresentedCourseTemp->setEnrolledNumber(enrolled_number); PresentedCourseTemp->setWaitingNumber(waiting_number); presentedcourses.push_back(PresentedCourseTemp); QStringList corequisit_list = query.value(5).toString().split(';'); QStringList prerequisit_list = query.value(5).toString().split(';'); for(int i =0 ; i < corequisit_list.count();i++) { int length = corequisit_list.at(i).length(); Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addCorequisite(coCoursTemp); } for(int i =0 ; i < prerequisit_list.count();i++) { int length = prerequisit_list.at(i).length(); Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addPrerequisite(preCoursTemp); } } return presentedcourses; } std::vector<PresentedCourse*> DbManager::getPresentedCourseByCourseId(const int& _course_id ,const int& _term_number){ std::vector<PresentedCourse*> presentedcourses; QSqlQuery query(m_db); query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND term_number = :term_number"); query.bindValue(":course_id", _course_id); query.bindValue(":term_number", _term_number); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int course_id = query.value(1).toInt(); int course_professor_id = query.value(2).toInt(); int capacity = query.value(3).toInt(); int enrolled_number = query.value(4).toInt(); int waiting_number = query.value(4).toInt(); int group_number = query.value(4).toInt(); int term_number = query.value(6).toInt(); int length = QString(course_id).length(); Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); Professor* professor_temp = getProfessor(course_professor_id); PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity); PresentedCourseTemp->setEnrolledNumber(enrolled_number); PresentedCourseTemp->setWaitingNumber(waiting_number); presentedcourses.push_back(PresentedCourseTemp); QStringList corequisit_list = query.value(5).toString().split(';'); QStringList prerequisit_list = query.value(5).toString().split(';'); for(int i =0 ; i < corequisit_list.count();i++) { int length = corequisit_list.at(i).length(); Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addCorequisite(coCoursTemp); } for(int i =0 ; i < prerequisit_list.count();i++) { int length = prerequisit_list.at(i).length(); Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addPrerequisite(preCoursTemp); } } return presentedcourses; } std::vector<PresentedCourse*> DbManager::getPresentedCourseByCourseProfessorId(const int& course_professor_id ,const int& term_number){ std::vector<PresentedCourse*> presentedcourses; QSqlQuery query(m_db); query.prepare("SELECT * FROM presented_courses WHERE course_professor_id = :course_professor_id AND term_number = :term_number"); query.bindValue(":course_professor_id", course_professor_id); query.bindValue(":term_number", term_number); if (!query.exec()) { qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course"; qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName(); } if (query.next()) { int course_id = query.value(1).toInt(); int course_professor_id = query.value(2).toInt(); int capacity = query.value(3).toInt(); int enrolled_number = query.value(4).toInt(); int waiting_number = query.value(4).toInt(); int group_number = query.value(4).toInt(); int term_number = query.value(6).toInt(); int length = QString(course_id).length(); Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); Professor* professor_temp = getProfessor(course_professor_id); PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity); PresentedCourseTemp->setEnrolledNumber(enrolled_number); PresentedCourseTemp->setWaitingNumber(waiting_number); presentedcourses.push_back(PresentedCourseTemp); QStringList corequisit_list = query.value(5).toString().split(';'); QStringList prerequisit_list = query.value(5).toString().split(';'); for(int i =0 ; i < corequisit_list.count();i++) { int length = corequisit_list.at(i).length(); Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addCorequisite(coCoursTemp); } for(int i =0 ; i < prerequisit_list.count();i++) { int length = prerequisit_list.at(i).length(); Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) ); PresentedCourseTemp->addPrerequisite(preCoursTemp); } } return presentedcourses; } std::vector<PresentedCourse*> DbManager::getPresentedCourseByDepartment(const int& departmentcode ,const int& term_number){ std::vector<Course*> departmentcourses = getCourseByDepartment(departmentcode); std::vector<PresentedCourse*> result ; for(int i = 0 ; i < departmentcourses.size(); i++ ){ int course_id = departmentcourses[i]->getCourseID(); std::vector<PresentedCourse*> departmentPresentedCourse = getPresentedCourseByCourseId(course_id ,term_number); for(int j = 0 ; j < departmentPresentedCourse.size(); j++ ){ result.push_back(departmentPresentedCourse[j]); } } return result; }
43.614424
319
0.645074
svasighi
23482a99736a6b10aed2567f92350be1b59d41fe
349
hpp
C++
NativePlugin/CaptainAsteroid/src/physics/components/Identity.hpp
axoloto/CaptainAsteroid
fcdcb6bc6987ecf53226daa7027116e40d74401a
[ "Apache-2.0" ]
null
null
null
NativePlugin/CaptainAsteroid/src/physics/components/Identity.hpp
axoloto/CaptainAsteroid
fcdcb6bc6987ecf53226daa7027116e40d74401a
[ "Apache-2.0" ]
null
null
null
NativePlugin/CaptainAsteroid/src/physics/components/Identity.hpp
axoloto/CaptainAsteroid
fcdcb6bc6987ecf53226daa7027116e40d74401a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "entityx/Entity.h" namespace CaptainAsteroidCPP { namespace Comp { enum class Id { Unknown, Asteroid, SpaceShip, LaserShot }; struct Identity : public entityx::Component<Identity> { Identity(Id _id = Id::Unknown) : id(_id){}; Id id; }; }// namespace Comp }// namespace CaptainAsteroidCPP
14.541667
55
0.659026
axoloto
234a2463845aca23371c81de23b68c50737f283d
1,002
cpp
C++
MonoNative.Tests/mscorlib/System/Threading/mscorlib_System_Threading_LockCookie_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Threading/mscorlib_System_Threading_LockCookie_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Threading/mscorlib_System_Threading_LockCookie_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Threading // Name: LockCookie // C++ Typed Name: mscorlib::System::Threading::LockCookie #include <gtest/gtest.h> #include <mscorlib/System/Threading/mscorlib_System_Threading_LockCookie.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Threading { //Public Methods Tests // Method GetHashCode // Signature: TEST(mscorlib_System_Threading_LockCookie_Fixture,GetHashCode_Test) { } // Method Equals // Signature: mscorlib::System::Threading::LockCookie obj TEST(mscorlib_System_Threading_LockCookie_Fixture,Equals_1_Test) { } // Method Equals // Signature: mscorlib::System::Object obj TEST(mscorlib_System_Threading_LockCookie_Fixture,Equals_2_Test) { } } } }
19.269231
88
0.719561
brunolauze
054b8ff3f294f45f74688bdadd81c04fc2cbde9d
2,162
cpp
C++
2D Graphics/Histograms/Sapostavyashta Vertikalna Histograma/main.cpp
BorisLechev/-University
c6a29bc7438733adb9f5818a9674f546187db555
[ "MIT" ]
null
null
null
2D Graphics/Histograms/Sapostavyashta Vertikalna Histograma/main.cpp
BorisLechev/-University
c6a29bc7438733adb9f5818a9674f546187db555
[ "MIT" ]
1
2022-03-02T09:56:43.000Z
2022-03-02T09:56:43.000Z
2D Graphics/Histograms/Sapostavyashta Vertikalna Histograma/main.cpp
BorisLechev/University
c6a29bc7438733adb9f5818a9674f546187db555
[ "MIT" ]
null
null
null
#include <iostream> #include <graphics.h> using namespace std; int main() { initwindow(800, 800); double startPointX = 100; double startPointY = 600; double windowSizeX = 600; double windowSizeY = 500; double columnWidth = 70; double distanceBetweenColumns = 70; double D = 60; double bi[] = {5, 26}; double ai[] = {15, 20}; double mi[] = {10, 12}; double amin = ai[0]; double amax = ai[0]; double bmin = bi[0]; double bmax = bi[0]; double sum[4]; double maxSum; for(int i = 0; i < 2; i++) { sum[i] = ai[i] + bi[i] + mi[i]; } maxSum = sum[0]; for(int i = 1; i < 3; i++) { if (sum[i] > maxSum) { maxSum = sum[i]; } } float scaleFactor = maxSum / windowSizeY; // koordinatna sistema line(startPointX, startPointY, startPointX + windowSizeX, startPointY); line(startPointX, startPointY, startPointX, startPointY - windowSizeY); // chertite na deleniyata // double value; // // for(p = 1; p < windowSizeY / D; p++) // { // line(startPointX, startPointY - p * D, startPointX - 3, startPointY - p * D); // value = p * D * scaleFactor; // cout << value << endl; // } for(int i = 1; i <= 2; i++) { bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth, startPointY - ai[i - 1] / scaleFactor, startPointX + i * (columnWidth + distanceBetweenColumns), startPointY); setfillstyle(i, i); bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth, startPointY - (ai[i - 1] + bi[i - 1]) / scaleFactor, startPointX + i * (columnWidth + distanceBetweenColumns), startPointY - ai[i - 1] / scaleFactor); setfillstyle(i + 1, i + 1); bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth, startPointY - (ai[i - 1] + bi[i - 1] + mi[i - 1]) / scaleFactor, startPointX + i * (columnWidth + distanceBetweenColumns), startPointY - (ai[i - 1] + bi[i - 1]) / scaleFactor); setfillstyle(i + 2, i + 2); } getch(); return 0; }
24.850575
81
0.567068
BorisLechev
054c821ee05d62550d458af50a06efa16b64be7e
977
cpp
C++
Software/GUI.cpp
seanziegler/TennisBallTracker
b4ad4c2f4a0394dc2e111769f58b8e8f9d77a853
[ "MIT" ]
1
2020-10-29T08:44:54.000Z
2020-10-29T08:44:54.000Z
Software/GUI.cpp
seanziegler/TennisBallTracker
b4ad4c2f4a0394dc2e111769f58b8e8f9d77a853
[ "MIT" ]
2
2019-07-25T15:23:54.000Z
2019-07-25T15:25:19.000Z
Software/GUI.cpp
seanziegler/TennisBallTracker
b4ad4c2f4a0394dc2e111769f58b8e8f9d77a853
[ "MIT" ]
null
null
null
#include "openCV.h" using namespace cv; class GUI { int lowH, lowS, lowV = 90; int highH = 180; int highS = 255, highV = 255; void lowHChange(int pos, void*) { int lowH = pos; } void lowSChange(int pos, void*) { int lowS = pos; } void lowVChange(int pos, void*) { int lowV = pos; } void highHChange(int pos, void*) { int highH = pos; } void highSChange(int pos, void*) { int highS = pos; } void highVChange(int pos, void*) { int highV = pos; } /*cv::namedWindow("HSV Value Selection"); const String HSVwindowName = "HSV Value Selection"; createTrackbar("Low H", HSVwindowName, 0, 180, lowHChange); createTrackbar("Low S", HSVwindowName, 0, 255, lowSChange); createTrackbar("Low V", HSVwindowName, 0, 255, lowVChange); createTrackbar("High H", HSVwindowName, &highH, 180, highHChange); createTrackbar("High S", HSVwindowName, &highS, 255, highSChange); createTrackbar("High V", HSVwindowName, &highV, 255, highVChange); */ };
19.54
67
0.669396
seanziegler
054d0de95f0452e026174ae515310216e4164f53
7,808
hpp
C++
src/ParallelAlgorithms/LinearSolver/Gmres/Gmres.hpp
fmahebert/spectre
936e2dff0434f169b9f5b03679cd27794003700a
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/ParallelAlgorithms/LinearSolver/Gmres/Gmres.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/ParallelAlgorithms/LinearSolver/Gmres/Gmres.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "DataStructures/DataBox/PrefixHelpers.hpp" #include "DataStructures/DataBox/Prefixes.hpp" #include "IO/Observer/Helpers.hpp" #include "ParallelAlgorithms/LinearSolver/Gmres/ElementActions.hpp" #include "ParallelAlgorithms/LinearSolver/Gmres/InitializeElement.hpp" #include "ParallelAlgorithms/LinearSolver/Gmres/ResidualMonitor.hpp" #include "ParallelAlgorithms/LinearSolver/Observe.hpp" #include "ParallelAlgorithms/LinearSolver/Tags.hpp" #include "Utilities/TMPL.hpp" /// Items related to the GMRES linear solver /// /// \see `LinearSolver::gmres::Gmres` namespace LinearSolver::gmres { /*! * \ingroup LinearSolverGroup * \brief A GMRES solver for nonsymmetric linear systems of equations * \f$Ax=b\f$. * * \details The only operation we need to supply to the algorithm is the * result of the operation \f$A(p)\f$ (see \ref LinearSolverGroup). Each step of * the algorithm expects that \f$A(q)\f$ is computed and stored in the DataBox * as `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo, operand_tag>`. * To perform a solve, add the `solve` action list to an array parallel * component. Pass the actions that compute \f$A(q)\f$, as well as any further * actions you wish to run in each step of the algorithm, as the first template * parameter to `solve`. If you add the `solve` action list multiple times, use * the second template parameter to label each solve with a different type. * * This linear solver supports preconditioning. Enable preconditioning by * setting the `Preconditioned` template parameter to `true`. If you do, run a * preconditioner (e.g. another parallel linear solver) in each step. The * preconditioner should approximately solve the linear problem \f$A(q)=b\f$ * where \f$q\f$ is the `operand_tag` and \f$b\f$ is the * `preconditioner_source_tag`. Make sure the tag * `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo, operand_tag>` * is updated with the preconditioned result in each step of the algorithm, i.e. * that it is \f$A(q)\f$ where \f$q\f$ is the preconditioner's approximate * solution to \f$A(q)=b\f$. The preconditioner always begins at an initial * guess of zero. It does not need to compute the operator applied to the * initial guess, since it's zero as well due to the linearity of the operator. * * Note that the operand \f$q\f$ for which \f$A(q)\f$ needs to be computed is * not the field \f$x\f$ we are solving for but * `db::add_tag_prefix<LinearSolver::Tags::Operand, FieldsTag>`. This field is * initially set to the residual \f$q_0 = b - A(x_0)\f$ where \f$x_0\f$ is the * initial value of the `FieldsTag`. * * When the algorithm step is performed after the operator action \f$A(q)\f$ has * been computed and stored in the DataBox, the GMRES algorithm implemented here * will converge the field \f$x\f$ towards the solution and update the operand * \f$q\f$ in the process. This requires reductions over all elements that are * received by a `ResidualMonitor` singleton parallel component, processed, and * then broadcast back to all elements. Since the reductions are performed to * find a vector that is orthogonal to those used in previous steps, the number * of reductions increases linearly with iterations. No restarting mechanism is * currently implemented. The actions are implemented in the `gmres::detail` * namespace and constitute the full algorithm in the following order: * 1. `PerformStep` (on elements): Start an Arnoldi orthogonalization by * computing the inner product between \f$A(q)\f$ and the first of the * previously determined set of orthogonal vectors. * 2. `StoreOrthogonalization` (on `ResidualMonitor`): Keep track of the * computed inner product in a Hessenberg matrix, then broadcast. * 3. `OrthogonalizeOperand` (on elements): Proceed with the Arnoldi * orthogonalization by computing inner products and reducing to * `StoreOrthogonalization` on the `ResidualMonitor` until the new orthogonal * vector is constructed. Then compute its magnitude and reduce. * 4. `StoreOrthogonalization` (on `ResidualMonitor`): Perform a QR * decomposition of the Hessenberg matrix to produce a residual vector. * Broadcast to `NormalizeOperandAndUpdateField` along with a termination * flag if the `Convergence::Tags::Criteria` are met. * 5. `NormalizeOperandAndUpdateField` (on elements): Set the operand \f$q\f$ as * the new orthogonal vector and normalize. Use the residual vector and the set * of orthogonal vectors to determine the solution \f$x\f$. * * \par Array sections * This linear solver supports running over a subset of the elements in the * array parallel component (see `Parallel::Section`). Set the * `ArraySectionIdTag` template parameter to restrict the solver to elements in * that section. Only a single section must be associated with the * `ArraySectionIdTag`. The default is `void`, which means running over all * elements in the array. Note that the actions in the `ApplyOperatorActions` * list passed to `solve` will _not_ be restricted to run only on section * elements, so all elements in the array may participate in preconditioning * (see LinearSolver::multigrid::Multigrid). * * \see ConjugateGradient for a linear solver that is more efficient when the * linear operator \f$A\f$ is symmetric. */ template <typename Metavariables, typename FieldsTag, typename OptionsGroup, bool Preconditioned, typename SourceTag = db::add_tag_prefix<::Tags::FixedSource, FieldsTag>, typename ArraySectionIdTag = void> struct Gmres { using fields_tag = FieldsTag; using options_group = OptionsGroup; using source_tag = SourceTag; static constexpr bool preconditioned = Preconditioned; /// Apply the linear operator to this tag in each iteration using operand_tag = std::conditional_t< Preconditioned, db::add_tag_prefix< LinearSolver::Tags::Preconditioned, db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>>, db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>>; /// Invoke a linear solver on the `operand_tag` sourced by the /// `preconditioner_source_tag` before applying the operator in each step using preconditioner_source_tag = db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>; /*! * \brief The parallel components used by the GMRES linear solver */ using component_list = tmpl::list< detail::ResidualMonitor<Metavariables, FieldsTag, OptionsGroup>>; using initialize_element = detail::InitializeElement<FieldsTag, OptionsGroup, Preconditioned>; using register_element = tmpl::list<>; using observed_reduction_data_tags = observers::make_reduction_data_tags< tmpl::list<observe_detail::reduction_data>>; template <typename ApplyOperatorActions, typename Label = OptionsGroup> using solve = tmpl::list< detail::PrepareSolve<FieldsTag, OptionsGroup, Preconditioned, Label, SourceTag, ArraySectionIdTag>, detail::NormalizeInitialOperand<FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>, detail::PrepareStep<FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>, ApplyOperatorActions, detail::PerformStep<FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>, detail::OrthogonalizeOperand<FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>, detail::NormalizeOperandAndUpdateField< FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>>; }; } // namespace LinearSolver::gmres
51.368421
80
0.740779
fmahebert
054f9861e4c257cf7140e1fb788c558c03aa6921
5,929
cc
C++
tonic-suite/asr/src/ivectorbin/ivector-mean.cc
csb1024/djinn_csb
de50d6b6bc9c137e9f4b881de9048eba9e83142d
[ "BSD-3-Clause" ]
59
2015-07-01T21:41:47.000Z
2021-07-28T07:07:42.000Z
tonic-suite/asr/src/ivectorbin/ivector-mean.cc
csb1024/djinn_csb
de50d6b6bc9c137e9f4b881de9048eba9e83142d
[ "BSD-3-Clause" ]
4
2016-01-24T13:25:03.000Z
2021-07-06T09:10:23.000Z
tonic-suite/asr/src/ivectorbin/ivector-mean.cc
csb1024/djinn_csb
de50d6b6bc9c137e9f4b881de9048eba9e83142d
[ "BSD-3-Clause" ]
54
2015-06-13T15:31:20.000Z
2021-07-28T07:07:43.000Z
// ivectorbin/ivector-mean.cc // Copyright 2013-2014 Daniel Povey // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" int main(int argc, char *argv[]) { using namespace kaldi; typedef kaldi::int32 int32; try { const char *usage = "With 3 or 4 arguments, averages iVectors over all the\n" "utterances of each speaker using the spk2utt file.\n" "Input the spk2utt file and a set of iVectors indexed by\n" "utterance; output is iVectors indexed by speaker. If 4\n" "arguments are given, extra argument is a table for the number\n" "of utterances per speaker (can be useful for PLDA). If 2\n" "arguments are given, computes the mean of all input files and\n" "writes out the mean vector.\n" "\n" "Usage: ivector-mean <spk2utt-rspecifier> <ivector-rspecifier> " "<ivector-wspecifier> [<num-utt-wspecifier>]\n" "or: ivector-mean <ivector-rspecifier> <mean-wxfilename>\n" "e.g.: ivector-mean data/spk2utt exp/ivectors.ark exp/spk_ivectors.ark " "exp/spk_num_utts.ark\n" "or: ivector-mean exp/ivectors.ark exp/mean.vec\n" "See also: ivector-subtract-global-mean\n"; ParseOptions po(usage); bool binary_write = false; po.Register("binary", &binary_write, "If true, write output in binary " "(only applicable when writing files, not archives/tables."); po.Read(argc, argv); if (po.NumArgs() < 2 || po.NumArgs() > 4) { po.PrintUsage(); exit(1); } if (po.NumArgs() == 2) { // Compute the mean of the input vectors and write it out. std::string ivector_rspecifier = po.GetArg(1), mean_wxfilename = po.GetArg(2); int32 num_done = 0; SequentialBaseFloatVectorReader ivector_reader(ivector_rspecifier); Vector<double> sum; for (; !ivector_reader.Done(); ivector_reader.Next()) { if (sum.Dim() == 0) sum.Resize(ivector_reader.Value().Dim()); sum.AddVec(1.0, ivector_reader.Value()); num_done++; } if (num_done == 0) { KALDI_ERR << "No iVectors read"; } else { sum.Scale(1.0 / num_done); WriteKaldiObject(sum, mean_wxfilename, binary_write); return 0; } } else { std::string spk2utt_rspecifier = po.GetArg(1), ivector_rspecifier = po.GetArg(2), ivector_wspecifier = po.GetArg(3), num_utts_wspecifier = po.GetOptArg(4); double spk_sumsq = 0.0; Vector<double> spk_sum; int64 num_spk_done = 0, num_spk_err = 0, num_utt_done = 0, num_utt_err = 0; RandomAccessBaseFloatVectorReader ivector_reader(ivector_rspecifier); SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier); BaseFloatVectorWriter ivector_writer(ivector_wspecifier); Int32Writer num_utts_writer(num_utts_wspecifier); for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) { std::string spk = spk2utt_reader.Key(); const std::vector<std::string> &uttlist = spk2utt_reader.Value(); if (uttlist.empty()) { KALDI_ERR << "Speaker with no utterances."; } Vector<BaseFloat> spk_mean; int32 utt_count = 0; for (size_t i = 0; i < uttlist.size(); i++) { std::string utt = uttlist[i]; if (!ivector_reader.HasKey(utt)) { KALDI_WARN << "No iVector present in input for utterance " << utt; num_utt_err++; } else { if (utt_count == 0) { spk_mean = ivector_reader.Value(utt); } else { spk_mean.AddVec(1.0, ivector_reader.Value(utt)); } num_utt_done++; utt_count++; } } if (utt_count == 0) { KALDI_WARN << "Not producing output for speaker " << spk << " since no utterances had iVectors"; num_spk_err++; } else { spk_mean.Scale(1.0 / utt_count); ivector_writer.Write(spk, spk_mean); if (num_utts_wspecifier != "") num_utts_writer.Write(spk, utt_count); num_spk_done++; spk_sumsq += VecVec(spk_mean, spk_mean); if (spk_sum.Dim() == 0) spk_sum.Resize(spk_mean.Dim()); spk_sum.AddVec(1.0, spk_mean); } } KALDI_LOG << "Computed mean of " << num_spk_done << " speakers (" << num_spk_err << " with no utterances), consisting of " << num_utt_done << " utterances (" << num_utt_err << " absent from input)."; if (num_spk_done != 0) { spk_sumsq /= num_spk_done; spk_sum.Scale(1.0 / num_spk_done); double mean_length = spk_sum.Norm(2.0), spk_length = sqrt(spk_sumsq), norm_spk_length = spk_length / sqrt(spk_sum.Dim()); KALDI_LOG << "Norm of mean of speakers is " << mean_length << ", root-mean-square speaker-iVector length divided by " << "sqrt(dim) is " << norm_spk_length; } return (num_spk_done != 0 ? 0 : 1); } } catch (const std::exception &e) { std::cerr << e.what(); return -1; } }
38.5
80
0.60398
csb1024
054fc497d48fcb564f03919a9190610f91a6fc28
2,122
hpp
C++
modules/asset/include/glpp/asset/render/scene_renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
16
2019-12-10T19:44:17.000Z
2022-01-04T03:16:19.000Z
modules/asset/include/glpp/asset/render/scene_renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
null
null
null
modules/asset/include/glpp/asset/render/scene_renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
3
2021-06-04T21:56:55.000Z
2022-03-03T06:47:56.000Z
#pragma once #include "scene_view.hpp" #include "mesh_renderer.hpp" namespace glpp::asset::render { template<class ShadingModel> class scene_renderer_t { public: using material_key_t = size_t; using renderer_t = mesh_renderer_t<ShadingModel>; scene_renderer_t(const ShadingModel& model, const scene_t& scene); void render(const scene_view_t& view); void render(const scene_view_t& view, const glpp::core::render::camera_t& camera); renderer_t& renderer(material_key_t index); const renderer_t& renderer(material_key_t index) const; private: std::vector<renderer_t> m_renderers; }; template<class ShadingModel> scene_renderer_t<ShadingModel>::scene_renderer_t(const ShadingModel& model, const scene_t& scene) { m_renderers.reserve(scene.materials.size()); std::transform( scene.materials.begin(), scene.materials.end(), std::back_inserter(m_renderers), [&](const material_t& material) { return mesh_renderer_t<ShadingModel>{ model, material }; } ); } template<class ShadingModel> void scene_renderer_t<ShadingModel>::render(const scene_view_t& view) { for(auto i = 0u; i < m_renderers.size(); ++i) { const auto& meshes = view.meshes_by_material(i); auto& renderer = m_renderers[i]; for(const auto& mesh : meshes) { renderer.update_model_matrix(mesh.model_matrix); renderer.render(mesh); } } } template<class ShadingModel> void scene_renderer_t<ShadingModel>::render(const scene_view_t& view, const glpp::core::render::camera_t& camera) { for(auto i = 0u; i < m_renderers.size(); ++i) { const auto& meshes = view.meshes_by_material(i); auto& renderer = m_renderers[i]; for(const auto& mesh : meshes) { renderer.update_model_matrix(mesh.model_matrix); renderer.render(mesh, camera); } } } template<class ShadingModel> typename scene_renderer_t<ShadingModel>::renderer_t& scene_renderer_t<ShadingModel>::renderer(material_key_t index) { return m_renderers[index]; } template<class ShadingModel> const typename scene_renderer_t<ShadingModel>::renderer_t& scene_renderer_t<ShadingModel>::renderer(material_key_t index) const { return m_renderers[index]; } }
28.675676
129
0.759661
lenamueller
05522110b84434638f878cd187d1463d33d0e6ff
4,137
cpp
C++
PopcornTorrent/Source/torrent/stack_allocator.cpp
tommy071/PopcornTorrent
88a1a4371d58e9d81839754d2eae079197dee5c5
[ "MIT" ]
4
2015-03-13T18:55:48.000Z
2015-06-27T09:33:44.000Z
src/stack_allocator.cpp
joriscarrier/libtorrent
1d801ec1b28c4e3643186905a5d28c7c1edbf534
[ "BSL-1.0", "BSD-3-Clause" ]
1
2017-09-19T08:52:30.000Z
2017-09-19T08:52:30.000Z
src/stack_allocator.cpp
joriscarrier/libtorrent
1d801ec1b28c4e3643186905a5d28c7c1edbf534
[ "BSL-1.0", "BSD-3-Clause" ]
1
2022-03-01T07:57:14.000Z
2022-03-01T07:57:14.000Z
/* Copyright (c) 2015-2016, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 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 "libtorrent/stack_allocator.hpp" #include <cstdarg> // for va_list, va_copy, va_end namespace libtorrent { namespace aux { allocation_slot stack_allocator::copy_string(string_view str) { int const ret = int(m_storage.size()); m_storage.resize(ret + numeric_cast<int>(str.size()) + 1); std::memcpy(&m_storage[ret], str.data(), str.size()); m_storage[ret + int(str.length())] = '\0'; return allocation_slot(ret); } allocation_slot stack_allocator::copy_string(char const* str) { int const ret = int(m_storage.size()); int const len = int(std::strlen(str)); m_storage.resize(ret + len + 1); std::memcpy(&m_storage[ret], str, numeric_cast<std::size_t>(len)); m_storage[ret + len] = '\0'; return allocation_slot(ret); } allocation_slot stack_allocator::format_string(char const* fmt, va_list v) { int const pos = int(m_storage.size()); int len = 512; for(;;) { m_storage.resize(pos + len + 1); va_list args; va_copy(args, v); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif int const ret = std::vsnprintf(m_storage.data() + pos, static_cast<std::size_t>(len + 1), fmt, args); #ifdef __clang__ #pragma clang diagnostic pop #endif va_end(args); if (ret < 0) { m_storage.resize(pos); return copy_string("(format error)"); } if (ret > len) { // try again len = ret; continue; } break; } // +1 is to include the 0-terminator m_storage.resize(pos + len + 1); return allocation_slot(pos); } allocation_slot stack_allocator::copy_buffer(span<char const> buf) { int const ret = int(m_storage.size()); int const size = int(buf.size()); if (size < 1) return {}; m_storage.resize(ret + size); std::memcpy(&m_storage[ret], buf.data(), numeric_cast<std::size_t>(size)); return allocation_slot(ret); } allocation_slot stack_allocator::allocate(int const bytes) { if (bytes < 1) return {}; int const ret = m_storage.end_index(); m_storage.resize(ret + bytes); return allocation_slot(ret); } char* stack_allocator::ptr(allocation_slot const idx) { if(idx.val() < 0) return nullptr; TORRENT_ASSERT(idx.val() < int(m_storage.size())); return &m_storage[idx.val()]; } char const* stack_allocator::ptr(allocation_slot const idx) const { if(idx.val() < 0) return nullptr; TORRENT_ASSERT(idx.val() < int(m_storage.size())); return &m_storage[idx.val()]; } void stack_allocator::swap(stack_allocator& rhs) { m_storage.swap(rhs.m_storage); } void stack_allocator::reset() { m_storage.clear(); } } }
28.729167
104
0.71767
tommy071
0552cb692d7c38ce92bed21ac12f87f3dc644950
545
cpp
C++
src/core/objects/storage.cpp
PeculiarVentures/pvpkcs11
474cf3b2a958c83ccfebf3165e45e7f46d649c81
[ "MIT" ]
30
2017-05-25T08:54:25.000Z
2021-12-21T13:42:35.000Z
src/core/objects/storage.cpp
PeculiarVentures/pvpkcs11
474cf3b2a958c83ccfebf3165e45e7f46d649c81
[ "MIT" ]
37
2017-05-24T21:47:36.000Z
2021-06-02T09:23:54.000Z
src/core/objects/storage.cpp
PeculiarVentures/pvpkcs11
474cf3b2a958c83ccfebf3165e45e7f46d649c81
[ "MIT" ]
7
2017-07-22T09:50:13.000Z
2019-08-18T23:42:52.000Z
#include "storage.h" using namespace core; Storage::Storage() : Object() { LOGGER_FUNCTION_BEGIN; LOGGER_DEBUG("New %s", __FUNCTION__); try { // set props defaults Add(AttributeBool::New(CKA_TOKEN, false, PVF_13)); Add(AttributeBool::New(CKA_PRIVATE, false, PVF_13)); Add(AttributeBool::New(CKA_MODIFIABLE, true, PVF_13)); Add(AttributeBytes::New(CKA_LABEL, NULL, 0, PVF_8)); // PVF_8 - no in spec Add(AttributeBool::New(CKA_COPYABLE, true, PVF_12)); } CATCH_EXCEPTION }
27.25
82
0.645872
PeculiarVentures
0553e9e2e4fd4df78f4ff7634230b41afaad54b9
5,495
cpp
C++
Source/GASExtensions/Private/Tasks/GASExtAT_WaitAttributeChangeWithValues.cpp
TheEmidee/UEGASExtensions
8851dbaf9251ecdc914f381df161484a7c5d4275
[ "MIT" ]
null
null
null
Source/GASExtensions/Private/Tasks/GASExtAT_WaitAttributeChangeWithValues.cpp
TheEmidee/UEGASExtensions
8851dbaf9251ecdc914f381df161484a7c5d4275
[ "MIT" ]
null
null
null
Source/GASExtensions/Private/Tasks/GASExtAT_WaitAttributeChangeWithValues.cpp
TheEmidee/UEGASExtensions
8851dbaf9251ecdc914f381df161484a7c5d4275
[ "MIT" ]
null
null
null
// Copy of AbilityTask_WaitAttributeChange that passes the old and new values on change #include "Tasks/GASExtAT_WaitAttributeChangeWithValues.h" #include <AbilitySystemComponent.h> #include <AbilitySystemGlobals.h> #include <GameplayEffectExtension.h> UGASExtAT_WaitAttributeChangeWithValues::UGASExtAT_WaitAttributeChangeWithValues( const FObjectInitializer & object_initializer ) : Super( object_initializer ) { bTriggerOnce = false; ComparisonType = EGASExtWaitAttributeChangeComparisonType::None; ComparisonValue = 0.0f; ExternalOwner = nullptr; } UGASExtAT_WaitAttributeChangeWithValues * UGASExtAT_WaitAttributeChangeWithValues::WaitForAttributeChangeWithValues( UGameplayAbility * owning_ability, FGameplayAttribute attribute, FGameplayTag with_src_tag, FGameplayTag without_src_tag, bool trigger_once, AActor * optional_external_owner ) { UGASExtAT_WaitAttributeChangeWithValues * my_obj = NewAbilityTask< UGASExtAT_WaitAttributeChangeWithValues >( owning_ability ); my_obj->WithTag = with_src_tag; my_obj->WithoutTag = without_src_tag; my_obj->Attribute = attribute; my_obj->ComparisonType = EGASExtWaitAttributeChangeComparisonType::None; my_obj->bTriggerOnce = trigger_once; my_obj->ExternalOwner = optional_external_owner ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor( optional_external_owner ) : nullptr; return my_obj; } UGASExtAT_WaitAttributeChangeWithValues * UGASExtAT_WaitAttributeChangeWithValues::WaitForAttributeChangeWithComparisonAndValues( UGameplayAbility * owning_ability, FGameplayAttribute in_attribute, FGameplayTag in_with_tag, FGameplayTag in_without_tag, EGASExtWaitAttributeChangeComparisonType in_comparison_type, float in_comparison_value, bool trigger_once, AActor * optional_external_owner ) { UGASExtAT_WaitAttributeChangeWithValues * my_obj = NewAbilityTask< UGASExtAT_WaitAttributeChangeWithValues >( owning_ability ); my_obj->WithTag = in_with_tag; my_obj->WithoutTag = in_without_tag; my_obj->Attribute = in_attribute; my_obj->ComparisonType = in_comparison_type; my_obj->ComparisonValue = in_comparison_value; my_obj->bTriggerOnce = trigger_once; my_obj->ExternalOwner = optional_external_owner ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor( optional_external_owner ) : nullptr; return my_obj; } void UGASExtAT_WaitAttributeChangeWithValues::Activate() { if ( UAbilitySystemComponent * asc = GetFocusedASC() ) { OnAttributeChangeDelegateHandle = asc->GetGameplayAttributeValueChangeDelegate( Attribute ).AddUObject( this, &UGASExtAT_WaitAttributeChangeWithValues::OnAttributeChange ); } } void UGASExtAT_WaitAttributeChangeWithValues::OnAttributeChange( const FOnAttributeChangeData & callback_data ) { const float new_value = callback_data.NewValue; const float old_value = callback_data.OldValue; const FGameplayEffectModCallbackData * data = callback_data.GEModData; if ( data == nullptr ) { // There may be no execution data associated with this change, for example a GE being removed. // In this case, we auto fail any WithTag requirement and auto pass any WithoutTag requirement if ( WithTag.IsValid() ) { return; } } else { if ( ( WithTag.IsValid() && !data->EffectSpec.CapturedSourceTags.GetAggregatedTags()->HasTag( WithTag ) ) || ( WithoutTag.IsValid() && data->EffectSpec.CapturedSourceTags.GetAggregatedTags()->HasTag( WithoutTag ) ) ) { // Failed tag check return; } } bool passed_comparison = true; switch ( ComparisonType ) { case EGASExtWaitAttributeChangeComparisonType::ExactlyEqualTo: passed_comparison = ( new_value == ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::GreaterThan: passed_comparison = ( new_value > ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::GreaterThanOrEqualTo: passed_comparison = ( new_value >= ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::LessThan: passed_comparison = ( new_value < ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::LessThanOrEqualTo: passed_comparison = ( new_value <= ComparisonValue ); break; case EGASExtWaitAttributeChangeComparisonType::NotEqualTo: passed_comparison = ( new_value != ComparisonValue ); break; default: break; } if ( passed_comparison ) { if ( ShouldBroadcastAbilityTaskDelegates() ) { OnChange.Broadcast( old_value, new_value ); } if ( bTriggerOnce ) { EndTask(); } } } UAbilitySystemComponent * UGASExtAT_WaitAttributeChangeWithValues::GetFocusedASC() { return ExternalOwner ? ExternalOwner : AbilitySystemComponent; } void UGASExtAT_WaitAttributeChangeWithValues::OnDestroy( bool ability_ended ) { if ( UAbilitySystemComponent * asc = GetFocusedASC() ) { asc->GetGameplayAttributeValueChangeDelegate( Attribute ).Remove( OnAttributeChangeDelegateHandle ); } Super::OnDestroy( ability_ended ); }
42.596899
395
0.719199
TheEmidee
0557b766a096ebf2de547bda82e105cba2d89fad
14,159
cpp
C++
Common/src/EGL/eglInstance.cpp
kbiElude/DolceSDK-Experiments
1b5cca8b437f5384e074b5b666bb2bdd3031d08d
[ "Unlicense" ]
null
null
null
Common/src/EGL/eglInstance.cpp
kbiElude/DolceSDK-Experiments
1b5cca8b437f5384e074b5b666bb2bdd3031d08d
[ "Unlicense" ]
null
null
null
Common/src/EGL/eglInstance.cpp
kbiElude/DolceSDK-Experiments
1b5cca8b437f5384e074b5b666bb2bdd3031d08d
[ "Unlicense" ]
null
null
null
extern "C" { #include <psp2/libdbg.h> } #include <sstream> #include <vector> #include "EGL/eglInstance.h" #include "ES/buffer.h" #include "ES/program.h" #include "ES/texture.h" #include "gfx/text_renderer.h" #include "io.h" #include "logger.h" EGLInstance::EGLInstance(Logger* in_logger_ptr) :m_display (nullptr), m_egl_config_ptr (nullptr), m_egl_context (nullptr), m_egl_surface (nullptr), m_gl_extensions_ptr(nullptr), m_logger_ptr (in_logger_ptr), m_never_bound (true) { /* Stub */ } EGLInstance::~EGLInstance() { m_text_renderer_ptr.reset(); if (m_egl_context != nullptr) { ::eglDestroyContext(m_display, m_egl_context); } if (m_egl_surface != nullptr) { ::eglDestroySurface(m_display, m_egl_surface); } } bool EGLInstance::bind_to_current_thread() { bool result = false; result = ::eglMakeCurrent(m_display, m_egl_surface, m_egl_surface, m_egl_context) == EGL_TRUE; if (m_never_bound) { /* Log base GL info & available GL extensions. */ auto es_extensions_ptr = ::eglQueryString(m_display, EGL_EXTENSIONS); auto renderer_ptr = ::glGetString (GL_RENDERER); auto vendor_ptr = ::glGetString (GL_VENDOR); auto version_ptr = ::glGetString (GL_VERSION); m_gl_extensions_ptr = reinterpret_cast<const char*>(::glGetString(GL_EXTENSIONS) ); #if 0 m_logger_ptr->log(false, /* in_flush_and_wait */ "Renderer version: %s\n" "Renderer: %s\n" "Vendor: %s\n", version_ptr, renderer_ptr, vendor_ptr); m_logger_ptr->log(false, /* in_flush_and_wait */ "ES Extensions: %s\n", es_extensions_ptr); m_logger_ptr->log(false, /* in_flush_and_wait */ "GL Extensions: %s\n", m_gl_extensions_ptr); #endif /* Init extension entrypoints */ if (strstr(m_gl_extensions_ptr, "GL_EXT_draw_instanced") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glDrawArraysInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_draw_instanced.glDrawArraysInstancedEXT)}, {"glDrawElementsInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_draw_instanced.glDrawElementsInstancedEXT)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_EXT_instanced_arrays") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glDrawArraysInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glDrawArraysInstancedEXT)}, {"glDrawElementsInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glDrawElementsInstancedEXT)}, {"glVertexAttribDivisorEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glVertexAttribDivisorEXT)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_EXT_texture_storage") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glTexStorage2DEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_texture_storage.glTexStorage2DEXT)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_SCE_piglet_shader_binary") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glPigletGetShaderBinarySCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_piglet_shader_binary.glPigletGetShaderBinarySCE) }, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } if (strstr(m_gl_extensions_ptr, "GL_SCE_texture_resource") != nullptr) { const ExtensionEntrypoint entrypoints[] = { {"glMapTextureResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glMapTextureResourceSCE)}, {"glTexImageResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glTexImageResourceSCE)}, {"glUnmapTextureResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glUnmapTextureResourceSCE)}, }; if (!init_extension_entrypoints(entrypoints, sizeof(entrypoints) / sizeof(entrypoints[0])) ) { SCE_DBG_ASSERT(false); result = false; goto end; } } /* Init text renderer */ m_text_renderer_ptr = TextRenderer::create(this, m_logger_ptr); SCE_DBG_ASSERT(m_text_renderer_ptr != nullptr); /* Done */ m_never_bound = false; } SCE_DBG_ASSERT(result); end: return result; } std::unique_ptr<EGLInstance> EGLInstance::create(Logger* in_logger_ptr, const bool& in_require_depth_buffer, const bool& in_require_stencil_buffer) { std::unique_ptr<EGLInstance> result_ptr; result_ptr.reset( new EGLInstance(in_logger_ptr) ); SCE_DBG_ASSERT(result_ptr != nullptr); if (result_ptr != nullptr) { if (!result_ptr->init(in_require_depth_buffer, in_require_stencil_buffer) ) { SCE_DBG_ASSERT(false); result_ptr.reset(); } } return result_ptr; } const EXTDrawInstancedEntrypoints* EGLInstance::get_ext_draw_instanced_entrypoints_ptr() const { return &m_entrypoints_gl_ext_draw_instanced; } const EXTInstancedArraysEntrypoints* EGLInstance::get_ext_instanced_arrays_entrypoints_ptr() const { return &m_entrypoints_gl_ext_instanced_arrays; } const EXTTextureStorageEntrypoints* EGLInstance::get_ext_texture_storage_entrypoints_ptr() const { return &m_entrypoints_gl_ext_texture_storage; } const uint32_t* EGLInstance::get_rt_extents_wh() const { static const uint32_t rt[] = {960, 544}; return rt; } const SCEPigletShaderBinaryEntrypoints* EGLInstance::get_sce_piglet_shader_binary_entrypoints_ptr() const { return &m_entrypoints_gl_sce_piglet_shader_binary; } const SCETextureResourceEntrypoints* EGLInstance::get_sce_texture_resource_entrypoints_ptr() const { return &m_entrypoints_gl_sce_texture_resource_entrypoints; } TextRenderer* EGLInstance::get_text_renderer_ptr() const { SCE_DBG_ASSERT(m_text_renderer_ptr != nullptr); return m_text_renderer_ptr.get(); } bool EGLInstance::init(const bool& in_require_depth_buffer, const bool& in_require_stencil_buffer) { EGLBoolean result; m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); SCE_DBG_ASSERT(m_display != EGL_NO_DISPLAY); result = eglInitialize(m_display, nullptr, /* major */ nullptr); /* minor */ SCE_DBG_ASSERT(result == EGL_TRUE); /* Enumerate available EGL configs */ { std::vector<EGLConfig> egl_config_vec; EGLint n_egl_configs = 0; result = eglGetConfigs(m_display, nullptr, /* configs */ 0, /* config_size */ &n_egl_configs); SCE_DBG_ASSERT(result == EGL_TRUE); egl_config_vec.resize (n_egl_configs); m_egl_config_vec.resize(n_egl_configs); result = eglGetConfigs(m_display, egl_config_vec.data(), n_egl_configs, &n_egl_configs); SCE_DBG_ASSERT(result == EGL_TRUE); for (uint32_t n_egl_config = 0; n_egl_config < n_egl_configs; ++n_egl_config) { const auto current_egl_config = egl_config_vec.at (n_egl_config); auto& current_egl_config_props = m_egl_config_vec.at(n_egl_config); current_egl_config_props.egl_config = current_egl_config; const struct { EGLint attribute; EGLint* result_ptr; } config_attribs[] = { {EGL_ALPHA_SIZE, &current_egl_config_props.n_alpha_bits}, {EGL_BLUE_SIZE, &current_egl_config_props.n_blue_bits}, {EGL_CONFIG_ID, &current_egl_config_props.egl_config_id}, {EGL_DEPTH_SIZE, &current_egl_config_props.n_depth_bits}, {EGL_GREEN_SIZE, &current_egl_config_props.n_green_bits}, {EGL_RED_SIZE, &current_egl_config_props.n_red_bits}, {EGL_STENCIL_SIZE, &current_egl_config_props.n_stencil_bits} }; for (const auto& current_config_attrib : config_attribs) { result = eglGetConfigAttrib(m_display, current_egl_config, current_config_attrib.attribute, current_config_attrib.result_ptr); SCE_DBG_ASSERT(result == EGL_TRUE); } } } /* On 3.60, we are reported 3 different configs, the only difference between the three being presence (or lack) * of depth and/or stencil buffer. * * Pick the right EGLConfig instance, depending on the input arguments. **/ { uint32_t best_score = 0xFFFFFFFFu; for (const auto& current_egl_config : m_egl_config_vec) { uint32_t score = 0; if (( in_require_depth_buffer && current_egl_config.n_depth_bits != 0) || (!in_require_depth_buffer && current_egl_config.n_depth_bits == 0) ) { ++score; } if (( in_require_stencil_buffer && current_egl_config.n_stencil_bits != 0) || (!in_require_stencil_buffer && current_egl_config.n_stencil_bits == 0) ) { ++score; } if ((best_score == 0xFFFFFFFFu) || (best_score < score) ) { best_score = score; m_egl_config_ptr = &current_egl_config; } } } SCE_DBG_ASSERT(m_egl_config_ptr != nullptr); /* Create an ES context. */ { static const EGLint attrib_list[] = { EGL_CONTEXT_MAJOR_VERSION, 2, EGL_CONTEXT_MINOR_VERSION, 0, EGL_NONE }; m_egl_context = eglCreateContext(m_display, m_egl_config_ptr->egl_config, EGL_NO_CONTEXT, /* share_context */ attrib_list); SCE_DBG_ASSERT(m_egl_context != EGL_NO_CONTEXT); } /* Create a rendering surface. * * NOTE: If the resolution is ever changed, make sure to update get_rt_extents_wh() too. **/ m_egl_surface = eglCreateWindowSurface(m_display, m_egl_config_ptr->egl_config, VITA_WINDOW_960X544, nullptr); /* attrib_list */ SCE_DBG_ASSERT(m_egl_surface != EGL_NO_SURFACE); /* NOTE: Do not bind the context to the calling thread. It is caller's responsibility to invoke bind() * from the right thread later on. */ return (m_egl_context != nullptr && m_egl_surface != nullptr); } bool EGLInstance::init_extension_entrypoints(const ExtensionEntrypoint* in_ext_entrypoint_ptr, const uint32_t& in_n_ext_entrypoints) { bool result = false; for (uint32_t n_entrypoint = 0; n_entrypoint < in_n_ext_entrypoints; ++n_entrypoint) { const auto& current_entrypoint = in_ext_entrypoint_ptr[n_entrypoint]; *current_entrypoint.func_ptr_ptr = reinterpret_cast<void*>(::eglGetProcAddress(current_entrypoint.func_name_ptr) ); if (*current_entrypoint.func_ptr_ptr == nullptr) { SCE_DBG_ASSERT(false); goto end; } } result = true; end: return result; } void EGLInstance::swap_buffers() { ::eglSwapBuffers(m_display, m_egl_surface); }
33.315294
150
0.558443
kbiElude
0558840bdaa1ae8725ae0bde815c93c79b69a3c5
2,614
cpp
C++
src/plugins/device.cpp
localarchive/incubator-cordova-qt
41f94032208723e35f4b6b907ffa145fa8820c7a
[ "Apache-2.0" ]
null
null
null
src/plugins/device.cpp
localarchive/incubator-cordova-qt
41f94032208723e35f4b6b907ffa145fa8820c7a
[ "Apache-2.0" ]
null
null
null
src/plugins/device.cpp
localarchive/incubator-cordova-qt
41f94032208723e35f4b6b907ffa145fa8820c7a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2011 Wolfgang Koller - http://www.gofg.at/ * * 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"device.h" #include "../pluginregistry.h" #if QT_VERSION < 0x050000 #include <QSystemDeviceInfo> #include <QSystemInfo> #else #include <QDeviceInfo> #include <QtSystemInfo> #endif #include <QDebug> #define CORDOVA "2.2.0" #ifdef QTM_NAMESPACE QTM_USE_NAMESPACE #endif // Create static instance of ourself Device* Device::m_device = new Device(); /** * Constructor - NOTE: Never do anything except registering the plugin */ Device::Device() : CPlugin() { PluginRegistry::getRegistry()->registerPlugin( "com.cordova.Device", this ); } /** * Called by the javascript constructor in order to receive all required device info(s) */ void Device::getInfo( int scId, int ecId ) { Q_UNUSED(ecId) #if QT_VERSION < 0x050000 QSystemDeviceInfo *systemDeviceInfo = new QSystemDeviceInfo(this); QSystemInfo *systemInfo = new QSystemInfo(this); #else QDeviceInfo *systemDeviceInfo = new QDeviceInfo(this); QDeviceInfo *systemInfo = new QDeviceInfo(this); #endif #ifdef Q_OS_SYMBIAN QString platform = "Symbian"; #endif #ifdef Q_OS_WIN QString platform = "Windows"; #endif #ifdef Q_OS_WINCE QString platform = "Windows CE"; #endif #ifdef Q_OS_LINUX QString platform = "Linux"; #endif #if QT_VERSION < 0x050000 this->callback( scId, "'" + systemDeviceInfo->model() + "', '" + CORDOVA + "', '" + platform + "', '" + systemDeviceInfo->uniqueDeviceID() + "', '" + systemInfo->version( QSystemInfo::Os ) + "'" ); #else qDebug() << Q_FUNC_INFO << ":" << systemInfo->imei(0) << "; " << systemInfo->manufacturer() << "; " << systemInfo->model() << "; " << systemInfo->productName() << "; " << systemInfo->uniqueDeviceID() << "; " << systemInfo->version(QDeviceInfo::Os) << "; " << systemInfo->version(QDeviceInfo::Firmware); this->callback( scId, "'" + systemDeviceInfo->model() + "', '" + CORDOVA + "', '" + platform + "', '" + systemDeviceInfo->uniqueDeviceID() + "', '" + systemInfo->version( QDeviceInfo::Os ) + "'" ); #endif }
32.271605
306
0.682479
localarchive
055ab2002a9c1a604026d64f4ef956c193e8b527
2,586
cpp
C++
src/net/Server.cpp
landness/RPC-K8S-githubAction_cicd_test
8178274f1b952650d52125deeda2cfc3e6d3632c
[ "MIT" ]
null
null
null
src/net/Server.cpp
landness/RPC-K8S-githubAction_cicd_test
8178274f1b952650d52125deeda2cfc3e6d3632c
[ "MIT" ]
null
null
null
src/net/Server.cpp
landness/RPC-K8S-githubAction_cicd_test
8178274f1b952650d52125deeda2cfc3e6d3632c
[ "MIT" ]
null
null
null
#include"net/Server.h" #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include"base/Util.h" Server::Server(Eventloop* loop,int threadnum,uint16_t port) :loop_(loop), threadnum_(threadnum), eventloopthreadpool_(new Eventloopthreadpool(loop_,threadnum_)), started_(false), port_(port), listenfd_(socket_bind_and_listen(port_)), acceptchannel_(new Channel(loop_,listenfd_)), nextconnid_(0) { //SIGPIPE if(setSocketNonBlocking(listenfd_) < 0) { perror("set nonblock error"); abort(); } } void Server::start() { if(!started_) { eventloopthreadpool_->start(); acceptchannel_->set_events(EPOLLIN|EPOLLET); acceptchannel_->setreadcallback(bind(&Server::newconnection,this)); loop_->addchannel(acceptchannel_); started_ = true; } } void Server::newconnection() { struct sockaddr_in client_addr; memset(&client_addr,0,sizeof(struct sockaddr_in)); socklen_t client_addr_len = sizeof(client_addr); int accept_fd = 0; while((accept_fd = accept(listenfd_,(struct sockaddr*)&client_addr,&client_addr_len)) > 0 ) { if(accept_fd >= MAXFDS) //限制并发链接数 { close(accept_fd); continue; } if(setSocketNonBlocking(accept_fd) < 0) { return; } setSocketNodelay(accept_fd); char buf[32]; snprintf(buf,sizeof(buf),"#%d",nextconnid_); ++nextconnid_; std::string connname = buf; setSocketNodelay(accept_fd); Eventloop* ioloop = eventloopthreadpool_->getnextloop(); TcpconnectionPtr conn = make_shared<Tcpconnection>(ioloop,connname,accept_fd); //不使用new by 陈硕?????? connections_[connname] = conn; conn->setConnectioncallback(connectioncallback_); conn->setMessagecallback(messagecallback_); //Rpc messagecallback 由connectioncallback 绑定 conn->setClosecallback(std::bind(&Server::removeconnection, this, std::placeholders::_1));//Fixme::unsafe ioloop->runinloop(std::bind(&Tcpconnection::connectEstablished,conn)); } } void Server::removeconnection(const TcpconnectionPtr& conn) { loop_->runinloop(std::bind(&Server::removeconnectioninloop,this,conn)); } void Server::removeconnectioninloop(const TcpconnectionPtr& conn) { loop_->assertinloopthread(); size_t n = connections_.erase(conn->name()); assert( n == 1); Eventloop* ioloop = conn->getloop(); ioloop->queueinloop(std::bind(&Tcpconnection::connectDestroyed,conn)); }
29.386364
113
0.663186
landness
055c54e469f20bed508c25b918ccb9bf9b4143a5
7,557
cpp
C++
matlab_code/jjcao_code-head/toolbox/jjcao_plot/mex_draw_thick_lines_on_img.cpp
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
matlab_code/jjcao_code-head/toolbox/jjcao_plot/mex_draw_thick_lines_on_img.cpp
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
matlab_code/jjcao_code-head/toolbox/jjcao_plot/mex_draw_thick_lines_on_img.cpp
joycewangsy/normals_pointnet
fc74a8ed1a009b18785990b1b4c20eda0549721c
[ "MIT" ]
null
null
null
/* // // Draw multiple thick lines on the image // // Inputs: // InputImg: Input image (Grayscale or Color) // CoordPnt: Coordinates of end points of lines [r1 r2 c1 c2] // (n x 4 double array, n: # of lines) // Thickness: Thickness of lines (The value is integer, but the type is double.) // (n x 1 double array, n: # of lines) // LineColor: Line colors (The values should be integers from 0 to 255) // (n x 4 double array, n: # of lines) // (Data type: double, ex. [255 255 255]: white ) // (The channels of 'InputImg' and 'LineColor' should be consistent) // // // Outputs: // OutputImg: Output image (The same format with InputImg) // // // Copyright, Gunhee Kim (gunhee@cs.cmu.edu) // Computer Science Department, Carnegie Mellon University, // October 19 2009 */ #include <mex.h> #include <math.h> //#include <string.h> #define UINT8 unsigned char #define UINT32 unsigned int #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #define abs(x) ((x) >= 0 ? (x) : -(x)) #define pow2(x) ((x)*(x)) void Bresenham(int x1, int x2, int y1, int yt) ; void plot(int x1, int y1) ; void draw_thick_line(int x1, int x2, int y1, int y2) ; double *LineColor, *LineThickness ; UINT8 *OutputImg ; int nPnt, nChannel, indLine ; int dimR, dimC, nDim ; void mexFunction( int nlhs, // Number of left hand side (output) arguments mxArray *plhs[], // Array of left hand side arguments int nrhs, // Number of right hand side (input) arguments const mxArray *prhs[] // Array of right hand side arguments ) { UINT8 *InputImg ; double *CoordPnt, *InCoord ; int i, dimPnt, add_r1, add_r2, add_c1, add_c2 ; /* Check for proper number of arguments. */ if (nrhs <4) { mexErrMsgTxt("Four inputs are required."); } else if (nlhs > 1) { mexErrMsgTxt("Too many output assigned."); } InputImg = (UINT8 *)mxGetPr(prhs[0]); // Input image (Data type: uint8*) InCoord = (double *) mxGetPr(prhs[1]); // [r1 r2 c1 c2] (Data type: double*) nPnt = (int) mxGetM(prhs[1]); dimPnt = (int) mxGetN(prhs[1]); LineThickness = (double *)mxGetPr(prhs[2]); // Line Thickness (Data type: double*) LineColor = (double *)mxGetPr(prhs[3]); // Line color (Data type: double*) nChannel = (int)mxGetN(prhs[3]); // Dimensions of input image dimR = (int)mxGetM(prhs[0]); dimC = (int)mxGetN(prhs[0]); nDim = (int)mxGetNumberOfDimensions(prhs[0]); /* // If the channels of Input image and line color are different, terminate it. if (((nDim==2) && (nChannel==3)) || ((nDim==3) && (nChannel==1)) ) { mexErrMsgTxt("The channels of Input image and line color are different !"); } */ // If the input image is color image if(nChannel==3) dimC = dimC/nChannel; //mexPrintf("%d %d %d %d %d %d\n", nChannel, dimR, dimC, nDim, dimPnt, nPnt) ; // Set output plhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]), mxGetDimensions(prhs[0]),mxUINT8_CLASS,mxREAL); OutputImg = (UINT8*)mxGetPr(plhs[0]); // copy InputImg to OutputImg for (i=0; i<dimR*dimC*nChannel; i++) OutputImg[i] = InputImg[i] -1 ; // decrease coordinates by 1 CoordPnt = (double *) mxCalloc(nPnt*dimPnt, sizeof(double)); // If the coordinate< 0 or > image dimension, reduce it. for (i=0; i<nPnt*dimPnt/2; i++) { CoordPnt[i] = InCoord[i] -1 ; if (CoordPnt[i]<0) CoordPnt[i] = 0 ; if (CoordPnt[i]>dimR) CoordPnt[i] = dimR ; } for (i=nPnt*dimPnt/2; i<nPnt*dimPnt; i++) { CoordPnt[i] = InCoord[i] -1 ; if (CoordPnt[i]<0) CoordPnt[i] = 0 ; if (CoordPnt[i]>dimC) CoordPnt[i] = dimC ; } // adding indices for each dim. add_r1 = 0 ; add_r2 = nPnt ; add_c1 = 2*nPnt ; add_c2 = 3*nPnt ; // Main loop for (i=0; i<nPnt; i++) { // lineIdx indLine = i ; draw_thick_line((int)CoordPnt[i+add_c1], // c1 = x1 (int)CoordPnt[i+add_c2], // c2 = x2 (int)CoordPnt[i+add_r1], // r1 = y1 (int)CoordPnt[i+add_r2] // r2 = y2 ) ; } mxFree(CoordPnt) ; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // End of the function "Main" function ////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Set the values void plot(int x1, int y1) { int idx = y1 + dimR*x1 ; for (int i=0; i<nChannel; i++) OutputImg[dimR*dimC*i+idx] = (UINT8)LineColor[indLine+i*nPnt] ; } // draw thick lines // (reference) Computer Graphics by A.P. Godse void draw_thick_line(int x1, int x2, int y1, int y2) { int i; float wy, wx ; int thickness = (int)LineThickness[indLine] ; Bresenham(x1, x2, y1, y2) ; if (abs((float)(y2-y1)/(float)(x2-x1)) < 1) { wy = (float)(thickness-1)*sqrt((float)(pow2(x2-x1)+pow2(y2-y1))) / (2.*(float)abs(x2-x1)) ; //mexPrintf("wy: %f %d %f \n", 2.*(float)abs(x2-x1), thickness, wy) ; for (i=0; i<wy; i++) { if ( ((y1-i)>-1) && ((y2-i)>-1) ) Bresenham(x1, x2, y1-i, y2-i) ; if ( ((y1+i)<dimR) && ((y2+i)<dimR) ) Bresenham(x1, x2, y1+i, y2+i) ; } } else { wx = (float)(thickness-1)*sqrt((float)(pow2(x2-x1)+pow2(y2-y1))) / (2.*(float)abs(y2-y1)) ; //mexPrintf("wx: %f %d %f \n", 2.*(float)abs(y2-y1), thickness, wx) ; for (i=0; i<wx; i++) { if ( ((x1-i)>-1) && ((x2-i)>-1) ) Bresenham(x1-i, x2-i, y1, y2) ; if ( ((x1+i)<dimC) && ((x2+i)<dimC) ) Bresenham(x1+i, x2+i, y1, y2) ; } } } // The following code is Bresenham's Line Algorithm. // (Reference) http://roguebasin.roguelikedevelopment.org/index.php?title=Bresenham's_Line_Algorithm //////////////////////////////////////////////////////////////////////////////// void Bresenham(int x1, int x2, int y1, int y2) { int delta_x = abs(x2 - x1) << 1; int delta_y = abs(y2 - y1) << 1; // if x1 == x2 or y1 == y2, then it does not matter what we set here signed char ix = x2 > x1?1:-1; signed char iy = y2 > y1?1:-1; plot(x1, y1); if (delta_x >= delta_y) { // error may go below zero int error = delta_y - (delta_x >> 1); while (x1 != x2) { if (error >= 0) { if (error || (ix > 0)) { y1 += iy; error -= delta_x; } // else do nothing } // else do nothing x1 += ix; error += delta_y; plot(x1, y1); } } else { // error may go below zero int error = delta_x - (delta_y >> 1); while (y1 != y2) { if (error >= 0) { if (error || (iy > 0)) { x1 += ix; error -= delta_y; } // else do nothing } // else do nothing y1 += iy; error += delta_x; plot(x1, y1); } } }
29.519531
110
0.492259
joycewangsy
055d55e7eecdc28c2152938f6a7f51df7a6cea94
1,892
cc
C++
src/reader/wgsl/parser_impl_struct_decoration_test.cc
sunnyps/tint
22daca166bbc412345fc60d4f60646d6d2f3ada0
[ "Apache-2.0" ]
null
null
null
src/reader/wgsl/parser_impl_struct_decoration_test.cc
sunnyps/tint
22daca166bbc412345fc60d4f60646d6d2f3ada0
[ "Apache-2.0" ]
null
null
null
src/reader/wgsl/parser_impl_struct_decoration_test.cc
sunnyps/tint
22daca166bbc412345fc60d4f60646d6d2f3ada0
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/ast/struct_block_decoration.h" #include "src/reader/wgsl/parser_impl_test_helper.h" namespace tint { namespace reader { namespace wgsl { namespace { struct DecorationData { const char* input; bool is_block; }; inline std::ostream& operator<<(std::ostream& out, DecorationData data) { out << std::string(data.input); return out; } class DecorationTest : public ParserImplTestWithParam<DecorationData> {}; TEST_P(DecorationTest, Parses) { auto params = GetParam(); auto p = parser(params.input); auto deco = p->decoration(); ASSERT_FALSE(p->has_error()); EXPECT_TRUE(deco.matched); EXPECT_FALSE(deco.errored); ASSERT_NE(deco.value, nullptr); auto* struct_deco = deco.value->As<ast::Decoration>(); ASSERT_NE(struct_deco, nullptr); EXPECT_EQ(struct_deco->Is<ast::StructBlockDecoration>(), params.is_block); } INSTANTIATE_TEST_SUITE_P(ParserImplTest, DecorationTest, testing::Values(DecorationData{"block", true})); TEST_F(ParserImplTest, Decoration_NoMatch) { auto p = parser("not-a-stage"); auto deco = p->decoration(); EXPECT_FALSE(deco.matched); EXPECT_FALSE(deco.errored); ASSERT_EQ(deco.value, nullptr); } } // namespace } // namespace wgsl } // namespace reader } // namespace tint
30.031746
76
0.716702
sunnyps
055e506ba9b67cc8d6287f8e41f7a2a3b1aaf783
2,196
hpp
C++
src/test/utils/thread.hpp
koplyarov/wigwag
d5646c610b324c9252ec7ac807f883f88e7442eb
[ "0BSD" ]
103
2016-02-26T14:39:03.000Z
2021-02-13T10:15:52.000Z
src/test/utils/thread.hpp
koplyarov/wigwag
d5646c610b324c9252ec7ac807f883f88e7442eb
[ "0BSD" ]
1
2018-05-07T06:00:19.000Z
2018-05-07T19:57:20.000Z
src/test/utils/thread.hpp
koplyarov/wigwag
d5646c610b324c9252ec7ac807f883f88e7442eb
[ "0BSD" ]
9
2016-03-17T11:56:33.000Z
2020-08-06T10:11:50.000Z
#ifndef UTILS_UTILS_HPP #define UTILS_UTILS_HPP // Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com> // // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <chrono> #include <thread> namespace wigwag { class thread { public: using thread_func = std::function<void(const std::atomic<bool>&)>; private: std::atomic<bool> _alive; thread_func _thread_func; std::string _error_message; std::thread _impl; public: thread(const thread_func& f) : _alive(true), _thread_func(f) { _impl = std::thread(std::bind(&thread::func, this)); } ~thread() { _alive = false; if (_impl.joinable()) _impl.join(); else std::cerr << "WARNING: thread is not joinable!" << std::endl; if (!_error_message.empty()) TS_FAIL(("Uncaught exception in thread: " + _error_message).c_str()); } static void sleep(int64_t ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); } private: void func() { try { _thread_func(_alive); } catch (const std::exception& ex) { _error_message = ex.what(); } } }; template < typename Lockable_ > std::unique_lock<Lockable_> lock(Lockable_& lockable) { return std::unique_lock<Lockable_>(lockable); } } #endif
30.5
172
0.617486
koplyarov
055eafa4d630e6a34738b1391aa08f6ba137c091
9,107
cpp
C++
openstudiocore/src/runmanager/lib/Test/ErrorEstimation_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/runmanager/lib/Test/ErrorEstimation_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/runmanager/lib/Test/ErrorEstimation_GTest.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * Likey = cense along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "RunManagerTestFixture.hpp" #include <runmanager/Test/ToolBin.hxx> #include <resources.hxx> #include "../JobFactory.hpp" #include "../RunManager.hpp" #include "../Workflow.hpp" #include "../ErrorEstimation.hpp" #include "../../../model/Model.hpp" #include "../../../model/Building.hpp" #include "../../../utilities/idf/IdfFile.hpp" #include "../../../utilities/idf/IdfObject.hpp" #include "../../../utilities/data/EndUses.hpp" #include "../../../utilities/data/Attribute.hpp" #include "../../../utilities/sql/SqlFile.hpp" #include "../../../isomodel/UserModel.hpp" #include "../../../isomodel/ForwardTranslator.hpp" #include <boost/filesystem/path.hpp> #include <QDir> #include <QElapsedTimer> #include <boost/filesystem.hpp> using openstudio::Attribute; using openstudio::IdfFile; using openstudio::IdfObject; using openstudio::IddObjectType; using openstudio::SqlFile; openstudio::SqlFile runSimulation(openstudio::model::Model t_model, bool t_estimate) { if (t_estimate) { openstudio::runmanager::RunManager::simplifyModelForPerformance(t_model); } openstudio::path outdir = openstudio::toPath(QDir::tempPath()) / openstudio::toPath("ErrorEstimationRunTest"); boost::filesystem::create_directories(outdir); openstudio::path db = outdir / openstudio::toPath("ErrorEstimationRunDB"); openstudio::runmanager::RunManager kit(db, true); openstudio::path infile = outdir / openstudio::toPath("in.osm"); openstudio::path weatherdir = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw"); t_model.save(infile, true); openstudio::runmanager::Workflow workflow("modeltoidf->expandobjects->energyplus"); workflow.setInputFiles(infile, weatherdir); // Build list of tools openstudio::runmanager::Tools tools = openstudio::runmanager::ConfigOptions::makeTools( energyPlusExePath().parent_path(), openstudio::path(), openstudio::path(), openstudio::path(), openstudio::path()); workflow.add(tools); int offset = 7; if (t_estimate) offset = 1; workflow.parallelizeEnergyPlus(kit.getConfigOptions().getMaxLocalJobs(), offset); openstudio::runmanager::Job job = workflow.create(outdir); kit.enqueue(job, true); kit.waitForFinished(); openstudio::path sqlpath = job.treeOutputFiles().getLastByExtension("sql").fullPath; openstudio::SqlFile sqlfile(sqlpath); return sqlfile; } double compareSqlFile(const openstudio::SqlFile &sf1, const openstudio::SqlFile &sf2) { return *sf1.netSiteEnergy() - *sf2.netSiteEnergy(); } double compare(double v1, double v2) { return v1-v2; } double compareUses(const openstudio::runmanager::FuelUses &t_fuse1, const openstudio::runmanager::FuelUses &t_fuse2) { double gas1 = t_fuse1.fuelUse(openstudio::FuelType::Gas); double elec1 = t_fuse1.fuelUse(openstudio::FuelType::Electricity); double gas2 = t_fuse2.fuelUse(openstudio::FuelType::Gas); double elec2 = t_fuse2.fuelUse(openstudio::FuelType::Electricity); LOG_FREE(Info, "compareUses", "Gas1 " << gas1 << " gas2 " << gas2 << " Gas Difference " << gas1 - gas2); LOG_FREE(Info, "compareUses", "Elec1 " << elec1 << " elec2 " << elec2 << " Elec Difference " << elec1 - elec2); double totalerror = (gas1+elec1) - (gas2+elec2); LOG_FREE(Info, "compareUses", "Total Error" << totalerror); return totalerror; } std::pair<double, double> runSimulation(openstudio::runmanager::ErrorEstimation &t_ee, double t_rotation) { openstudio::model::Model m = openstudio::model::exampleModel(); openstudio::model::Building b = *m.building(); b.setNorthAxis(b.northAxis() + t_rotation); QElapsedTimer et; et.start(); openstudio::SqlFile sqlfile1(runSimulation(m, false)); qint64 originaltime = et.restart(); openstudio::SqlFile sqlfile2(runSimulation(m, true)); qint64 reducedtime = et.elapsed(); openstudio::path weatherpath = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw"); openstudio::isomodel::ForwardTranslator translator; openstudio::isomodel::UserModel userModel = translator.translateModel(m); userModel.setWeatherFilePath(weatherpath); openstudio::isomodel::SimModel simModel = userModel.toSimModel(); openstudio::isomodel::ISOResults isoResults = simModel.simulate(); LOG_FREE(Info, "runSimulation", "OriginalTime " << originaltime << " reduced " << reducedtime); std::vector<double> variables; variables.push_back(t_rotation); openstudio::runmanager::FuelUses fuses0(0); try { fuses0 = t_ee.approximate(variables); } catch (const std::exception &e) { LOG_FREE(Info, "runSimulation", "Unable to generate estimate: " << e.what()); } openstudio::runmanager::FuelUses fuses3 = t_ee.add(userModel, isoResults, "ISO", variables); openstudio::runmanager::FuelUses fuses2 = t_ee.add(sqlfile2, "Estimation", variables); openstudio::runmanager::FuelUses fuses1 = t_ee.add(sqlfile1, "FullRun", variables); LOG_FREE(Info, "runSimulation", "Comparing Full Run to linear approximation"); compareUses(fuses1, fuses0); LOG_FREE(Info, "runSimulation", "Comparing Full Run to error adjusted ISO run"); return std::make_pair(compare(*sqlfile1.netSiteEnergy(), isoResults.totalEnergyUse()), compareUses(fuses1, fuses3)); } TEST_F(RunManagerTestFixture, ErrorEstimationTest) { openstudio::runmanager::ErrorEstimation ee(1); ee.setConfidence("FullRun", 1.0); ee.setConfidence("Estimation", 0.75); ee.setConfidence("ISO", 0.50); std::pair<double, double> run1 = runSimulation(ee, 0); LOG(Info, "Run1 initialerror: " << run1.first*1000000000 << " adjustederror: " << run1.second); std::pair<double, double> run2 = runSimulation(ee, 90); LOG(Info, "Run2 initialerror: " << run2.first*1000000000 << " adjustederror: " << run2.second); std::pair<double, double> run3 = runSimulation(ee, 180); LOG(Info, "Run3 initialerror: " << run3.first*1000000000 << " adjustederror: " << run3.second); std::pair<double, double> run4 = runSimulation(ee, 270); LOG(Info, "Run4 initialerror: " << run4.first*1000000000 << " adjustederror: " << run4.second); // std::pair<double, double> run5 = runSimulation(ee, 225); // LOG(Info, "Run5 initialerror: " << run5.first*1000000000 << " adjustederror: " << run5.second); } TEST_F(RunManagerTestFixture, LinearApproximationTestSimple) { LinearApproximation la(1); std::vector<double> vals; vals.push_back(0); la.addVals(vals, 0); vals[0] = 2; la.addVals(vals, 2); EXPECT_DOUBLE_EQ(2.0, la.approximate(vals)); vals[0] = 0; EXPECT_DOUBLE_EQ(0.0, la.approximate(vals)); vals[0] = 1; EXPECT_DOUBLE_EQ(1.0, la.approximate(vals)); } TEST_F(RunManagerTestFixture, LinearApproximationTestHuge) { const size_t size = 200; LinearApproximation la(size); std::vector<double> vals(size); // just establish a baseline for (size_t i = 0; i < size; ++i) { vals[i] = i; } // let's say that this equals 100 la.addVals(vals, 100); // and we should be able to get back the value we just put in EXPECT_EQ(100.0, la.approximate(vals)); // now we'll modify one variable at a time for (size_t i = 0; i < size; ++i) { std::vector<double> newvals(vals); double origVariable = newvals[i]; double newVariable = origVariable * 2.0; newvals[i] = newVariable; double valueAtThisPoint = 100.0 + newvals[i]; la.addVals(newvals, valueAtThisPoint); EXPECT_DOUBLE_EQ(valueAtThisPoint, la.approximate(newvals)); newvals[i] = (origVariable + newVariable) / 2; EXPECT_DOUBLE_EQ((valueAtThisPoint + 100.0) / 2, la.approximate(newvals)); } vals[size/10] = 62.4; vals[size/8] = 99; vals[size/6] = 99; vals[size/4] = 102; vals[size/2] = 102; la.approximate(vals); }
33.981343
144
0.676183
zhouchong90
056385addecf1c5c6e493ce4be2b08b27e21f22c
2,688
cpp
C++
src/effect.cpp
limal/nit
a1db3068d8f7426a1700e4729c247db97f9af9de
[ "Zlib" ]
2
2015-09-19T00:43:34.000Z
2016-05-31T19:33:22.000Z
src/effect.cpp
limal/nit
a1db3068d8f7426a1700e4729c247db97f9af9de
[ "Zlib" ]
null
null
null
src/effect.cpp
limal/nit
a1db3068d8f7426a1700e4729c247db97f9af9de
[ "Zlib" ]
null
null
null
/* Copyright (C) 2010 Lukasz Wolnik 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. Lukasz Wolnik lukasz.wolnik@o2.pl */ #include "StdAfx.h" #include "effect.h" #include "graphics.h" using namespace nit; IEffect::IEffect(Graphics* gfx, wchar_t* filename) : effect(0) { ID3DXBuffer* errors = 0; IDirect3DDevice9* device = gfx->GetDevice(); D3DXCreateEffectFromFile(device, filename, 0, 0, D3DXSHADER_DEBUG, 0, &effect, &errors); // TODO // // Remove dependency to dxerr.lib from March 2009 DirectX SDK if (errors) { MessageBoxA(NULL, (char*)errors->GetBufferPointer(), 0, 0); } gfx->AddOnLostDevice(&MakeDelegate(this, &IEffect::OnLostDevice)); gfx->AddOnResetDevice(&MakeDelegate(this, &IEffect::OnResetDevice)); } IEffect::~IEffect() { effect->Release(); } void IEffect::Begin(unsigned int* num_passes) { effect->Begin(num_passes, 0); } void IEffect::BeginPass(unsigned int pass) { effect->BeginPass(pass); } void IEffect::CommitChanges() { effect->CommitChanges(); } void IEffect::End() { effect->End(); } void IEffect::EndPass() { effect->EndPass(); } void IEffect::GetParameterByName(char* name) { params[name] = effect->GetParameterByName(0, name); } void IEffect::GetTechniqueByName(char* name) { params[name] = effect->GetTechniqueByName(name); } void IEffect::OnLostDevice() { effect->OnLostDevice(); } void IEffect::OnResetDevice() { effect->OnResetDevice(); } void IEffect::SetFloat(char* name, const float f) { effect->SetFloat(params[name], f); } void IEffect::SetMatrix(char* name, const D3DXMATRIX *matrix) { effect->SetMatrix(params[name], matrix); } void IEffect::SetTechnique(char* name) { effect->SetTechnique(params[name]); } void IEffect::SetTexture(char* name, IDirect3DTexture9* texture) { effect->SetTexture(params[name], texture); } void IEffect::SetVector(char* name, const D3DXVECTOR4* vector) { effect->SetVector(params[name], vector); }
21.853659
89
0.739583
limal
0565a1b5e9a933f750b3496639ca912fae31b108
709
cpp
C++
libsnes/bsnes/snes/alt/dsp/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
libsnes/bsnes/snes/alt/dsp/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
libsnes/bsnes/snes/alt/dsp/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
#ifdef DSP_CPP static void dsp_state_save(unsigned char **out, void *in, size_t size) { memcpy(*out, in, size); *out += size; } static void dsp_state_load(unsigned char **in, void *out, size_t size) { memcpy(out, *in, size); *in += size; } void DSP::serialize(serializer &s) { Processor::serialize(s); s.array(samplebuffer); unsigned char state[SPC_DSP::state_size]; unsigned char *p = state; memset(&state, 0, SPC_DSP::state_size); if(s.mode() == serializer::Save) { spc_dsp.copy_state(&p, dsp_state_save); s.array(state); } else if(s.mode() == serializer::Load) { s.array(state); spc_dsp.copy_state(&p, dsp_state_load); } else { s.array(state); } } #endif
22.15625
72
0.651622
ircluzar
0568e69a2d055267a721157689224fc5b3a29411
7,452
cpp
C++
src/cpu/resampling/ref_resampling.cpp
bhipple/mkl-dnn
ed1cf723ee94cf95b77af55fe1309374363b8edd
[ "Apache-2.0" ]
1
2020-09-18T04:34:16.000Z
2020-09-18T04:34:16.000Z
src/cpu/resampling/ref_resampling.cpp
awesomemachinelearning/mkl-dnn
ed1cf723ee94cf95b77af55fe1309374363b8edd
[ "Apache-2.0" ]
null
null
null
src/cpu/resampling/ref_resampling.cpp
awesomemachinelearning/mkl-dnn
ed1cf723ee94cf95b77af55fe1309374363b8edd
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include <assert.h> #include <float.h> #include <math.h> #include "c_types_map.hpp" #include "dnnl_thread.hpp" #include "math_utils.hpp" #include "type_helpers.hpp" #include "ref_resampling.hpp" #include "resampling_utils.hpp" namespace dnnl { namespace impl { namespace cpu { static inline dim_t get_offset( const memory_desc_wrapper &data_d, int n, int c, int d, int h, int w) { if (data_d.ndims() == 5) return data_d.off(n, c, d, h, w); else if (data_d.ndims() == 4) return data_d.off(n, c, h, w); else return data_d.off(n, c, w); } using namespace resampling_utils; template <impl::data_type_t data_type> void ref_resampling_fwd_t<data_type>::execute_forward( const exec_ctx_t &ctx) const { if (this->pd()->has_zero_dim_memory()) return; const auto src = CTX_IN_MEM(const data_t *, DNNL_ARG_SRC); auto dst = CTX_OUT_MEM(data_t *, DNNL_ARG_DST); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const auto alg = pd()->desc()->alg_kind; const int MB = pd()->MB(); const int C = pd()->C(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int OD = pd()->OD(); const int OH = pd()->OH(); const int OW = pd()->OW(); const float FD = pd()->FD(); const float FH = pd()->FH(); const float FW = pd()->FW(); auto lin_interp = [&](float c0, float c1, float w) { return c0 * w + c1 * (1 - w); }; auto bilin_interp = [&](float c00, float c01, float c10, float c11, float w0, float w1) { return lin_interp( lin_interp(c00, c10, w0), lin_interp(c01, c11, w0), w1); }; auto trilin_interp = [&](float c000, float c010, float c100, float c110, float c001, float c011, float c101, float c111, float w0, float w1, float w2) { return lin_interp(bilin_interp(c000, c010, c100, c110, w0, w1), bilin_interp(c001, c011, c101, c111, w0, w1), w2); }; parallel_nd(MB, C, OD, OH, OW, [&](dim_t mb, dim_t ch, dim_t od, dim_t oh, dim_t ow) { if (alg == alg_kind::resampling_nearest) { dim_t id = nearest_idx(od, FD), ih = nearest_idx(oh, FH), iw = nearest_idx(ow, FW); dst[get_offset(dst_d, mb, ch, od, oh, ow)] = src[get_offset(src_d, mb, ch, id, ih, iw)]; } else if (alg == alg_kind::resampling_linear) { // Trilinear interpolation (linear interpolation on a 3D spatial // tensor) can be expressed as linear interpolation along // dimension x followed by interpolation along dimension y and z // C011--C11--C111 // - - | // - - | //C001--C01--C111 | // - .C - C110 // - - - // - - - //C000--C00--C100 auto id = linear_coeffs_t(od, FD, ID); auto iw = linear_coeffs_t(ow, FW, IW); auto ih = linear_coeffs_t(oh, FH, IH); dim_t src_l[8] = {0}; for_(int i = 0; i < 2; i++) for_(int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) { src_l[4 * i + 2 * j + k] = src[get_offset(src_d, mb, ch, id.idx[i], ih.idx[j], iw.idx[k])]; } dst[get_offset(dst_d, mb, ch, od, oh, ow)] = trilin_interp(src_l[0], src_l[1], src_l[2], src_l[3], src_l[4], src_l[5], src_l[6], src_l[7], id.wei[0], ih.wei[0], iw.wei[0]); } }); } template struct ref_resampling_fwd_t<data_type::f32>; template struct ref_resampling_fwd_t<data_type::bf16>; template <impl::data_type_t data_type> void ref_resampling_bwd_t<data_type>::execute_backward( const exec_ctx_t &ctx) const { if (this->pd()->has_zero_dim_memory()) return; const auto diff_dst = CTX_IN_MEM(const data_t *, DNNL_ARG_DIFF_DST); auto diff_src = CTX_OUT_MEM(data_t *, DNNL_ARG_DIFF_SRC); const memory_desc_wrapper diff_src_d(pd()->diff_src_md()); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const auto alg = pd()->desc()->alg_kind; const int MB = pd()->MB(); const int C = pd()->C(); const int ID = pd()->ID(); const int IH = pd()->IH(); const int IW = pd()->IW(); const int OD = pd()->OD(); const int OH = pd()->OH(); const int OW = pd()->OW(); const float FD = pd()->FD(); const float FH = pd()->FH(); const float FW = pd()->FW(); parallel_nd(MB, C, ID, IH, IW, [&](dim_t mb, dim_t ch, dim_t id, dim_t ih, dim_t iw) { diff_src[get_offset(diff_src_d, mb, ch, id, ih, iw)] = 0.f; }); parallel_nd(MB, C, [&](dim_t mb, dim_t ch) { for_(int od = 0; od < OD; ++od) for_(int oh = 0; oh < OH; ++oh) for (int ow = 0; ow < OW; ++ow) { if (alg == alg_kind::resampling_nearest) { dim_t id = nearest_idx(od, FD), ih = nearest_idx(oh, FH), iw = nearest_idx(ow, FW); diff_src[get_offset(diff_src_d, mb, ch, id, ih, iw)] += diff_dst[get_offset(diff_dst_d, mb, ch, od, oh, ow)]; } else if (alg == alg_kind::resampling_linear) { auto id = linear_coeffs_t(od, FD, ID); auto iw = linear_coeffs_t(ow, FW, IW); auto ih = linear_coeffs_t(oh, FH, IH); // accessor for source values on a cubic lattice data_t dd = diff_dst[get_offset(diff_dst_d, mb, ch, od, oh, ow)]; for_(int i = 0; i < 2; i++) for_(int j = 0; j < 2; j++) for (int k = 0; k < 2; k++) { auto off = get_offset(diff_src_d, mb, ch, id.idx[i], ih.idx[j], iw.idx[k]); diff_src[off] += dd * id.wei[i] * ih.wei[j] * iw.wei[k]; } } } }); } template struct ref_resampling_bwd_t<data_type::f32>; template struct ref_resampling_bwd_t<data_type::bf16>; } // namespace cpu } // namespace impl } // namespace dnnl // vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
39.428571
84
0.510735
bhipple
056e10daebea881f4612325d74584eca8bd8ec2b
5,767
cpp
C++
tests/test_os_char_driver.cpp
KKoovalsky/JunglesOsStructs
33b3341aa7d99b152a6cb95bc3016bf78d6f5535
[ "MIT" ]
null
null
null
tests/test_os_char_driver.cpp
KKoovalsky/JunglesOsStructs
33b3341aa7d99b152a6cb95bc3016bf78d6f5535
[ "MIT" ]
null
null
null
tests/test_os_char_driver.cpp
KKoovalsky/JunglesOsStructs
33b3341aa7d99b152a6cb95bc3016bf78d6f5535
[ "MIT" ]
null
null
null
/** * @file test_os_char_driver.cpp * @brief Tests os_char_driver template * @author Kacper Kowalski - kacper.s.kowalski@gmail.com */ #include "os_char_driver.hpp" #include "os_task.hpp" #include "unity.h" #include <array> #include <csignal> #include <functional> #include <iostream> #include <string> #include <string_view> #include <vector> using namespace jungles; #define SIGNAL_TX SIGRTMIN #define SIGNAL_RX (SIGRTMIN + 1) // -------------------------------------------------------------------------------------------------------------------- // DECLARATION OF THE TEST CASES // -------------------------------------------------------------------------------------------------------------------- static void UNIT_TEST_1_block_on_read_and_unblock_on_message_received(); static void UNIT_TEST_2_blocking_write_multiple_string_types(); // -------------------------------------------------------------------------------------------------------------------- // DECLARATION OF PRIVATE FUNCTIONS AND VARIABLES // -------------------------------------------------------------------------------------------------------------------- static std::function<void(void)> tx_isr_handler, rx_isr_handler; static std::function<void(char)> byte_sender; static void helper_set_tx_isr_handler(std::function<void(void)> f); static void helper_set_rx_isr_handler(std::function<void(void)> f); static void helper_set_byte_sender(std::function<void(char)> f); static bool tx_isr_enabled; static void tx_isr_handler_callback(int signal); static void rx_isr_handler_callback(int signal); static void tx_it_enable(); static void tx_it_disable(); static void rx_it_enable(); static void rx_it_disable(); static void byte_send(char c); // -------------------------------------------------------------------------------------------------------------------- // EXECUTION OF THE TESTS // -------------------------------------------------------------------------------------------------------------------- void test_os_char_driver() { std::signal(SIGNAL_TX, tx_isr_handler_callback); std::signal(SIGNAL_RX, rx_isr_handler_callback); RUN_TEST(UNIT_TEST_1_block_on_read_and_unblock_on_message_received); RUN_TEST(UNIT_TEST_2_blocking_write_multiple_string_types); std::signal(SIGNAL_TX, SIG_DFL); std::signal(SIGNAL_RX, SIG_DFL); } // -------------------------------------------------------------------------------------------------------------------- // DEFINITION OF THE TEST CASES // -------------------------------------------------------------------------------------------------------------------- static void UNIT_TEST_1_block_on_read_and_unblock_on_message_received() { os_char_driver<64, 16> chardrv{tx_it_enable, tx_it_disable, rx_it_enable, rx_it_disable, byte_send}; auto reader_task_handle = os_task_get_current_task_handle(); os_task sync_reader_task( [reader_task_handle, &chardrv]() { // Ensure readline() will be called os_task_yield(); os_task_yield(); os_task_yield(); for (unsigned state = os_task_state_running; state != os_task_state_blocked && state != os_task_state_blocked; state = os_task_get_state(reader_task_handle)) os_delay_ms(1); helper_set_rx_isr_handler([&chardrv]() { static constexpr char test_string_rcvd[] = "makapaka"; static const char *it = test_string_rcvd; static constexpr const char *end = test_string_rcvd + std::distance(std::begin(test_string_rcvd), std::end(test_string_rcvd)); if (it != end) { chardrv.rx_isr_handler(*it++); std::raise(SIGNAL_RX); } }); std::raise(SIGNAL_RX); }, "sync_reader", 256, 1); auto line = chardrv.readline(os_no_timeout); TEST_ASSERT_EQUAL_STRING("makapaka", line.c_str()); os_task_yield(); } static void UNIT_TEST_2_blocking_write_multiple_string_types() { os_char_driver<64, 16> chardrv{tx_it_enable, tx_it_disable, rx_it_enable, rx_it_disable, byte_send}; std::string s{"std::string"}; std::vector v{'s', 't', 'd', ':', ':', 'v', 'e', 'c', 't', 'o', 'r'}; std::array<char, 10> a{'s', 't', 'd', ':', ':', 'a', 'r', 'r', 'a', 'y'}; std::string sv{"std::string_view"}; std::string result; helper_set_byte_sender([&result](char c) { result += c; }); helper_set_tx_isr_handler([&chardrv]() { chardrv.tx_isr_handler(); }); chardrv.write(s, v, a, sv); TEST_ASSERT_EQUAL_STRING("std::stringstd::vectorstd::arraystd::string_view", result.c_str()); } // -------------------------------------------------------------------------------------------------------------------- // DEFINITION OF PRIVATE FUNCTIONS // -------------------------------------------------------------------------------------------------------------------- static void helper_set_tx_isr_handler(std::function<void(void)> f) { tx_isr_handler = f; } static void helper_set_rx_isr_handler(std::function<void(void)> f) { rx_isr_handler = f; } static void tx_isr_handler_callback(int signal) { tx_isr_handler(); if (tx_isr_enabled) std::raise(SIGNAL_TX); } static void rx_isr_handler_callback(int signal) { rx_isr_handler(); } static void helper_set_byte_sender(std::function<void(char)> f) { byte_sender = f; } static void tx_it_enable() { tx_isr_enabled = true; std::raise(SIGNAL_TX); } static void tx_it_disable() { tx_isr_enabled = false; } static void rx_it_enable() { } static void rx_it_disable() { } static void byte_send(char c) { byte_sender(c); }
33.923529
119
0.542396
KKoovalsky
057034491dd499f87a2e96c9394bc97ddf53ba3f
1,215
cc
C++
src/ast/ArrayLiteral.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
1
2020-01-06T09:43:56.000Z
2020-01-06T09:43:56.000Z
src/ast/ArrayLiteral.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
src/ast/ArrayLiteral.cc
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
#include "ArrayLiteral.hh" void ArrayLiteral::add_expression(ptr_t<Expression> &expression) { m_expressions.push_back(std::move(expression)); } void ArrayLiteral::analyze(Scope *scope) { m_type.change_kind(Kind::ARRAY); if (m_expressions.empty()) { m_type.change_primitive(Primitive::DONT_CARE); return; } m_expressions.front()->analyze(scope); Type first = m_expressions.front()->type(); for (unsigned i = 1; i < m_expressions.size(); ++i) { auto &current = m_expressions.at(i); current->analyze(scope); if (!current->is_literal()) { error::add_semantic_error("Array literals require literal values", source_ref); } if (current->type() != first) { error::add_semantic_error("Mismatched types in array literal", source_ref); } } m_type.change_primitive(first.primitive()); } std::string ArrayLiteral::dump(unsigned indent) const { std::ostringstream oss {}; oss << util::indent(indent) << name() << " [" << std::endl; for (auto &x : m_expressions) { oss << x->dump(indent + 1) << std::endl; } oss << util::indent(indent) << "]"; return oss.str(); }
27.613636
91
0.614815
walecome
0574c46d401ff119ce5fb2146c678e1a77fbb4d4
4,208
cc
C++
squid/squid3-3.3.8.spaceify/src/globals.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/globals.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/globals.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
#include "squid.h" /* * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * */ #include "acl/AclDenyInfoList.h" #include "CacheDigest.h" #include "defines.h" #include "hash.h" #include "IoStats.h" #include "rfc2181.h" #if HAVE_STDIO_H #include <stdio.h> #endif char *ConfigFile = NULL; char tmp_error_buf[ERROR_BUF_SZ]; char ThisCache[RFC2181_MAXHOSTNAMELEN << 1]; char ThisCache2[RFC2181_MAXHOSTNAMELEN << 1]; char config_input_line[BUFSIZ]; const char *DefaultConfigFile = DEFAULT_CONFIG_FILE; const char *cfg_filename = NULL; const char *dash_str = "-"; const char *null_string = ""; const char *version_string = VERSION; const char *appname_string = PACKAGE; char const *visible_appname_string = NULL; int Biggest_FD = -1; int Number_FD = 0; int Opening_FD = 0; int NDnsServersAlloc = 0; int RESERVED_FD; int Squid_MaxFD = SQUID_MAXFD; int config_lineno = 0; int do_mallinfo = 0; int opt_reuseaddr = 1; int neighbors_do_private_keys = 1; int opt_catch_signals = 1; int opt_foreground_rebuild = 0; char *opt_forwarded_for = NULL; int opt_reload_hit_only = 0; int opt_udp_hit_obj = 0; int opt_create_swap_dirs = 0; int opt_store_doublecheck = 0; int syslog_enable = 0; int DnsSocketA = -1; int DnsSocketB = -1; int n_disk_objects = 0; IoStats IOStats; AclDenyInfoList *DenyInfoList = NULL; struct timeval squid_start; int starting_up = 1; int shutting_down = 0; int reconfiguring = 0; time_t hit_only_mode_until = 0; double request_failure_ratio = 0.0; int store_hash_buckets = 0; hash_table *store_table = NULL; int hot_obj_count = 0; int CacheDigestHashFuncCount = 4; CacheDigest *store_digest = NULL; const char *StoreDigestFileName = "store_digest"; const char *StoreDigestMimeStr = "application/cache-digest"; const char *MultipartMsgBoundaryStr = "Unique-Squid-Separator"; #if USE_HTTP_VIOLATIONS int refresh_nocache_hack = 0; #endif int store_open_disk_fd = 0; int store_swap_low = 0; int store_swap_high = 0; size_t store_pages_max = 0; int64_t store_maxobjsize = -1; hash_table *proxy_auth_username_cache = NULL; int incoming_sockets_accepted; #if _SQUID_MSWIN_ unsigned int WIN32_Socks_initialized = 0; #endif #if _SQUID_WINDOWS_ unsigned int WIN32_OS_version = 0; char *WIN32_OS_string = NULL; char *WIN32_Service_name = NULL; char *WIN32_Command_Line = NULL; char *WIN32_Service_Command_Line = NULL; unsigned int WIN32_run_mode = _WIN_SQUID_RUN_MODE_INTERACTIVE; #endif #if HAVE_SBRK void *sbrk_start = 0; #endif int ssl_ex_index_server = -1; int ssl_ctx_ex_index_dont_verify_domain = -1; int ssl_ex_index_cert_error_check = -1; int ssl_ex_index_ssl_error_detail = -1; int ssl_ex_index_ssl_peeked_cert = -1; int ssl_ex_index_ssl_errors = -1; const char *external_acl_message = NULL; int opt_send_signal = -1; int opt_no_daemon = 0; int opt_parse_cfg_only = 0; /// current Squid process number (e.g., 4). /// Zero for SMP-unaware code and in no-SMP mode. int KidIdentifier = 0;
30.492754
72
0.753327
spaceify
05757127a7838beddc1bf07edd5253cb2ef89b80
4,301
cpp
C++
CarbonRender/Src/CRCinematicController.cpp
lanyu8/CarbonRender
dcd0a5d53ee2c458ad53c4e690359c250219ee22
[ "MIT" ]
44
2017-07-23T08:38:19.000Z
2022-03-27T02:53:10.000Z
CarbonRender/Src/CRCinematicController.cpp
lanyu8/CarbonRender
dcd0a5d53ee2c458ad53c4e690359c250219ee22
[ "MIT" ]
2
2018-10-10T15:56:58.000Z
2021-07-16T07:31:10.000Z
CarbonRender/Src/CRCinematicController.cpp
lanyu8/CarbonRender
dcd0a5d53ee2c458ad53c4e690359c250219ee22
[ "MIT" ]
14
2018-06-08T09:19:55.000Z
2022-03-17T08:04:57.000Z
#include "..\Inc\CRCinematicController.h" float CinematicController::GetCurrentTime() { clock_t currentTime; currentTime = clock(); return (float)currentTime/CLOCKS_PER_SEC; } void CinematicController::Init() { end = true; filmStartTime = -1; } void CinematicController::Update() { float stage0Cost = 6.0f; float stage1Cost = 3.0f; float stage2Cost = 6.0f; if (!end) { float currentTime = GetCurrentTime(); if (currentTime - filmStartTime >= stage0Cost + stage1Cost + stage2Cost) { end = true; } else { float process = (currentTime - filmStartTime) / (stage0Cost + stage1Cost + stage2Cost); process = Math::Min(process, 1.0f); float sunStartTime = 14.8f; float sunEndTime = 16.6f; float fogStartPrec = 55.0f; float fogEndPrec = 60.0f; float currentSunTime = (1.0f - process) * sunStartTime + process * sunEndTime; WeatherSystem::Instance()->SetHour(currentSunTime); float currentFogPrec = (1.0f - process) * fogStartPrec + process * fogEndPrec; WeatherSystem::Instance()->SetFogPrecipitation(currentFogPrec); if (currentTime - filmStartTime <= stage0Cost) { float3 camStartPos = float3(11.868318f, 5.0f, -8.464635f); float3 camEndPos = float3(11.868318f, 3.151639f, -8.464635f); process = (currentTime - filmStartTime) / stage0Cost; process = Math::Min(process, 1.0f); process = (-Math::Cos(process * PI) + 1.0f) * 0.5f; float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos; CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos); } else if (currentTime - filmStartTime <= stage0Cost + stage1Cost) { float3 camStartPos = float3(11.868318f, 3.151639f, -8.464635f); float3 camEndPos = float3(9.648738f, 3.151639f, -4.547123f); float3 camStartRota = float3(3.600040f, -54.599995f, 0.0f); float3 camEndRota = float3(1.500041f, -43.599918f, 0.0f); float camStartFov = 55.0f; float camEndFov = 60.0f; process = (currentTime - filmStartTime - stage0Cost) / stage1Cost; process = Math::Min(process, 1.0f); process = (-Math::Cos(process * PI) + 1.0f) * 0.5f; float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos; CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos); float3 camCurrentRota = (1.0f - process) * camStartRota + process * camEndRota; CameraManager::Instance()->GetCurrentCamera()->SetRotation(camCurrentRota); float camCurrentFov = (1.0f - process) * camStartFov + process * camEndFov; CameraManager::Instance()->GetCurrentCamera()->SetFov(camCurrentFov); } else { float3 camStartPos = float3(9.648738f, 3.151639f, -4.547123f); float3 camEndPos = float3(11.303256f, 3.151639f, -2.809704f); process = (currentTime - filmStartTime - stage0Cost - stage1Cost) / stage2Cost; process = Math::Min(process, 1.0f); process = (-Math::Cos(process * PI) + 1.0f) * 0.5f; float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos; CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos); } } } } void CinematicController::KeyInputCallback(GLFWwindow * window, int key, int scanCode, int action, int mods) { switch (key) { default: break; case GLFW_KEY_F1: { if (action == GLFW_PRESS) MenuManager::Instance()->ToogleMenu(); } break; case GLFW_KEY_P: { if (action == GLFW_PRESS) { ControllerManager::Instance()->Pop(); } } break; case GLFW_KEY_SPACE: { if (action == GLFW_PRESS && end) { WeatherSystem::Instance()->SetHour(14.8f); WeatherSystem::Instance()->SetFogPrecipitation(55.0f); CameraManager::Instance()->GetCurrentCamera()->SetFov(55.0f); CameraManager::Instance()->GetCurrentCamera()->SetPosition(float3(11.868318f, 5.0f, -8.464635f)); CameraManager::Instance()->GetCurrentCamera()->SetRotation(float3(3.600040f, -54.599995f, 0.0f)); filmStartTime = GetCurrentTime(); end = false; } } break; case GLFW_KEY_BACKSPACE: { if (action == GLFW_PRESS) { filmStartTime = GetCurrentTime(); } } break; } } void CinematicController::MouseMotionCallback(GLFWwindow * window, double x, double y) { } void CinematicController::ScrollCallback(GLFWwindow * window, double xOffset, double yOffset) { }
29.060811
108
0.686585
lanyu8
05785b84b5e654e85f09eb3050356cabd3289965
184
hpp
C++
plugins/arclite/example/headers.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
plugins/arclite/example/headers.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
plugins/arclite/example/headers.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <string> #include <list> #include <vector> #include <map> #include <iterator> using namespace std; #include <initguid.h> #include "CPP/7zip/Archive/IArchive.h"
15.333333
38
0.733696
TheChatty
0581e6944bec46067d0c8b50521a9f7e6ae526e9
467
cpp
C++
programmer/TestDataBus.cpp
cheinan/eeprom
690f9adeb7c3a06aec3c3600fd298b22ec76fb13
[ "MIT" ]
null
null
null
programmer/TestDataBus.cpp
cheinan/eeprom
690f9adeb7c3a06aec3c3600fd298b22ec76fb13
[ "MIT" ]
null
null
null
programmer/TestDataBus.cpp
cheinan/eeprom
690f9adeb7c3a06aec3c3600fd298b22ec76fb13
[ "MIT" ]
null
null
null
#include <iostream> #include "DataBus.h" #include "ControlLines.h" void TestDataBusWrite() { std::cout << "Testing the address bus\n"; ControlLines the_control_lines(HIGH, HIGH, HIGH); DataBus the_data_bus(true); unsigned short data = 1; for (unsigned char i = 0; i < 8;i++) { the_data_bus.Set(data); std::cout << "Data bus set to 0x" << std::hex << data << "\n"; std::cin.get(); data <<= 1; } } int main() { TestDataBusWrite(); return 0; }
15.566667
64
0.631692
cheinan
05824ee8344f61cfabe03ebd45d7232391c2a3e6
5,822
cpp
C++
llbc/src/core/objbase/DictionaryElem.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
83
2015-11-10T09:52:56.000Z
2022-01-12T11:53:01.000Z
llbc/src/core/objbase/DictionaryElem.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
30
2017-09-30T07:43:20.000Z
2022-01-23T13:18:48.000Z
llbc/src/core/objbase/DictionaryElem.cpp
lailongwei/llbc
ec7e69bfa1f0afece8bb19dfa9a0a4578508a077
[ "MIT" ]
34
2015-11-14T12:37:44.000Z
2021-12-16T02:38:36.000Z
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "llbc/common/Export.h" #include "llbc/common/BeforeIncl.h" #include "llbc/common/Config.h" #include "llbc/core/os/OS_Console.h" #include "llbc/core/utils/Util_Debug.h" #include "llbc/core/objbase/Object.h" #include "llbc/core/objbase/KeyHashAlgorithm.h" #include "llbc/core/objbase/DictionaryElem.h" __LLBC_INTERNAL_NS_BEGIN static LLBC_NS LLBC_String __emptyStrKey; __LLBC_INTERNAL_NS_END __LLBC_NS_BEGIN LLBC_DictionaryElem::LLBC_DictionaryElem(int key, LLBC_Object *o) : _intKey(key) , _strKey(NULL) , _hash(0) , _obj(o) , _bucket(NULL) , _bucketSize(0) , _prev(NULL) , _next(NULL) , _bucketPrev(NULL) , _bucketNext(NULL) , _hashFun(*LLBC_KeyHashAlgorithmSingleton->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO)) { o->Retain(); } LLBC_DictionaryElem::LLBC_DictionaryElem(const LLBC_String &key, LLBC_Object *o) : _intKey(0) , _strKey(LLBC_New(LLBC_String, key)) , _hash(0) , _obj(o) , _bucket(NULL) , _bucketSize(0) , _prev(NULL) , _next(NULL) , _bucketPrev(NULL) , _bucketNext(NULL) , _hashFun(*LLBC_KeyHashAlgorithmSingleton->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO)) { o->Retain(); } LLBC_DictionaryElem::~LLBC_DictionaryElem() { LLBC_XDelete(_strKey); _obj->Release(); } bool LLBC_DictionaryElem::IsIntKey() const { return !_strKey; } bool LLBC_DictionaryElem::IsStrKey() const { return !!_strKey; } const int &LLBC_DictionaryElem::GetIntKey() const { return _intKey; } const LLBC_String &LLBC_DictionaryElem::GetStrKey() const { return _strKey ? *_strKey : LLBC_INL_NS __emptyStrKey; } uint32 LLBC_DictionaryElem::GetHashValue() const { return _hash; } LLBC_Object *&LLBC_DictionaryElem::GetObject() { return _obj; } LLBC_Object * const &LLBC_DictionaryElem::GetObject() const { return _obj; } void LLBC_DictionaryElem::Hash(LLBC_DictionaryElem **bucket, size_t bucketSize) { _bucket = bucket; _bucketSize = bucketSize; // Generate hash key. if(IsIntKey()) { _hash = _intKey % _bucketSize; } else { _hash = _hashFun(_strKey->c_str(), _strKey->size()) % static_cast<uint32>(_bucketSize); } // Link to hash bucket. SetBucketElemPrev(NULL); LLBC_DictionaryElem *&hashed = _bucket[_hash]; if(!hashed) { SetBucketElemNext(NULL); hashed = this; } else { hashed->SetBucketElemPrev(this); SetBucketElemNext(hashed); hashed = this; #ifdef LLBC_DEBUG int confictCount = 0; LLBC_DictionaryElem *countElem = hashed; for(; countElem != NULL; countElem = countElem->GetBucketElemNext()) { confictCount += 1; } trace("Dictionary(addr: %x), key confict!, bucket: %d, count: %d\n", this, _hash, confictCount); #endif } } void LLBC_DictionaryElem::CancelHash() { if(_bucket[_hash] == this) { _bucket[_hash] = GetBucketElemNext(); } if(GetBucketElemPrev()) { GetBucketElemPrev()-> SetBucketElemNext(GetBucketElemNext()); } if(GetBucketElemNext()) { GetBucketElemNext()-> SetBucketElemPrev(GetBucketElemPrev()); } } LLBC_DictionaryElem **LLBC_DictionaryElem::GetBucket() { return _bucket; } size_t LLBC_DictionaryElem::GetBucketSize() const { return _bucketSize; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemPrev() { return _prev; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemPrev() const { return _prev; } void LLBC_DictionaryElem::SetElemPrev(LLBC_DictionaryElem *prev) { _prev = prev; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemNext() { return _next; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemNext() const { return _next; } void LLBC_DictionaryElem::SetElemNext(LLBC_DictionaryElem *next) { _next = next; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemPrev() { return _bucketPrev; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemPrev() const { return _bucketPrev; } void LLBC_DictionaryElem::SetBucketElemPrev(LLBC_DictionaryElem *prev) { _bucketPrev = prev; } LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemNext() { return _bucketNext; } const LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemNext() const { return _bucketNext; } void LLBC_DictionaryElem::SetBucketElemNext(LLBC_DictionaryElem *next) { _bucketNext = next; } LLBC_Object *&LLBC_DictionaryElem::operator *() { return _obj; } LLBC_Object * const &LLBC_DictionaryElem::operator *() const { return _obj; } __LLBC_NS_END #include "llbc/common/AfterIncl.h"
21.562963
104
0.714703
lailongwei
058b8021a09c1ed7b9b95f8b5c2a0d66fc88c4d5
4,281
hh
C++
src/phantasm-renderer/ComputePass.hh
project-arcana/phantasm-renderer
dd6f9af8d95f227f88c81194dea4a893761cac62
[ "MIT" ]
2
2020-10-22T18:09:11.000Z
2020-12-09T13:53:46.000Z
src/phantasm-renderer/ComputePass.hh
project-arcana/phantasm-renderer
dd6f9af8d95f227f88c81194dea4a893761cac62
[ "MIT" ]
1
2021-04-29T08:16:49.000Z
2021-04-30T07:54:25.000Z
src/phantasm-renderer/ComputePass.hh
project-arcana/phantasm-renderer
dd6f9af8d95f227f88c81194dea4a893761cac62
[ "MIT" ]
null
null
null
#pragma once #include <phantasm-hardware-interface/commands.hh> #include <phantasm-renderer/argument.hh> #include <phantasm-renderer/common/api.hh> #include <phantasm-renderer/fwd.hh> #include <phantasm-renderer/resource_types.hh> namespace pr::raii { class Frame; class PR_API ComputePass { public: [[nodiscard]] ComputePass bind(prebuilt_argument const& sv) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(sv._sv, phi::handle::null_resource, 0); return p; } [[nodiscard]] ComputePass bind(prebuilt_argument const& sv, buffer const& constant_buffer, uint32_t constant_buffer_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(sv._sv, constant_buffer.res.handle, constant_buffer_offset); return p; } // CBV only [[nodiscard]] ComputePass bind(buffer const& constant_buffer, uint32_t constant_buffer_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(phi::handle::null_shader_view, constant_buffer.res.handle, constant_buffer_offset); return p; } // raw phi [[nodiscard]] ComputePass bind(phi::handle::shader_view sv, phi::handle::resource cbv = phi::handle::null_resource, uint32_t cbv_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_argument(sv, cbv, cbv_offset); return p; } // cache-access variants // hits a OS mutex [[nodiscard]] ComputePass bind(argument const& arg) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_cached_argument(arg, phi::handle::null_resource, 0); return p; } [[nodiscard]] ComputePass bind(argument const& arg, buffer const& constant_buffer, uint32_t constant_buffer_offset = 0) { ComputePass p = {mParent, mCmd, mArgNum}; p.add_cached_argument(arg, constant_buffer.res.handle, constant_buffer_offset); return p; } void dispatch(uint32_t x, uint32_t y = 1, uint32_t z = 1); void dispatch_indirect(buffer const& argument_buffer, uint32_t num_arguments = 1, uint32_t offset_bytes = 0); void set_constant_buffer(buffer const& constant_buffer, unsigned offset = 0); void set_constant_buffer(phi::handle::resource raw_cbv, unsigned offset = 0); void set_constant_buffer_offset(unsigned offset); template <class T> void write_constants(T const& val) { mCmd.write_root_constants<T>(val); } ComputePass(ComputePass&& rhs) = default; private: friend class Frame; // Frame-side ctor ComputePass(Frame* parent, phi::handle::pipeline_state pso) : mParent(parent) { mCmd.pipeline_state = pso; } private: // internal re-bind ctor ComputePass(Frame* parent, phi::cmd::dispatch const& cmd, unsigned arg_i) : mParent(parent), mCmd(cmd), mArgNum(arg_i) {} private: // persisted, raw phi void add_argument(phi::handle::shader_view sv, phi::handle::resource cbv, uint32_t cbv_offset); // cache-access variant // hits a OS mutex void add_cached_argument(argument const& arg, phi::handle::resource cbv, uint32_t cbv_offset); Frame* mParent = nullptr; phi::cmd::dispatch mCmd; // index of owning argument - 1, 0 means no arguments existing unsigned mArgNum = 0; }; // inline implementation inline void ComputePass::set_constant_buffer(const buffer& constant_buffer, unsigned offset) { set_constant_buffer(constant_buffer.res.handle, offset); } inline void ComputePass::set_constant_buffer(phi::handle::resource raw_cbv, unsigned offset) { CC_ASSERT(mArgNum != 0 && "Attempted to set_constant_buffer on a ComputePass without prior bind"); mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer = raw_cbv; mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer_offset = offset; } inline void ComputePass::set_constant_buffer_offset(unsigned offset) { CC_ASSERT(mArgNum != 0 && "Attempted to set_constant_buffer_offset on a ComputePass without prior bind"); mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer_offset = offset; } inline void ComputePass::add_argument(phi::handle::shader_view sv, phi::handle::resource cbv, uint32_t cbv_offset) { ++mArgNum; mCmd.add_shader_arg(cbv, cbv_offset, sv); } }
33.445313
144
0.705443
project-arcana
058dbe3b9450e1fda9666c2ec33f238bee8610a0
3,337
cpp
C++
src/Engine/ResourceManager.cpp
ennis/autograph-pipelines
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
[ "MIT" ]
1
2021-04-24T12:29:42.000Z
2021-04-24T12:29:42.000Z
src/Engine/ResourceManager.cpp
ennis/autograph-pipelines
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
[ "MIT" ]
null
null
null
src/Engine/ResourceManager.cpp
ennis/autograph-pipelines
afc66ef60bf99fca26d200bd7739528e1bf3ed8c
[ "MIT" ]
null
null
null
#include <autograph/Core/Support/Debug.h> #include <autograph/Core/Support/string_view.h> #include <autograph/Core/Types.h> #include <autograph/Engine/ResourceManager.h> #include <experimental/filesystem> namespace ag { namespace fs = std::experimental::filesystem; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// namespace ResourceManager { static std::vector<std::string> resourceDirectories_; // returns the main path part of the ID, or the empty string if it has none std::string getPathPart(const char *id) { ag::string_view idstr{id}; return idstr.substr(0, idstr.find_last_of('$')).to_string(); } std::string getPathPart(const std::string &id) { return getPathPart(id.c_str()); } // returns the subpath part of the ID, or the empty string if it has none std::string getSubpathPart(const char *id) { ag::string_view idstr{id}; auto p = idstr.find_last_of('$'); if (p == std::string::npos) { return {}; } else { return idstr.substr(p + 1).to_string(); } } std::string getSubpathPart(const std::string &id) { return getSubpathPart(id.c_str()); } std::string getParentPath(const char *id) { fs::path path = getPathPart(id); return path.parent_path().generic_string(); } std::string getParentPath(const std::string &id) { return getParentPath(id.c_str()); } void addResourceDirectory(const std::string &fullPath) { addResourceDirectory(fullPath.c_str()); } void addResourceDirectory(const char *fullPath) { resourceDirectories_.emplace_back(fullPath); } int getResourceDirectoriesCount() { return (int)resourceDirectories_.size(); } std::string getResourceDirectory(int index) { return resourceDirectories_[index]; } std::string getFilesystemPath(const char *id) { return getFilesystemPath(id, {}); } std::string getFilesystemPath(const std::string &id) { return getFilesystemPath(id.c_str()); } std::string getFilesystemPath(const char *id, ag::span<const char *const> prefixes) { namespace fs = std::experimental::filesystem; std::string pathPart = getPathPart(id); std::string ret; // first, check if ID is a well-specified filesystem path fs::path path{pathPart}; if (fs::is_regular_file(path)) { return pathPart; } for (auto &dir : resourceDirectories_) { fs::path baseDir{dir}; if (prefixes.empty()) { auto fullPath = baseDir / pathPart; if (fs::is_regular_file(fullPath)) { // got our file AG_DEBUG("{} -> {}", pathPart, fullPath.string()); ret = fullPath.string(); return ret; } } else { for (auto prefix : prefixes) { auto fullPath = baseDir / prefix / pathPart; if (fs::is_regular_file(fullPath)) { // got our file AG_DEBUG("{} -> {}", pathPart, fullPath.string()); ret = fullPath.string(); return ret; } } } } AG_DEBUG("findResourceFile: {} not found", pathPart); AG_DEBUG(" Tried directories:"); for (auto &dir : resourceDirectories_) { AG_DEBUG(" - {}", dir); } if (!prefixes.empty()) { AG_DEBUG(" Tried prefixes:"); for (auto prefix : prefixes) { AG_DEBUG(" - {}", prefix); } } return {}; } } // namespace ResourceManager } // namespace ag
26.91129
78
0.633203
ennis
058e03ba87822896688a16ae33e7c0490f2658e7
5,344
cpp
C++
particles-simulator/src/OpenGL/Shader.cpp
bartos97/particles-simulator
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
[ "WTFPL" ]
null
null
null
particles-simulator/src/OpenGL/Shader.cpp
bartos97/particles-simulator
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
[ "WTFPL" ]
null
null
null
particles-simulator/src/OpenGL/Shader.cpp
bartos97/particles-simulator
dc2fc18fbc047803b3c17d7cc7bf9dbc99b00a2b
[ "WTFPL" ]
null
null
null
#include "pch.h" #include "Shader.h" #include <fstream> #include <sstream> const Shader* Shader::m_currentlyBound = nullptr; Shader::Shader(const char* vertexShaderPath, const char* fragmentShaderPath) : m_id(0) { PS_LOG("Shader object constructed"); assignData(vertexShaderPath, fragmentShaderPath); m_isDataAssigned = true; } Shader::Shader() : m_isDataAssigned(false), m_id(0) { PS_LOG("Shader object constructed without data assignment!"); } Shader::~Shader() { GL_CALL(glDeleteProgram(m_id)); PS_LOG("Shader #%d deleted", m_id); } void Shader::assignData(const char* vertexShaderPath, const char* fragmentShaderPath) { std::string vertexStr; std::string fragmentStr; readFiles(vertexShaderPath, fragmentShaderPath, vertexStr, fragmentStr); createShaderProgram(vertexStr, fragmentStr); m_isDataAssigned = true; PS_LOG("Shader #%d data assigned", m_id); } void Shader::bind() const { PS_ASSERT(m_isDataAssigned, "Tring to bind Shader without data assigned!"); if (Shader::m_currentlyBound != this) { GL_CALL(glUseProgram(m_id)); Shader::m_currentlyBound = this; PS_LOG("Shader #%d is now bound", m_id); } } void Shader::unbind() const { GL_CALL(glUseProgram(0)); Shader::m_currentlyBound = nullptr; PS_LOG("No Shader bound."); } void Shader::setUniform(const std::string& name, float x) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform1f(location, x); } void Shader::setUniform(const std::string& name, bool x) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform1i(location, x); } void Shader::setUniform(const std::string& name, int x) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform1i(location, x); } void Shader::setUniform(const std::string& name, float x, float y, float z, float w) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform4f(location, x, y, z, w); } void Shader::setUniform(const std::string& name, const glm::vec4& vec) { setUniform(name, vec.x, vec.y, vec.z, vec.w); } void Shader::setUniform(const std::string& name, float x, float y, float z) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform3f(location, x, y, z); } void Shader::setUniform(const std::string& name, const glm::vec3& vec) { setUniform(name, vec.x, vec.y, vec.z); } void Shader::setUniform(const std::string& name, float x, float y) { int location = glGetUniformLocation(m_id, name.c_str()); glUniform2f(location, x, y); } void Shader::setUniform(const std::string& name, const glm::vec2& vec) { setUniform(name, vec.x, vec.y); } void Shader::setUniform(const std::string& name, const glm::mat4& mat) { int location = glGetUniformLocation(m_id, name.c_str()); glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(mat)); } void Shader::setUniform(const std::string& name, const glm::mat3& mat) { int location = glGetUniformLocation(m_id, name.c_str()); glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(mat)); } void Shader::readFiles(const char* vertexShaderPath, const char* fragmentShaderPath, std::string& vertexStr, std::string& fragmentStr) { std::ifstream vertexFile; std::ifstream fragmentFile; vertexFile.exceptions(std::ifstream::badbit | std::ifstream::failbit); fragmentFile.exceptions(std::ifstream::badbit | std::ifstream::failbit); try { std::stringstream vertexStream; vertexFile.open(vertexShaderPath); vertexStream << vertexFile.rdbuf(); vertexFile.close(); vertexStr = vertexStream.str(); std::stringstream fragmentStream; fragmentFile.open(fragmentShaderPath); fragmentStream << fragmentFile.rdbuf(); fragmentFile.close(); fragmentStr = fragmentStream.str(); } catch (const std::exception & e) { PS_ASSERT(false, "Failed with some shader file!\n%s", e.what()); } } void Shader::createShaderProgram(std::string& vertexStr, std::string& fragmentStr) { unsigned int vertexShader = compileSingleShader(vertexStr.c_str(), GL_VERTEX_SHADER); unsigned int fragmentShader = compileSingleShader(fragmentStr.c_str(), GL_FRAGMENT_SHADER); int success; GL_CALL(m_id = glCreateProgram()); GL_CALL(glAttachShader(m_id, vertexShader)); GL_CALL(glAttachShader(m_id, fragmentShader)); GL_CALL(glLinkProgram(m_id)); glGetProgramiv(m_id, GL_LINK_STATUS, &success); if (!success) { char errorInfo[512]; glGetProgramInfoLog(m_id, 512, NULL, errorInfo); PS_ASSERT(success, "%s", errorInfo); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); } unsigned int Shader::compileSingleShader(const char* shaderStr, GLenum shaderEnum) { int success; GL_CALL(unsigned int shader = glCreateShader(shaderEnum)); GL_CALL(glShaderSource(shader, 1, &shaderStr, NULL)); GL_CALL(glCompileShader(shader)); glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { char errorInfo[512]; glGetShaderInfoLog(shader, 512, NULL, errorInfo); PS_ASSERT(success, "%s", errorInfo); } return shader; }
26.72
95
0.680015
bartos97
05901ad8b5edb9a693c390620e47089fdada2186
384
hpp
C++
Loader.hpp
mcgillowen/cpsc453-hw2
2276beec4102da044a4d2c4888089a5eb47eb79c
[ "MIT" ]
null
null
null
Loader.hpp
mcgillowen/cpsc453-hw2
2276beec4102da044a4d2c4888089a5eb47eb79c
[ "MIT" ]
null
null
null
Loader.hpp
mcgillowen/cpsc453-hw2
2276beec4102da044a4d2c4888089a5eb47eb79c
[ "MIT" ]
null
null
null
// Loader.hpp // Class that loads a .obj file into vectors of floats for OpenGL #ifndef LOADER_HPP #define LOADER_HPP #include <vector> #include "IndexedVertexArray.hpp" #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> using std::vector; class Loader { private: public: static IndexedVertexArray* loadObjFile(const char * path); }; #endif // LOADER_HPP
16
66
0.713542
mcgillowen
05908226497d855649fa2daee06a5d7100e553ec
870
cpp
C++
src/problem38/Solution1.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
src/problem38/Solution1.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
src/problem38/Solution1.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: string countAndSay(int n) { int curr = 1; string curr_str = "1"; while (curr < n) { curr++; string newString; char curr_char = ' '; int count = 0; for (int i = 0; i < curr_str.size(); i++) { if (curr_str[i] == curr_char) { count++; } else { if (curr_char != ' ') { newString.push_back('1' + count - 1); newString.push_back(curr_char); } curr_char = curr_str[i]; count = 1; } } newString.push_back('1' + count - 1); newString.push_back(curr_char); curr_str = newString; } return curr_str; } };
29
61
0.385057
MyYaYa
0592b8544d8f02b6d232bbf9bdfc1fc0afe312a1
2,041
cc
C++
cc/xlsx-read-test.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/xlsx-read-test.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/xlsx-read-test.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
#include "acmacs-base/argv.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/range-v3.hh" #include "acmacs-whocc/xlsx.hh" #include "acmacs-whocc/log.hh" // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of enablers"}}; argument<str_array> xlsx{*this, arg_name{".xlsx"}, mandatory}; }; int main(int argc, char* const argv[]) { using namespace std::string_view_literals; using namespace acmacs; int exit_code = 0; try { Options opt(argc, argv); acmacs::log::enable(opt.verbose); for (const auto& filename : *opt.xlsx) { AD_INFO("{}", filename); auto doc = acmacs::xlsx::open(filename); // AD_INFO("{} sheets: {}", filename, doc.number_of_sheets()); for (const auto sheet_no : range_from_0_to(doc.number_of_sheets())) { auto sheet = doc.sheet(sheet_no); AD_INFO(" {}: \"{}\" {}-{}", sheet_no + 1, sheet->name(), sheet->number_of_rows(), sheet->number_of_columns()); for (acmacs::sheet::nrow_t row{0}; row < sheet->number_of_rows(); ++row) { for (acmacs::sheet::ncol_t col{0}; col < sheet->number_of_columns(); ++col) { const auto cell = fmt::format("{}", sheet->cell(row, col)); AD_LOG(acmacs::log::xlsx, "cell {}{}: \"{}\"", row, col, cell); } } } } } catch (std::exception& err) { AD_ERROR("{}", err); exit_code = 2; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
36.446429
130
0.525723
acorg
0596f5a5ae5747e7f4e34985b2f2ce685bbb3b5b
5,901
cpp
C++
kernel/net/E1000ENetworkAdapter.cpp
elango/pranaOS
1017aff798c04c5811befdaca2afdbd7fefed09a
[ "BSD-2-Clause" ]
null
null
null
kernel/net/E1000ENetworkAdapter.cpp
elango/pranaOS
1017aff798c04c5811befdaca2afdbd7fefed09a
[ "BSD-2-Clause" ]
null
null
null
kernel/net/E1000ENetworkAdapter.cpp
elango/pranaOS
1017aff798c04c5811befdaca2afdbd7fefed09a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, Krisna Pranav * * SPDX-License-Identifier: BSD-2-Clause */ // includes #include <base/MACAddress.h> #include <kernel/bus/PCI/IDs.h> #include <kernel/net/E1000ENetworkAdapter.h> #include <kernel/Sections.h> namespace Kernel { #define REG_EEPROM 0x0014 static bool is_valid_device_id(u16 device_id) { switch (device_id) { case 0x10D3: return true; case 0x1000: case 0x0438: case 0x043A: case 0x043C: case 0x0440: case 0x1001: case 0x1004: case 0x1008: case 0x1009: case 0x100C: case 0x100D: case 0x100E: case 0x100F: case 0x1010: case 0x1011: case 0x1012: case 0x1013: case 0x1014: case 0x1015: case 0x1016: case 0x1017: case 0x1018: case 0x1019: case 0x101A: case 0x101D: case 0x101E: case 0x1026: case 0x1027: case 0x1028: case 0x1049: case 0x104A: case 0x104B: case 0x104C: case 0x104D: case 0x105E: case 0x105F: case 0x1060: case 0x1075: case 0x1076: case 0x1077: case 0x1078: case 0x1079: case 0x107A: case 0x107B: case 0x107C: case 0x107D: case 0x107E: case 0x107F: case 0x108A: case 0x108B: case 0x108C: case 0x1096: case 0x1098: case 0x1099: case 0x109A: case 0x10A4: case 0x10A5: case 0x10A7: case 0x10A9: case 0x10B5: case 0x10B9: case 0x10BA: case 0x10BB: case 0x10BC: case 0x10BD: case 0x10BF: case 0x10C0: case 0x10C2: case 0x10C3: case 0x10C4: case 0x10C5: case 0x10C9: case 0x10CA: case 0x10CB: case 0x10CC: case 0x10CD: case 0x10CE: case 0x10D5: case 0x10D6: case 0x10D9: case 0x10DA: case 0x10DE: case 0x10DF: case 0x10E5: case 0x10E6: case 0x10E7: case 0x10E8: case 0x10EA: case 0x10EB: case 0x10EF: case 0x10F0: case 0x10F5: case 0x10F6: case 0x1501: case 0x1502: case 0x1503: case 0x150A: case 0x150C: case 0x150D: case 0x150E: case 0x150F: case 0x1510: case 0x1511: case 0x1516: case 0x1518: case 0x1520: case 0x1521: case 0x1522: case 0x1523: case 0x1524: case 0x1525: case 0x1526: case 0x1527: case 0x152D: case 0x152F: case 0x1533: case 0x1534: case 0x1535: case 0x1536: case 0x1537: case 0x1538: case 0x1539: case 0x153A: case 0x153B: case 0x1546: case 0x1559: case 0x155A: case 0x156F: case 0x1570: case 0x157B: case 0x157C: case 0x15A0: case 0x15A1: case 0x15A2: case 0x15A3: case 0x15B7: case 0x15B8: case 0x15B9: case 0x15BB: case 0x15BC: case 0x15BD: case 0x15BE: case 0x15D6: case 0x15D7: case 0x15D8: case 0x15DF: case 0x15E0: case 0x15E1: case 0x15E2: case 0x15E3: case 0x1F40: case 0x1F41: case 0x1F45: case 0x294C: return false; default: return false; } } UNMAP_AFTER_INIT RefPtr<E1000ENetworkAdapter> E1000ENetworkAdapter::try_to_initialize(PCI::Address address) { auto id = PCI::get_id(address); if (id.vendor_id != PCI::VendorID::Intel) return {}; if (!is_valid_device_id(id.device_id)) return {}; u8 irq = PCI::get_interrupt_line(address); auto adapter = adopt_ref_if_nonnull(new (nothrow) E1000ENetworkAdapter(address, irq)); if (!adapter) return {}; if (adapter->initialize()) return adapter; return {}; } UNMAP_AFTER_INIT bool E1000ENetworkAdapter::initialize() { dmesgln("E1000e: Found @ {}", pci_address()); m_io_base = IOAddress(PCI::get_BAR2(pci_address()) & ~1); enable_bus_mastering(pci_address()); size_t mmio_base_size = PCI::get_BAR_space_size(pci_address(), 0); m_mmio_region = MM.allocate_kernel_region(PhysicalAddress(page_base_of(PCI::get_BAR0(pci_address()))), page_round_up(mmio_base_size), "E1000e MMIO", Region::Access::Read | Region::Access::Write, Region::Cacheable::No); if (!m_mmio_region) return false; m_mmio_base = m_mmio_region->vaddr(); m_use_mmio = true; m_interrupt_line = PCI::get_interrupt_line(pci_address()); dmesgln("E1000e: port base: {}", m_io_base); dmesgln("E1000e: MMIO base: {}", PhysicalAddress(PCI::get_BAR0(pci_address()) & 0xfffffffc)); dmesgln("E1000e: MMIO base size: {} bytes", mmio_base_size); dmesgln("E1000e: Interrupt line: {}", m_interrupt_line); detect_eeprom(); dmesgln("E1000e: Has EEPROM? {}", m_has_eeprom); read_mac_address(); const auto& mac = mac_address(); dmesgln("E1000e: MAC address: {}", mac.to_string()); initialize_rx_descriptors(); initialize_tx_descriptors(); setup_link(); setup_interrupts(); return true; } UNMAP_AFTER_INIT E1000ENetworkAdapter::E1000ENetworkAdapter(PCI::Address address, u8 irq) : E1000NetworkAdapter(address, irq) { } UNMAP_AFTER_INIT E1000ENetworkAdapter::~E1000ENetworkAdapter() { } UNMAP_AFTER_INIT void E1000ENetworkAdapter::detect_eeprom() { m_has_eeprom = true; } UNMAP_AFTER_INIT u32 E1000ENetworkAdapter::read_eeprom(u8 address) { VERIFY(m_has_eeprom); u16 data = 0; u32 tmp = 0; if (m_has_eeprom) { out32(REG_EEPROM, ((u32)address << 2) | 1); while (!((tmp = in32(REG_EEPROM)) & (1 << 1))) ; } else { out32(REG_EEPROM, ((u32)address << 2) | 1); while (!((tmp = in32(REG_EEPROM)) & (1 << 1))) ; } data = (tmp >> 16) & 0xffff; return data; } }
22.437262
222
0.601762
elango
059f420b9459540b73fe39df0c7c74a82b5141d6
9,325
hpp
C++
include/rovio/RovioInterfaceImpl.hpp
krzacz0r/maplab_rovio
1c881862bdfd5096d7c8ad268218020187bd6bc4
[ "BSD-3-Clause" ]
40
2017-11-29T08:46:10.000Z
2021-11-12T05:46:04.000Z
include/rovio/RovioInterfaceImpl.hpp
krzacz0r/maplab_rovio
1c881862bdfd5096d7c8ad268218020187bd6bc4
[ "BSD-3-Clause" ]
5
2018-01-08T17:02:15.000Z
2019-04-01T18:29:01.000Z
include/rovio/RovioInterfaceImpl.hpp
krzacz0r/maplab_rovio
1c881862bdfd5096d7c8ad268218020187bd6bc4
[ "BSD-3-Clause" ]
26
2017-12-03T02:22:47.000Z
2022-01-17T05:39:46.000Z
/* * Copyright (c) 2014, Autonomous Systems Lab * 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 Autonomous Systems Lab, ETH Zurich 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. * */ #ifndef ROVIO_ROVIO_INTERFACE_IMPL_H_ #define ROVIO_ROVIO_INTERFACE_IMPL_H_ #include <functional> #include <memory> #include <mutex> #include <queue> #include <glog/logging.h> #include "rovio/CameraCalibration.hpp" #include "rovio/CoordinateTransform/FeatureOutput.hpp" #include "rovio/CoordinateTransform/FeatureOutputReadable.hpp" #include "rovio/CoordinateTransform/LandmarkOutput.hpp" #include "rovio/CoordinateTransform/RovioOutput.hpp" #include "rovio/CoordinateTransform/YprOutput.hpp" #include "rovio/FilterConfiguration.hpp" #include "rovio/Memory.hpp" #include "rovio/RovioFilter.hpp" #include "RovioInterfaceStatesImpl.hpp" #include "rovio/RovioInterface.hpp" namespace rovio { struct FilterInitializationState; template <typename FILTER> class RovioInterfaceImpl : public RovioInterface { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW RovioInterfaceImpl(typename std::shared_ptr<FILTER> mpFilter); explicit RovioInterfaceImpl(const std::string &filter_config_file); RovioInterfaceImpl( const std::string &filter_config_file, const std::vector<std::string>& camera_calibration_files); explicit RovioInterfaceImpl(const FilterConfiguration &filter_config); RovioInterfaceImpl( const FilterConfiguration &filter_config, const CameraCalibrationVector& camera_calibrations); virtual ~RovioInterfaceImpl() {} typedef FILTER mtFilter; typedef typename mtFilter::mtFilterState mtFilterState; typedef typename mtFilterState::mtState mtState; /** \brief Outputting the feature and patch update state involves allocating * some large arrays and could result in some overhead. Therefore the * state will not be retrieved by default. */ bool getState(const bool get_feature_update, const bool get_patch_update, RovioState* filter_update); bool getState(RovioState* filter_update); /** \brief Returns the time step of the last/latest safe filter state.. */ double getLastSafeTime(); /** \brief Reset the filter when the next IMU measurement is received. * The orientaetion is initialized using an accel. measurement. */ void requestReset(); /** \brief Reset the filter when the next IMU measurement is received. * The pose is initialized to the passed pose. * @param WrWM - Position Vector, pointing from the World-Frame to the * IMU-Frame, expressed in World-Coordinates. * @param qMW - Quaternion, expressing World-Frame in IMU-Coordinates (World * Coordinates->IMU Coordinates) */ void requestResetToPose(const V3D &WrWM, const QPD &qMW); void resetToLastSafePose(); bool processVelocityUpdate(const Eigen::Vector3d &AvM, const double time_s); bool processImuUpdate(const Eigen::Vector3d &acc, const Eigen::Vector3d &gyr, const double time_s, bool update_filter); bool processImageUpdate(const int camID, const cv::Mat &cv_img, const double time_s); bool processGroundTruthUpdate(const Eigen::Vector3d &JrJV, const QPD &qJV, const double time_s); bool processGroundTruthOdometryUpdate( const Eigen::Vector3d &JrJV, const QPD &qJV, const Eigen::Matrix<double, 6, 6> &measuredCov, const double time_s); bool processLocalizationLandmarkUpdates( const int camID, const Eigen::Matrix2Xd& keypoint_observations, const Eigen::Matrix3Xd& G_landmarks, const double time_s); void resetLocalizationMapBaseframeAndCovariance( const V3D& WrWG, const QPD& qWG, double position_cov, double rotation_cov); /** \brief Register multiple callbacks that are invoked once the filter * concludes a successful update. */ typedef std::function<void(const RovioState&)> RovioStateCallback; void registerStateUpdateCallback(RovioStateCallback callback); /** \brief Enable and disable feature and patch update output. If disabled, * the RovioStateImpl<FILTER> returned by the callback does not contain * any state information of the features/patches. */ void setEnableFeatureUpdateOutput(const bool enable_feature_update); void setEnablePatchUpdateOutput(const bool get_patch_update); bool isInitialized() const; /** \brief Tests the functionality of the rovio node. * * @todo debug with doVECalibration = false and depthType = 0 */ void makeTest(); private: /** \brief Trigger a filter update. Will return true if an update happened. */ bool updateFilter(); void notifyAllStateUpdateCallbacks(const RovioState& state) const; /** \brief Print update to std::cout and visualize images using opencv. The * visualization is configured and enabled/disabled based on mpImgUpdate. */ void visualizeUpdate(); std::vector<RovioStateCallback> filter_update_state_callbacks_; typedef StandardOutput mtOutput; // TODO(mfehr): Ownership of the filter does not need to be shared, consider // changing to unique ptr or raw ptr if someone outside the interface can own // the filter. std::shared_ptr<mtFilter> mpFilter_; typedef typename mtFilter::mtPrediction::mtMeas mtPredictionMeas; mtPredictionMeas predictionMeas_; typedef typename std::tuple_element<0, typename mtFilter::mtUpdates>::type mtImgUpdate; mtImgUpdate *mpImgUpdate_; typedef typename std::tuple_element<1, typename mtFilter::mtUpdates>::type mtPoseUpdate; mtPoseUpdate *mpPoseUpdate_; typedef typename std::tuple_element<3, typename mtFilter::mtUpdates>::type mtLocLandmarkUpdate; mtLocLandmarkUpdate *mpLocLandmarkUpdate_; typedef typename mtImgUpdate::mtMeas mtImgMeas; mtImgMeas imgUpdateMeas_; typedef typename mtPoseUpdate::mtMeas mtPoseMeas; mtPoseMeas poseUpdateMeas_; typedef typename mtLocLandmarkUpdate::mtMeas mtLocLandmarkMeas; mtLocLandmarkMeas locLandmarkUpdateMeas_; typedef typename std::tuple_element<2, typename mtFilter::mtUpdates>::type mtVelocityUpdate; typedef typename mtVelocityUpdate::mtMeas mtVelocityMeas; mtVelocityMeas velocityUpdateMeas_; struct FilterInitializationState { FilterInitializationState() : WrWM_(V3D::Zero()), state_(State::WaitForInitUsingAccel) {} enum class State { // Initialize the filter using accelerometer measurement on the next // opportunity. WaitForInitUsingAccel, // Initialize the filter using an external pose on the next opportunity. WaitForInitExternalPose, // The filter is initialized. Initialized } state_; // Buffer to hold the initial pose that should be set during initialization // with the state WaitForInitExternalPose. V3D WrWM_; QPD qMW_; explicit operator bool() const { return isInitialized(); } bool isInitialized() const { return (state_ == State::Initialized); } }; FilterInitializationState init_state_; // Rovio outputs and coordinate transformations Eigen::MatrixXd cameraOutputCov_; CameraOutputCT<mtState> cameraOutputCT_; ImuOutputCT<mtState> imuOutputCT_; rovio::TransformFeatureOutputCT<mtState> transformFeatureOutputCT_; rovio::LandmarkOutputImuCT<mtState> landmarkOutputImuCT_; // Features. rovio::FeatureOutput featureOutput_; rovio::FeatureOutputReadable featureOutputReadable_; rovio::FeatureOutputReadableCT featureOutputReadableCT_; Eigen::MatrixXd featureOutputCov_; Eigen::MatrixXd featureOutputReadableCov_; // Landmarks. rovio::LandmarkOutput landmarkOutput_; Eigen::MatrixXd landmarkOutputCov_; // State output config. bool enable_feature_update_output_; bool enable_patch_update_output_; mutable std::recursive_mutex m_filter_; }; } // namespace rovio #endif // ROVIO_ROVIO_INTERFACE_IMPL_H_ #include "RovioInterfaceImplInl.hpp"
36.425781
81
0.760536
krzacz0r
05a180599890366b7d731e58dd437a17ed2f82eb
22,776
cpp
C++
tests/HttpHandlerTest.cpp
acossette/pillow
89259eb4540d27551470de0d80363a37ba3eda7d
[ "Zed", "Ruby" ]
39
2015-01-28T12:51:41.000Z
2021-09-25T16:27:09.000Z
tests/HttpHandlerTest.cpp
acossette/pillow
89259eb4540d27551470de0d80363a37ba3eda7d
[ "Zed", "Ruby" ]
1
2016-01-21T00:10:25.000Z
2016-01-21T00:29:40.000Z
tests/HttpHandlerTest.cpp
acossette/pillow
89259eb4540d27551470de0d80363a37ba3eda7d
[ "Zed", "Ruby" ]
22
2015-08-07T23:28:27.000Z
2020-07-13T08:12:22.000Z
#include <QtTest/QTest> #include <QtTest/QSignalSpy> #include "HttpHandlerTest.h" #include "HttpHandler.h" #include "HttpHandlerSimpleRouter.h" #include "HttpConnection.h" #include <QtCore/QDir> #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> using namespace Pillow; Pillow::HttpConnection * HttpHandlerTestBase::createGetRequest(const QByteArray &path, const QByteArray& httpVersion) { return createRequest("GET", path, QByteArray(), httpVersion); } Pillow::HttpConnection * HttpHandlerTestBase::createPostRequest(const QByteArray &path, const QByteArray &content, const QByteArray &httpVersion) { return createRequest("POST", path, content, httpVersion); } Pillow::HttpConnection * HttpHandlerTestBase::createRequest(const QByteArray &method, const QByteArray &path, const QByteArray &content, const QByteArray &httpVersion) { QByteArray data = QByteArray().append(method).append(" ").append(path).append(" HTTP/").append(httpVersion).append("\r\n"); if (content.size() > 0) { data.append("Content-Length: ").append(QByteArray::number(content.size())).append("\r\n"); data.append("Content-Type: text/plain\r\n"); } data.append("\r\n").append(content); QBuffer* inputBuffer = new QBuffer(); inputBuffer->open(QIODevice::ReadWrite); QBuffer* outputBuffer = new QBuffer(); outputBuffer->open(QIODevice::ReadWrite); connect(outputBuffer, SIGNAL(bytesWritten(qint64)), this, SLOT(outputBuffer_bytesWritten())); Pillow::HttpConnection* connection = new Pillow::HttpConnection(this); connect(connection, SIGNAL(requestCompleted(Pillow::HttpConnection*)), this, SLOT(requestCompleted(Pillow::HttpConnection*))); connection->initialize(inputBuffer, outputBuffer); inputBuffer->setParent(connection); outputBuffer->setParent(connection); inputBuffer->write(data); inputBuffer->seek(0); while (connection->state() != Pillow::HttpConnection::SendingHeaders) QCoreApplication::processEvents(); return connection; } void HttpHandlerTestBase::requestCompleted(Pillow::HttpConnection* connection) { QCoreApplication::processEvents(); response = responseBuffer; responseBuffer = QByteArray(); requestParams = connection->requestParams(); } void HttpHandlerTestBase::outputBuffer_bytesWritten() { QBuffer* buffer = static_cast<QBuffer*>(sender()); responseBuffer.append(buffer->data()); if (buffer->isOpen()) buffer->seek(0); } class MockHandler : public Pillow::HttpHandler { public: MockHandler(const QByteArray& acceptPath, int statusCode, QObject* parent) : Pillow::HttpHandler(parent), acceptPath(acceptPath), statusCode(statusCode), handleRequestCount(0) {} QByteArray acceptPath; int statusCode; int handleRequestCount; bool handleRequest(Pillow::HttpConnection *connection) { ++handleRequestCount; if (acceptPath == connection->requestPath()) { connection->writeResponse(statusCode); return true; } return false; } }; void HttpHandlerTest::testHandlerStack() { HttpHandlerStack handler; MockHandler* mock1 = new MockHandler("/1", 200, &handler); MockHandler* mock1_1 = new MockHandler("/", 403, mock1); new QObject(&handler); // Some dummy object, also child of handler. MockHandler* mock2 = new MockHandler("/2", 302, &handler); MockHandler* mock3 = new MockHandler("/", 500, &handler); MockHandler* mock4 = new MockHandler("/", 200, &handler); bool handled = handler.handleRequest(createGetRequest("/")); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 500")); QCOMPARE(mock1->handleRequestCount, 1); QCOMPARE(mock1_1->handleRequestCount, 0); QCOMPARE(mock2->handleRequestCount, 1); QCOMPARE(mock3->handleRequestCount, 1); QCOMPARE(mock4->handleRequestCount, 0); handled = handler.handleRequest(createGetRequest("/2")); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 302")); QCOMPARE(mock1->handleRequestCount, 2); QCOMPARE(mock1_1->handleRequestCount, 0); QCOMPARE(mock2->handleRequestCount, 2); QCOMPARE(mock3->handleRequestCount, 1); QCOMPARE(mock4->handleRequestCount, 0); } void HttpHandlerTest::testHandlerFixed() { bool handled = HttpHandlerFixed(403, "Fixed test").handleRequest(createGetRequest()); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 403")); QVERIFY(response.endsWith("\r\n\r\nFixed test")); } void HttpHandlerTest::testHandler404() { bool handled = HttpHandler404().handleRequest(createGetRequest("/some_path")); QVERIFY(handled); QVERIFY(response.startsWith("HTTP/1.0 404")); QVERIFY(response.contains("/some_path")); } void HttpHandlerTest::testHandlerFunction() { #ifdef Q_COMPILER_LAMBDA HttpHandlerFunction handler([](Pillow::HttpConnection* request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "hello from lambda"); }); QVERIFY(handler.handleRequest(createGetRequest("/some/random/path"))); QVERIFY(response.startsWith("HTTP/1.0 200 OK")); QVERIFY(response.endsWith("hello from lambda")); #else QSKIP("Compiler does not support lambdas or C++0x support is not enabled.", SkipSingle); #endif } void HttpHandlerTest::testHandlerLog() { QBuffer buffer; buffer.open(QIODevice::ReadWrite); Pillow::HttpConnection* request1 = createGetRequest("/first"); Pillow::HttpConnection* request2 = createGetRequest("/second"); Pillow::HttpConnection* request3 = createGetRequest("/third"); HttpHandlerLog handler(&buffer, &buffer); QVERIFY(!handler.handleRequest(request1)); QVERIFY(!handler.handleRequest(request2)); QVERIFY(!handler.handleRequest(request3)); QVERIFY(buffer.data().isEmpty()); request3->writeResponse(302); request1->writeResponse(200); request2->writeResponse(500); // The log handler should write the log entries as they are completed. buffer.seek(0); QVERIFY(buffer.readLine().contains("GET /third")); QVERIFY(buffer.readLine().contains("GET /first")); QVERIFY(buffer.readLine().contains("GET /second")); QVERIFY(buffer.readLine().isEmpty()); } void HttpHandlerTest::testHandlerLogTrace() { QBuffer buffer; buffer.open(QIODevice::ReadWrite); Pillow::HttpConnection* request1 = createGetRequest("/first", "1.1"); Pillow::HttpConnection* request2 = createGetRequest("/second", "1.1"); Pillow::HttpConnection* request3 = createGetRequest("/third", "1.1"); HttpHandlerLog handler(&buffer, &buffer); handler.setMode(HttpHandlerLog::TraceRequests); QVERIFY(!handler.handleRequest(request1)); QVERIFY(!buffer.data().isEmpty()); QVERIFY(buffer.data().contains("[BEGIN]")); QVERIFY(!buffer.data().contains("[ END ]")); QVERIFY(!handler.handleRequest(request2)); QVERIFY(!handler.handleRequest(request3)); request3->writeResponse(302); QVERIFY(buffer.data().contains("[ END ]")); request1->writeResponse(200); request2->writeResponse(500); QVERIFY(!buffer.data().contains("[CLOSE]")); request1->close(); QVERIFY(buffer.data().contains("[CLOSE]")); buffer.seek(0); QVERIFY(buffer.readLine().contains("GET /first")); QVERIFY(buffer.readLine().contains("GET /second")); QVERIFY(buffer.readLine().contains("GET /third")); QVERIFY(buffer.readLine().contains("GET /third")); // END QVERIFY(buffer.readLine().contains("GET /first")); // END QVERIFY(buffer.readLine().contains("GET /second")); // END QVERIFY(buffer.readLine().contains("GET /first")); // CLOSE QVERIFY(buffer.readLine().isEmpty()); } void HttpHandlerFileTest::initTestCase() { testPath = QDir::tempPath() + "/HttpHandlerFileTest"; QDir(testPath).mkpath("."); QVERIFY(QFile::exists(testPath)); QByteArray bigData(16 * 1024 * 1024, '-'); { QFile f(testPath + "/first"); f.open(QIODevice::WriteOnly); f.write("first content"); f.flush(); f.close(); } { QFile f(testPath + "/second"); f.open(QIODevice::WriteOnly); f.write("second content"); f.flush(); f.close(); } { QFile f(testPath + "/large"); f.open(QIODevice::WriteOnly); f.write(bigData); f.flush(); f.close(); } { QFile f(testPath + "/first"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), QByteArray("first content")); } { QFile f(testPath + "/second"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), QByteArray("second content")); } { QFile f(testPath + "/large"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), bigData); } } void HttpHandlerFileTest::testServesFiles() { HttpHandlerFile handler(testPath); QVERIFY(!handler.handleRequest(createGetRequest("/"))); QVERIFY(!handler.handleRequest(createGetRequest("/bad_path"))); QVERIFY(!handler.handleRequest(createGetRequest("/another_bad"))); Pillow::HttpConnection* request = createGetRequest("/first"); QVERIFY(handler.handleRequest(request)); QVERIFY(response.startsWith("HTTP/1.0 200 OK")); QVERIFY(response.endsWith("first content")); response.clear(); // Note: the large files test currently fails when the output device is a QBuffer. request = createGetRequest("/large"); QVERIFY(handler.handleRequest(request)); while (response.isEmpty()) QCoreApplication::processEvents(); QVERIFY(response.size() > 16 * 1024 * 1024); QVERIFY(response.startsWith("HTTP/1.0 200 OK")); QVERIFY(response.endsWith(QByteArray(16 * 1024 * 1024, '-'))); } void HttpHandlerSimpleRouterTest::testHandlerRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/some_path", new HttpHandlerFixed(303, "Hello")); handler.addRoute("/other/path", new HttpHandlerFixed(404, "World")); handler.addRoute("/some_path/even/deeper", new HttpHandlerFixed(200, "!")); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/some_path/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/other/path"))); QVERIFY(response.startsWith("HTTP/1.0 404")); QVERIFY(response.endsWith("World")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/some_path/even/deeper?with=query_string"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("!")); response.clear(); } void HttpHandlerSimpleRouterTest::testQObjectMetaCallRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/first", this, "handleRequest1"); handler.addRoute("/first/second", this, "handleRequest2"); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/second/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/first"))); QVERIFY(response.startsWith("HTTP/1.0 403")); QVERIFY(response.endsWith("Hello")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/first/second?with=query_string"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("World")); response.clear(); } void HttpHandlerSimpleRouterTest::testQObjectSlotCallRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/route", this, SLOT(handleRequest2(Pillow::HttpConnection*))); QVERIFY(handler.handleRequest(createGetRequest("/route"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("World")); response.clear(); } void HttpHandlerSimpleRouterTest::testStaticRoute() { HttpHandlerSimpleRouter handler; handler.addRoute("/first", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("/first/second", 404, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("/third", 500, Pillow::HttpHeaderCollection(), "Third Route"); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/first/second/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/first"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/third?with=query_string#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 500")); QVERIFY(response.endsWith("Third Route")); response.clear(); } void HttpHandlerSimpleRouterTest::testFuncRoute() { #ifdef Q_COMPILER_LAMBDA HttpHandlerSimpleRouter handler; handler.addRoute("/a_route", [](Pillow::HttpConnection* request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "Amazing First Route"); }); handler.addRoute("/a_route/and_another", [](Pillow::HttpConnection* request) { request->writeResponse(400, Pillow::HttpHeaderCollection(), "Delicious Second Route"); }); QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either"))); QVERIFY(!handler.handleRequest(createGetRequest("/a_route/should_not_match"))); QVERIFY(!handler.handleRequest(createGetRequest("/a_route/and_another/should_not_match"))); QVERIFY(handler.handleRequest(createGetRequest("/a_route"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Amazing First Route")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/a_route/and_another?with=query_string#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 400")); QVERIFY(response.endsWith("Delicious Second Route")); response.clear(); #else QSKIP("Compiler does not support lambdas or C++0x support is not enabled.", SkipSingle); #endif } void HttpHandlerSimpleRouterTest::handleRequest1(Pillow::HttpConnection *request) { request->writeResponse(403, Pillow::HttpHeaderCollection(), "Hello"); } void HttpHandlerSimpleRouterTest::handleRequest2(Pillow::HttpConnection *request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "World"); } void HttpHandlerSimpleRouterTest::testPathParams() { HttpHandlerSimpleRouter handler; handler.addRoute("/first/:with_param", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("/second/:with_param/and/:another", 200, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("/third/:with/:many/:params", 200, Pillow::HttpHeaderCollection(), "Third Route"); QVERIFY(handler.handleRequest(createGetRequest("/first/some_param-value"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); QCOMPARE(requestParams.size(), 1); QCOMPARE(requestParams.at(0).first, QString("with_param")); QCOMPARE(requestParams.at(0).second, QString("some_param-value")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/second/some_param-value/and/another_value"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Second Route")); QCOMPARE(requestParams.size(), 2); QCOMPARE(requestParams.at(0).first, QString("with_param")); QCOMPARE(requestParams.at(0).second, QString("some_param-value")); QCOMPARE(requestParams.at(1).first, QString("another")); QCOMPARE(requestParams.at(1).second, QString("another_value")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/third/some_param-value/another_value/and_a_last_one?with=overriden&extra=bonus_query_param#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route")); QCOMPARE(requestParams.size(), 4); QCOMPARE(requestParams.at(0).first, QString("with")); QCOMPARE(requestParams.at(0).second, QString("some_param-value")); // The route param should have overriden the query string param. QCOMPARE(requestParams.at(1).first, QString("extra")); QCOMPARE(requestParams.at(1).second, QString("bonus_query_param")); QCOMPARE(requestParams.at(2).first, QString("many")); QCOMPARE(requestParams.at(2).second, QString("another_value")); QCOMPARE(requestParams.at(3).first, QString("params")); QCOMPARE(requestParams.at(3).second, QString("and_a_last_one")); response.clear(); QVERIFY(!handler.handleRequest(createGetRequest("/first/some_param-value/and_extra_stuff"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/bad_part/another_value"))); QVERIFY(!handler.handleRequest(createGetRequest("/third/some_param-value/another_value/and_a_last_one/and_extra_stuff"))); } void HttpHandlerSimpleRouterTest::testPathSplats() { HttpHandlerSimpleRouter handler; handler.addRoute("/first/*with_splat", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("/second/:with_param/and/*splat", 200, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("/third/*with/two/*splats", 200, Pillow::HttpHeaderCollection(), "Third Route"); QVERIFY(handler.handleRequest(createGetRequest("/first/"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); QCOMPARE(requestParams.size(), 1); QCOMPARE(requestParams.at(0).first, QString("with_splat")); QCOMPARE(requestParams.at(0).second, QString("")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/first/with/anything-after.that/really_I_tell_you.html"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("First Route")); QCOMPARE(requestParams.size(), 1); QCOMPARE(requestParams.at(0).first, QString("with_splat")); QCOMPARE(requestParams.at(0).second, QString("with/anything-after.that/really_I_tell_you.html")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/second/some-param-value/and/"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Second Route")); QCOMPARE(requestParams.size(), 2); QCOMPARE(requestParams.at(0).first, QString("with_param")); QCOMPARE(requestParams.at(0).second, QString("some-param-value")); QCOMPARE(requestParams.at(1).first, QString("splat")); QCOMPARE(requestParams.at(1).second, QString("")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/second/some-param-value/and/extra/stuff/splatted.at/the.end?with=bonus_query_param#and_fragment"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Second Route")); QCOMPARE(requestParams.size(), 3); QCOMPARE(requestParams.at(0).first, QString("with")); QCOMPARE(requestParams.at(0).second, QString("bonus_query_param")); QCOMPARE(requestParams.at(1).first, QString("with_param")); QCOMPARE(requestParams.at(1).second, QString("some-param-value")); QCOMPARE(requestParams.at(2).first, QString("splat")); QCOMPARE(requestParams.at(2).second, QString("extra/stuff/splatted.at/the.end")); response.clear(); QVERIFY(handler.handleRequest(createGetRequest("/third/some/path/two/and/another/path%20with%20spaces.txt"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route")); QCOMPARE(requestParams.size(), 2); QCOMPARE(requestParams.at(0).first, QString("with")); QCOMPARE(requestParams.at(0).second, QString("some/path")); QCOMPARE(requestParams.at(1).first, QString("splats")); QCOMPARE(requestParams.at(1).second, QString("and/another/path with spaces.txt")); response.clear(); QVERIFY(!handler.handleRequest(createGetRequest("/first"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/and"))); QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/bad_part/splat/splat/splat"))); } void HttpHandlerSimpleRouterTest::testMatchesMethod() { HttpHandlerSimpleRouter handler; handler.addRoute("GET", "/get", 200, Pillow::HttpHeaderCollection(), "First Route"); handler.addRoute("POST", "/post", 200, Pillow::HttpHeaderCollection(), "Second Route"); handler.addRoute("GET", "/both", 200, Pillow::HttpHeaderCollection(), "Third Route (GET)"); handler.addRoute("POST", "/both", 200, Pillow::HttpHeaderCollection(), "Third Route (POST)"); QVERIFY(handler.handleRequest(createGetRequest("/get"))); QVERIFY(!handler.handleRequest(createPostRequest("/get"))); QVERIFY(!handler.handleRequest(createGetRequest("/post"))); QVERIFY(handler.handleRequest(createPostRequest("/post"))); QVERIFY(handler.handleRequest(createGetRequest("/both"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route (GET)")); response.clear(); QVERIFY(handler.handleRequest(createPostRequest("/both"))); QVERIFY(response.startsWith("HTTP/1.0 200")); QVERIFY(response.endsWith("Third Route (POST)")); response.clear(); } void HttpHandlerSimpleRouterTest::testUnmatchedRequestAction() { HttpHandlerSimpleRouter handler; QVERIFY(handler.unmatchedRequestAction() == HttpHandlerSimpleRouter::Passthrough); handler.setUnmatchedRequestAction(HttpHandlerSimpleRouter::Return4xxResponse); handler.addRoute("GET", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (GET)"); handler.addRoute("DELETE", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (DELETE)"); QVERIFY(handler.handleRequest(createGetRequest("/unmatched/route"))); QVERIFY(response.startsWith("HTTP/1.0 404")); response.clear(); } void HttpHandlerSimpleRouterTest::testMethodMismatchAction() { HttpHandlerSimpleRouter handler; QVERIFY(handler.methodMismatchAction() == HttpHandlerSimpleRouter::Passthrough); handler.setMethodMismatchAction(HttpHandlerSimpleRouter::Return4xxResponse); handler.addRoute("GET", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (GET)"); handler.addRoute("DELETE", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (DELETE)"); QVERIFY(handler.handleRequest(createPostRequest("/a"))); QVERIFY(response.startsWith("HTTP/1.0 405")); QVERIFY(response.contains("Allow: GET, DELETE")); response.clear(); } void HttpHandlerSimpleRouterTest::testSupportsMethodParam() { HttpHandlerSimpleRouter handler; handler.addRoute("POST", "/a", 200, Pillow::HttpHeaderCollection(), "Route"); handler.addRoute("DELETE", "/b", 200, Pillow::HttpHeaderCollection(), "Route"); QVERIFY(handler.acceptsMethodParam() == false); QVERIFY(!handler.handleRequest(createGetRequest("/a"))); QVERIFY(handler.handleRequest(createPostRequest("/a"))); QVERIFY(!handler.handleRequest(createGetRequest("/a?_method=post"))); QVERIFY(!handler.handleRequest(createGetRequest("/b?_method=delete"))); QVERIFY(!handler.handleRequest(createPostRequest("/b?_method=delete"))); handler.setAcceptsMethodParam(true); QVERIFY(!handler.handleRequest(createGetRequest("/a"))); QVERIFY(handler.handleRequest(createPostRequest("/a"))); QVERIFY(handler.handleRequest(createGetRequest("/a?_method=POST"))); QVERIFY(handler.handleRequest(createGetRequest("/b?_method=DELETE"))); QVERIFY(handler.handleRequest(createPostRequest("/b?_method=DELETE"))); QVERIFY(handler.handleRequest(createGetRequest("/b?_method=delete"))); QVERIFY(handler.handleRequest(createPostRequest("/b?_method=delete"))); }
41.944751
170
0.757684
acossette
05a4793814cdf4b3c2dfa2d1c2559e5d161339e7
13,758
cpp
C++
libs/type_index/test/type_index_test.cpp
Abce/boost
2d7491a27211aa5defab113f8e2d657c3d85ca93
[ "BSL-1.0" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
libs/boost/libs/type_index/test/type_index_test.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/libs/type_index/test/type_index_test.cpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
// // Copyright Antony Polukhin, 2012-2014. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/test/minimal.hpp> #include <boost/type_index.hpp> #include <boost/functional/hash.hpp> #include <boost/lexical_cast.hpp> #define BOOST_CHECK_EQUAL(x, y) BOOST_CHECK(x == y) #define BOOST_CHECK_NE(x, y) BOOST_CHECK(x != y) #define BOOST_CHECK_LE(x, y) BOOST_CHECK(x <= y) #define BOOST_CHECK_GE(x, y) BOOST_CHECK(x >= y) namespace my_namespace1 { class my_class{}; } namespace my_namespace2 { class my_class{}; } void names_matches_type_id() { using namespace boost::typeindex; BOOST_CHECK_EQUAL(type_id<int>().pretty_name(), "int"); BOOST_CHECK_EQUAL(type_id<double>().pretty_name(), "double"); BOOST_CHECK_EQUAL(type_id<int>().name(), type_id<int>().name()); BOOST_CHECK_NE(type_id<int>().name(), type_id<double>().name()); BOOST_CHECK_NE(type_id<double>().name(), type_id<int>().name()); BOOST_CHECK_EQUAL(type_id<double>().name(), type_id<double>().name()); } void default_construction() { using namespace boost::typeindex; type_index ti1, ti2; BOOST_CHECK_EQUAL(ti1, ti2); BOOST_CHECK_EQUAL(type_id<void>(), ti1); BOOST_CHECK_EQUAL(type_id<void>().name(), ti1.name()); BOOST_CHECK_NE(type_id<int>(), ti1); } void copy_construction() { using namespace boost::typeindex; type_index ti1, ti2 = type_id<int>(); BOOST_CHECK_NE(ti1, ti2); ti1 = ti2; BOOST_CHECK_EQUAL(ti2, ti1); const type_index ti3(ti1); BOOST_CHECK_EQUAL(ti3, ti1); } void comparators_type_id() { using namespace boost::typeindex; type_index t_int = type_id<int>(); type_index t_double = type_id<double>(); BOOST_CHECK_EQUAL(t_int, t_int); BOOST_CHECK_LE(t_int, t_int); BOOST_CHECK_GE(t_int, t_int); BOOST_CHECK_NE(t_int, t_double); BOOST_CHECK_LE(t_double, t_double); BOOST_CHECK_GE(t_double, t_double); BOOST_CHECK_NE(t_double, t_int); BOOST_CHECK(t_double < t_int || t_int < t_double); BOOST_CHECK(t_double > t_int || t_int > t_double); } void hash_code_type_id() { using namespace boost::typeindex; std::size_t t_int1 = type_id<int>().hash_code(); std::size_t t_double1 = type_id<double>().hash_code(); std::size_t t_int2 = type_id<int>().hash_code(); std::size_t t_double2 = type_id<double>().hash_code(); BOOST_CHECK_EQUAL(t_int1, t_int2); BOOST_CHECK_NE(t_int1, t_double2); BOOST_CHECK_LE(t_double1, t_double2); } template <class T1, class T2> static void test_with_modofiers() { using namespace boost::typeindex; type_index t1 = type_id_with_cvr<T1>(); type_index t2 = type_id_with_cvr<T2>(); BOOST_CHECK_NE(t2, t1); BOOST_CHECK(t2 != t1.type_info()); BOOST_CHECK(t2.type_info() != t1); BOOST_CHECK(t1 < t2 || t2 < t1); BOOST_CHECK(t1 > t2 || t2 > t1); BOOST_CHECK(t1.type_info() < t2 || t2.type_info() < t1); BOOST_CHECK(t1.type_info() > t2 || t2.type_info() > t1); BOOST_CHECK(t1 < t2.type_info() || t2 < t1.type_info()); BOOST_CHECK(t1 > t2.type_info() || t2 > t1.type_info()); // Chaecking that comparison operators overloads compile BOOST_CHECK(t1 <= t2 || t2 <= t1); BOOST_CHECK(t1 >= t2 || t2 >= t1); BOOST_CHECK(t1.type_info() <= t2 || t2.type_info() <= t1); BOOST_CHECK(t1.type_info() >= t2 || t2.type_info() >= t1); BOOST_CHECK(t1 <= t2.type_info() || t2 <= t1.type_info()); BOOST_CHECK(t1 >= t2.type_info() || t2 >= t1.type_info()); BOOST_CHECK_EQUAL(t1, type_id_with_cvr<T1>()); BOOST_CHECK_EQUAL(t2, type_id_with_cvr<T2>()); BOOST_CHECK(t1 == type_id_with_cvr<T1>().type_info()); BOOST_CHECK(t2 == type_id_with_cvr<T2>().type_info()); BOOST_CHECK(t1.type_info() == type_id_with_cvr<T1>()); BOOST_CHECK(t2.type_info() == type_id_with_cvr<T2>()); BOOST_CHECK_EQUAL(t1.hash_code(), type_id_with_cvr<T1>().hash_code()); BOOST_CHECK_EQUAL(t2.hash_code(), type_id_with_cvr<T2>().hash_code()); BOOST_CHECK_NE(t1.hash_code(), type_id_with_cvr<T2>().hash_code()); BOOST_CHECK_NE(t2.hash_code(), type_id_with_cvr<T1>().hash_code()); } void type_id_storing_modifiers() { test_with_modofiers<int, const int>(); test_with_modofiers<int, const int&>(); test_with_modofiers<int, int&>(); test_with_modofiers<int, volatile int>(); test_with_modofiers<int, volatile int&>(); test_with_modofiers<int, const volatile int>(); test_with_modofiers<int, const volatile int&>(); test_with_modofiers<const int, int>(); test_with_modofiers<const int, const int&>(); test_with_modofiers<const int, int&>(); test_with_modofiers<const int, volatile int>(); test_with_modofiers<const int, volatile int&>(); test_with_modofiers<const int, const volatile int>(); test_with_modofiers<const int, const volatile int&>(); test_with_modofiers<const int&, int>(); test_with_modofiers<const int&, const int>(); test_with_modofiers<const int&, int&>(); test_with_modofiers<const int&, volatile int>(); test_with_modofiers<const int&, volatile int&>(); test_with_modofiers<const int&, const volatile int>(); test_with_modofiers<const int&, const volatile int&>(); test_with_modofiers<int&, const int>(); test_with_modofiers<int&, const int&>(); test_with_modofiers<int&, int>(); test_with_modofiers<int&, volatile int>(); test_with_modofiers<int&, volatile int&>(); test_with_modofiers<int&, const volatile int>(); test_with_modofiers<int&, const volatile int&>(); #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES test_with_modofiers<int&&, const int>(); test_with_modofiers<int&&, const int&>(); test_with_modofiers<int&&, const int&&>(); test_with_modofiers<int&&, int>(); test_with_modofiers<int&&, volatile int>(); test_with_modofiers<int&&, volatile int&>(); test_with_modofiers<int&&, volatile int&&>(); test_with_modofiers<int&&, const volatile int>(); test_with_modofiers<int&&, const volatile int&>(); test_with_modofiers<int&&, const volatile int&&>(); #endif } template <class T> static void test_storing_nonstoring_modifiers_templ() { using namespace boost::typeindex; type_index t1 = type_id_with_cvr<T>(); type_index t2 = type_id<T>(); BOOST_CHECK_EQUAL(t2, t1); BOOST_CHECK_EQUAL(t1, t2); BOOST_CHECK(t1 <= t2); BOOST_CHECK(t1 >= t2); BOOST_CHECK(t2 <= t1); BOOST_CHECK(t2 >= t1); BOOST_CHECK_EQUAL(t2.pretty_name(), t1.pretty_name()); } void type_id_storing_modifiers_vs_nonstoring() { test_storing_nonstoring_modifiers_templ<int>(); test_storing_nonstoring_modifiers_templ<my_namespace1::my_class>(); test_storing_nonstoring_modifiers_templ<my_namespace2::my_class>(); boost::typeindex::type_index t1 = boost::typeindex::type_id_with_cvr<const int>(); boost::typeindex::type_index t2 = boost::typeindex::type_id<int>(); BOOST_CHECK_NE(t2, t1); BOOST_CHECK(t1.pretty_name() == "const int" || t1.pretty_name() == "int const"); } void type_index_stream_operator_via_lexical_cast_testing() { using namespace boost::typeindex; std::string s_int2 = boost::lexical_cast<std::string>(type_id<int>()); BOOST_CHECK_EQUAL(s_int2, "int"); std::string s_double2 = boost::lexical_cast<std::string>(type_id<double>()); BOOST_CHECK_EQUAL(s_double2, "double"); } void type_index_stripping_cvr_test() { using namespace boost::typeindex; BOOST_CHECK_EQUAL(type_id<int>(), type_id<const int>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<const volatile int>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<const volatile int&>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<int&>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<volatile int>()); BOOST_CHECK_EQUAL(type_id<int>(), type_id<volatile int&>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<const double>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<const volatile double>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<const volatile double&>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<double&>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<volatile double>()); BOOST_CHECK_EQUAL(type_id<double>(), type_id<volatile double&>()); } void type_index_user_defined_class_test() { using namespace boost::typeindex; BOOST_CHECK_EQUAL(type_id<my_namespace1::my_class>(), type_id<my_namespace1::my_class>()); BOOST_CHECK_EQUAL(type_id<my_namespace2::my_class>(), type_id<my_namespace2::my_class>()); #ifndef BOOST_NO_RTTI BOOST_CHECK(type_id<my_namespace1::my_class>() == typeid(my_namespace1::my_class)); BOOST_CHECK(type_id<my_namespace2::my_class>() == typeid(my_namespace2::my_class)); BOOST_CHECK(typeid(my_namespace1::my_class) == type_id<my_namespace1::my_class>()); BOOST_CHECK(typeid(my_namespace2::my_class) == type_id<my_namespace2::my_class>()); #endif BOOST_CHECK_NE(type_id<my_namespace1::my_class>(), type_id<my_namespace2::my_class>()); BOOST_CHECK_NE( type_id<my_namespace1::my_class>().pretty_name().find("my_namespace1::my_class"), std::string::npos); } struct A { public: BOOST_TYPE_INDEX_REGISTER_CLASS virtual ~A(){} }; struct B: public A { BOOST_TYPE_INDEX_REGISTER_CLASS }; struct C: public B { BOOST_TYPE_INDEX_REGISTER_CLASS }; void comparators_type_id_runtime() { C c1; B b1; A* pc1 = &c1; A& rc1 = c1; A* pb1 = &b1; A& rb1 = b1; #ifndef BOOST_NO_RTTI BOOST_CHECK(typeid(rc1) == typeid(*pc1)); BOOST_CHECK(typeid(rb1) == typeid(*pb1)); BOOST_CHECK(typeid(rc1) != typeid(*pb1)); BOOST_CHECK(typeid(rb1) != typeid(*pc1)); BOOST_CHECK(typeid(&rc1) == typeid(pb1)); BOOST_CHECK(typeid(&rb1) == typeid(pc1)); #else BOOST_CHECK(boost::typeindex::type_index(pc1->boost_type_index_type_id_runtime_()).raw_name()); #endif BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(rc1), boost::typeindex::type_id_runtime(*pc1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id<C>(), boost::typeindex::type_id_runtime(*pc1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(rb1), boost::typeindex::type_id_runtime(*pb1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id<B>(), boost::typeindex::type_id_runtime(*pb1)); BOOST_CHECK_NE(boost::typeindex::type_id_runtime(rc1), boost::typeindex::type_id_runtime(*pb1)); BOOST_CHECK_NE(boost::typeindex::type_id_runtime(rb1), boost::typeindex::type_id_runtime(*pc1)); #ifndef BOOST_NO_RTTI BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(&rc1), boost::typeindex::type_id_runtime(pb1)); BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(&rb1), boost::typeindex::type_id_runtime(pc1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rc1) == typeid(*pc1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rb1) == typeid(*pb1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rc1) != typeid(*pb1)); BOOST_CHECK(boost::typeindex::type_id_runtime(rb1) != typeid(*pc1)); BOOST_CHECK(boost::typeindex::type_id_runtime(&rc1) == typeid(pb1)); BOOST_CHECK(boost::typeindex::type_id_runtime(&rb1) == typeid(pc1)); #endif } #ifndef BOOST_NO_RTTI void comparators_type_id_vs_type_info() { using namespace boost::typeindex; type_index t_int = type_id<int>(); BOOST_CHECK(t_int == typeid(int)); BOOST_CHECK(typeid(int) == t_int); BOOST_CHECK(t_int <= typeid(int)); BOOST_CHECK(typeid(int) <= t_int); BOOST_CHECK(t_int >= typeid(int)); BOOST_CHECK(typeid(int) >= t_int); type_index t_double = type_id<double>(); BOOST_CHECK(t_double == typeid(double)); BOOST_CHECK(typeid(double) == t_double); BOOST_CHECK(t_double <= typeid(double)); BOOST_CHECK(typeid(double) <= t_double); BOOST_CHECK(t_double >= typeid(double)); BOOST_CHECK(typeid(double) >= t_double); if (t_double < t_int) { BOOST_CHECK(t_double < typeid(int)); BOOST_CHECK(typeid(double) < t_int); BOOST_CHECK(typeid(int) > t_double); BOOST_CHECK(t_int > typeid(double)); BOOST_CHECK(t_double <= typeid(int)); BOOST_CHECK(typeid(double) <= t_int); BOOST_CHECK(typeid(int) >= t_double); BOOST_CHECK(t_int >= typeid(double)); } else { BOOST_CHECK(t_double > typeid(int)); BOOST_CHECK(typeid(double) > t_int); BOOST_CHECK(typeid(int) < t_double); BOOST_CHECK(t_int < typeid(double)); BOOST_CHECK(t_double >= typeid(int)); BOOST_CHECK(typeid(double) >= t_int); BOOST_CHECK(typeid(int) <= t_double); BOOST_CHECK(t_int <= typeid(double)); } } #endif // BOOST_NO_RTTI int test_main(int , char* []) { names_matches_type_id(); default_construction(); copy_construction(); comparators_type_id(); hash_code_type_id(); type_id_storing_modifiers(); type_id_storing_modifiers_vs_nonstoring(); type_index_stream_operator_via_lexical_cast_testing(); type_index_stripping_cvr_test(); type_index_user_defined_class_test(); comparators_type_id_runtime(); #ifndef BOOST_NO_RTTI comparators_type_id_vs_type_info(); #endif return 0; }
33.720588
104
0.672554
Abce
05a6cf3b2dd11e36ff53ce0c1def9bbf6099d848
2,190
cpp
C++
src/boydelatour.cpp
matheuscscp/TG
a460ed3f756cd9a759f7a0accc69bfe0754c4f2e
[ "MIT" ]
1
2016-06-10T02:37:25.000Z
2016-06-10T02:37:25.000Z
src/boydelatour.cpp
matheuscscp/TG
a460ed3f756cd9a759f7a0accc69bfe0754c4f2e
[ "MIT" ]
null
null
null
src/boydelatour.cpp
matheuscscp/TG
a460ed3f756cd9a759f7a0accc69bfe0754c4f2e
[ "MIT" ]
null
null
null
#include "libtg.hpp" #define clip(X) min(X,10000) using namespace std; static vector<Vertex>* formula; // position of u in a reverse toposort static vector<int> posdp; static int pos(int u) { static int next = 1; int& ans = posdp[u]; if (ans) return ans; for (int v : (*formula)[u].down) pos(v); return ans = next++; } // p(phi(u)) static vector<int> p; static int p_(int u) { int& ans = p[u]; if (ans) return ans; switch ((*formula)[u].type) { case CONJ: ans = 0; for (int v : (*formula)[u].down) ans = clip(ans+p_(v)); break; case DISJ: ans = 1; for (int v : (*formula)[u].down) ans = clip(ans*p_(v)); break; default: ans = 1; break; } return ans; } // Boy de la Tour's top-down renaming static void R_rec(int u, int a) { auto& phi = (*formula)[u]; if (p[u] == 1) return; // check renaming condition bool renamed = false; if (a >= 2 && (a != 2 || p[u] != 2)) { // ap > a+p a = 1; renamed = true; } // search children if (phi.type == CONJ) { for (int v : phi.down) R_rec(v,a); p[u] = 0; for (int v : phi.down) p[u] = clip(p[u]+p[v]); } else { // phi.type == DISJ int n = phi.down.size(); vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n for (int i = n-2; 0 <= i; i--) dp[i] = clip(p[phi.down[i+1]]*dp[i+1]); int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i for (int i = 0; i < n; i++) { R_rec(phi.down[i],clip(ai*dp[i])); ai = clip(ai*p[phi.down[i]]); } p[u] = 1; for (int v : phi.down) p[u] = clip(p[u]*p[v]); } if (renamed) { R.push_back(u); p[u] = 1; } } void boydelatour() { formula = (is_tree ? &T : &G); // dp tables posdp = vector<int>(formula->size(),0); p = vector<int>(formula->size(),0); // necessary preprocessing for Boy de la Tour's algorithm // compute p field and reverse toposort edges auto toposortless = [](int u, int v) { return pos(u) < pos(v); }; for (int u = 0; u < formula->size(); u++) { auto& phi = (*formula)[u]; sort(phi.down.begin(),phi.down.end(),toposortless); p[u] = p_(u); } R_rec(0,1); // recursive algorithm }
23.052632
74
0.528311
matheuscscp
05af88578e695fae5aef5141d6dcd710aad563a4
863
cpp
C++
prj_4/dictionary_merge.cpp
MatrixWood/some-modern-cpp-training
d4d6901acf394bd6d620d63aab5f514839e31c57
[ "MIT" ]
null
null
null
prj_4/dictionary_merge.cpp
MatrixWood/some-modern-cpp-training
d4d6901acf394bd6d620d63aab5f514839e31c57
[ "MIT" ]
null
null
null
prj_4/dictionary_merge.cpp
MatrixWood/some-modern-cpp-training
d4d6901acf394bd6d620d63aab5f514839e31c57
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <iterator> #include <deque> #include <tuple> #include <string> #include <fstream> using namespace std; using dict_entry = pair<string, string>; namespace std { ostream& operator<<(ostream &os, const dict_entry p) { return os << p.first << " " << p.second; } istream& operator>>(istream &is, dict_entry &p) { return is >> p.first >> p.second; } } template <typename IS> deque<dict_entry> from_instream(IS &&is) { deque<dict_entry> d {istream_iterator<dict_entry>{is}, {}}; sort(begin(d), end(d)); return d; } int main() { ifstream file_in {"dict.txt"}; const auto dict1 (from_instream(ifstream{"dict.txt"})); const auto dict2 (from_instream(cin)); merge(begin(dict1), end(dict1), begin(dict2), end(dict2), ostream_iterator<dict_entry>{cout, "\n"}); }
20.069767
63
0.651217
MatrixWood
05b38635a526b938ded96e2cddcd4052b36969bf
3,032
hpp
C++
samples/RayTracing/CameraManipulator.hpp
W4RH4WK/Vulkan-Hpp
33b244859b97650c9ca5d32ed6439f944f0eb83c
[ "Apache-2.0" ]
null
null
null
samples/RayTracing/CameraManipulator.hpp
W4RH4WK/Vulkan-Hpp
33b244859b97650c9ca5d32ed6439f944f0eb83c
[ "Apache-2.0" ]
null
null
null
samples/RayTracing/CameraManipulator.hpp
W4RH4WK/Vulkan-Hpp
33b244859b97650c9ca5d32ed6439f944f0eb83c
[ "Apache-2.0" ]
null
null
null
// Copyright(c) 2019, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <glm/glm.hpp> #include <vulkan/vulkan.hpp> namespace vk { namespace su { class CameraManipulator { public: enum class Action { None, Orbit, Dolly, Pan, LookAround }; enum class Mode { Examine, Fly, Walk, Trackball }; enum class MouseButton { None, Left, Middle, Right }; enum class ModifierFlagBits { Shift = 1, Ctrl = 2, Alt = 4 }; using ModifierFlags = vk::Flags<ModifierFlagBits, uint32_t, ModifierFlagBits::Shift>; public: CameraManipulator(); glm::vec3 const& getCameraPosition() const; glm::vec3 const& getCenterPosition() const; glm::mat4 const& getMatrix() const; Mode getMode() const; glm::ivec2 const& getMousePosition() const; float getRoll() const; float getSpeed() const; glm::vec3 const& getUpVector() const; glm::u32vec2 const& getWindowSize() const; Action mouseMove(glm::ivec2 const& position, MouseButton mouseButton, ModifierFlags & modifiers); void setLookat(const glm::vec3& cameraPosition, const glm::vec3& centerPosition, const glm::vec3& upVector); void setMode(Mode mode); void setMousePosition(glm::ivec2 const& position); void setRoll(float roll); // roll in radians void setSpeed(float speed); void setWindowSize(glm::ivec2 const& size); void wheel(int value); private: void dolly(glm::vec2 const& delta); void motion(glm::ivec2 const& position, Action action = Action::None); void orbit(glm::vec2 const& delta, bool invert = false); void pan(glm::vec2 const& delta); double projectOntoTBSphere(const glm::vec2& p); void trackball(glm::ivec2 const& position); void update(); private: glm::vec3 m_cameraPosition = glm::vec3(10, 10, 10); glm::vec3 m_centerPosition = glm::vec3(0, 0, 0); glm::vec3 m_upVector = glm::vec3(0, 1, 0); float m_roll = 0; // Rotation around the Z axis in RAD glm::mat4 m_matrix = glm::mat4(1); glm::u32vec2 m_windowSize = glm::u32vec2(1, 1); float m_speed = 30.0f; glm::ivec2 m_mousePosition = glm::ivec2(0, 0); Mode m_mode = Mode::Examine; }; } // namespace su } // namespace vk
37.9
116
0.628958
W4RH4WK
05b897c9c3e127bb51aae3329e962a46e18b36c4
9,288
cxx
C++
python/src/b2Math.cxx
pyb2d/pyb2d
5d0f9f581d93c3681ee4f518a5d7fd6be900e695
[ "MIT" ]
26
2021-12-10T12:08:39.000Z
2022-03-29T17:45:31.000Z
python/src/b2Math.cxx
pyb2d/pyb2d
5d0f9f581d93c3681ee4f518a5d7fd6be900e695
[ "MIT" ]
14
2021-11-18T23:58:55.000Z
2022-01-06T09:44:58.000Z
python/src/b2Math.cxx
DerThorsten/pybox2d
5d0f9f581d93c3681ee4f518a5d7fd6be900e695
[ "MIT" ]
3
2021-12-16T05:52:12.000Z
2021-12-21T08:58:54.000Z
#include <pybind11/pybind11.h> #include <pybind11/operators.h> #include "box2d_wrapper.hpp" namespace py = pybind11; b2Vec2 operator+ (const b2Vec2 & lhs, const py::tuple & rhs) { return b2Vec2( lhs.x + rhs[0].cast<float>() , lhs.y + rhs[1].cast<float>() ); } b2Vec2 operator+ (const py::tuple & lhs, const b2Vec2 & rhs) { return b2Vec2( lhs[0].cast<float>() + rhs.x , lhs[1].cast<float>() + rhs.y ); } // b2Vec2 operator+ (const b2Vec2 & lhs, const b2Vec2 & rhs) // { // return b2Vec2( // lhs.x + rhs.x , // lhs.y + rhs.y // ); // } #ifndef PYB2D_LIQUID_FUN b2Vec2 operator/ (const b2Vec2 & lhs, float rhs) { return b2Vec2( lhs.x / rhs , lhs.y / rhs ); } b2Vec2 operator* (const b2Vec2 & lhs, float rhs) { return b2Vec2( lhs.x * rhs , lhs.y * rhs ); } #endif void exportB2Math(py::module & pyb2dModule){ pyb2dModule.def("b2IsValid",&b2IsValid, py::arg("x")); //pyb2dModule.def("b2InvSqrt",&b2InvSqrt, py::arg("x")); pyb2dModule.def("b2Sqrt",&sqrtf, py::arg("x")); pyb2dModule.def("b2Atan2",&atan2f, py::arg("x"),py::arg("y")); py::class_<b2Vec2>(pyb2dModule,"Vec2") .def(py::init([](py::tuple t) { if(py::len(t) != 2) { throw std::runtime_error("tuple has wrong length"); } return new b2Vec2(t[0].cast<float>(), t[1].cast<float>()); } )) .def(py::init([](py::list t) { if(py::len(t) != 2) { throw std::runtime_error("list has wrong length"); } return new b2Vec2(t[0].cast<float>(), t[1].cast<float>()); } )) .def(py::init<>()) .def(py::init<b2Vec2>()) .def(py::init<float,float>(),py::arg("x"),py::arg("y")) .def_readwrite("x", &b2Vec2::x) .def_readwrite("y", &b2Vec2::y) // member functions .def("set_zero",&b2Vec2::SetZero) .def("Set",&b2Vec2::Set,py::arg("x"),py::arg("y")) //.def("Length",&b2Vec2::Length) .def("normalize",&b2Vec2::Normalize) .def("is_valid",&b2Vec2::IsValid) .def("skew",&b2Vec2::Skew) .def("__len__",[](const b2Vec2 & vec){return 2;}) // operators // .def(py::self += py::self) // .def(py::self -= py::self) // .def(py::self *= float()) // .def(py::self + float()) // .def(py::self - float()) .def(float() * py::self) .def(py::self * float()) .def(py::self / float()) .def(py::self + py::self) .def(py::self - py::self) // .def(py::self + py::tuple()) // .def(py::tuple() + py::self) .def_property_readonly("length",[](const b2Vec2 & self){ return std::sqrt(self.x * self.x + self.y * self.y); }) .def_property_readonly("length_squared",&b2Vec2::LengthSquared) ; py::implicitly_convertible<py::tuple, b2Vec2>(); py::implicitly_convertible<py::list, b2Vec2>(); py::class_<b2Vec3>(pyb2dModule,"Vec3") .def(py::init<>()) .def(py::init<float,float,float>(),py::arg("x"),py::arg("y"),py::arg("z")) .def_readwrite("x", &b2Vec3::x) .def_readwrite("y", &b2Vec3::y) .def_readwrite("z", &b2Vec3::z) // member functions .def("set_zero",&b2Vec3::SetZero) .def("set",&b2Vec3::Set,py::arg("x"),py::arg("y"),py::arg("z")) //.def("normalize",&b2Vec3::Normalize) // operators .def(py::self += py::self) .def(py::self -= py::self) .def(py::self *= float()) //.def_property_readonly("length",&b2Vec3::Length) // .def_property_readonly("length_squared",&b2Vec3::LengthSquared) ; // py::class_<b2Vec4>(pyb2dModule,"b2Vec4") // .def(py::init<>()) // .def(py::init<float,float,float,float>(),py::arg("x"),py::arg("y"),py::arg("z"),py::arg("w")) // .def_readwrite("x", &b2Vec4::x) // .def_readwrite("y", &b2Vec4::y) // .def_readwrite("z", &b2Vec4::z) // .def_readwrite("z", &b2Vec4::w) // //.def_property_readonly("length",&b2Vec4::Length) // //.def_property_readonly("length_squared",&b2Vec4::LengthSquared) // ; py::class_<b2Mat22>(pyb2dModule,"Mat22") .def(py::init<>()) .def(py::init<const b2Vec2 &,const b2Vec2 &>(),py::arg("c1"),py::arg("c2")) .def(py::init<float,float,float,float>(),py::arg("a11"),py::arg("a12"),py::arg("a21"),py::arg("a22")) .def_readwrite("ex", &b2Mat22::ex) .def_readwrite("ey", &b2Mat22::ey) // member functions .def("set",&b2Mat22::Set,py::arg("c1"),py::arg("c2")) .def("set_identity",&b2Mat22::SetIdentity) .def("set_zero",&b2Mat22::SetZero) .def("get_inverse",&b2Mat22::GetInverse) .def("solve",&b2Mat22::Solve,py::arg("b")) // operators ; py::class_<b2Mat33>(pyb2dModule,"Mat33") .def(py::init<>()) .def(py::init<const b2Vec3 &,const b2Vec3 &,const b2Vec3 &>(),py::arg("c1"),py::arg("c2"),py::arg("c3")) .def_readwrite("ex", &b2Mat33::ex) .def_readwrite("ey", &b2Mat33::ey) .def_readwrite("ez", &b2Mat33::ez) // member functions .def("set_zero",&b2Mat33::SetZero) .def("solve_33",&b2Mat33::Solve33,py::arg("b")) .def("solve_22",&b2Mat33::Solve22,py::arg("b")) .def("get_inverse_22",&b2Mat33::GetInverse22,py::arg("M")) .def("get_sym_inverse_33",&b2Mat33::GetSymInverse33,py::arg("M")) // operators // ; py::class_<b2Rot>(pyb2dModule,"Rot") .def(py::init<>()) .def(py::init<float>(),py::arg("angle")) .def_readwrite("s", &b2Rot::s) .def_readwrite("c", &b2Rot::c) // member functions .def("set",&b2Rot::Set,py::arg("angle")) .def("set_identity",&b2Rot::SetIdentity) .def("get_angle",&b2Rot::GetAngle) .def("get_x_axis",&b2Rot::GetXAxis) .def("get_y_axis",&b2Rot::GetYAxis) // operators // ; py::class_<b2Transform>(pyb2dModule,"Transform") .def(py::init<>()) .def(py::init<const b2Vec2 &, const b2Rot & >(),py::arg("position"),py::arg("rotation")) .def_readwrite("p", &b2Transform::p) .def_readwrite("position", &b2Transform::p) .def_readwrite("q", &b2Transform::q) // member functions .def("set",&b2Transform::Set,py::arg("position"),py::arg("angle")) .def("set_identity",&b2Transform::SetIdentity) // .def("GetPositionX",&b2Transform::GetPositionX) // .def("GetPositionY",&b2Transform::GetPositionY) //.def("GetRotationCos",&b2Transform::GetRotationCos) // operators // ; py::class_<b2Sweep>(pyb2dModule,"Sweep") .def(py::init<>()) .def_readwrite("local_center", &b2Sweep::localCenter) .def_readwrite("c0", &b2Sweep::c0) .def_readwrite("c", &b2Sweep::c) .def_readwrite("a0", &b2Sweep::a0) .def_readwrite("a", &b2Sweep::a) .def_readwrite("alpha0", &b2Sweep::alpha0) // member functions .def("Advance",&b2Sweep::Advance,py::arg("alpha")) .def("Normalize",&b2Sweep::Normalize) // operators // ; pyb2dModule.def("dot", [](const b2Vec2& a, const b2Vec2& b){ return b2Dot(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("dot", [](const b2Vec3& a, const b2Vec3& b){ return b2Dot(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](const b2Vec2& a, const b2Vec2& b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](const b2Vec3& a, const b2Vec3& b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](const b2Vec2& a, float b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("cross", [](float a, const b2Vec2& b){ return b2Cross(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("mulT", [](const b2Mat22 & A, const b2Vec2& v){ return b2MulT(A,v); },py::arg("A"),py::arg("v")); pyb2dModule.def("mulT", [](const b2Rot & q, const b2Vec2& v){ return b2MulT(q,v); },py::arg("q"),py::arg("v")); pyb2dModule.def("distance", [](const b2Vec2& a, const b2Vec2& b){ return b2Distance(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("distance_squared", [](const b2Vec2& a, const b2Vec2& b){ return b2DistanceSquared(a,b); },py::arg("a"),py::arg("b")); pyb2dModule.def("mul", [](const b2Mat22 & A, const b2Mat22& B){ return b2Mul(A,B); },py::arg("A"),py::arg("B")); pyb2dModule.def("mul", [](const b2Mat33 & A, const b2Vec3& v){ return b2Mul(A,v); },py::arg("A"),py::arg("v")); pyb2dModule.def("mul", [](const b2Rot & q, const b2Rot& r){ return b2Mul(q,r); },py::arg("q"),py::arg("r")); pyb2dModule.def("mul", [](const b2Rot & q, const b2Vec2& v){ return b2Mul(q,v); },py::arg("q"),py::arg("v")); pyb2dModule.def("mul", [](const b2Transform & T, const b2Vec2& v){ return b2Mul(T,v); },py::arg("T"),py::arg("v")); }
33.652174
112
0.535099
pyb2d
05bd135eb8b2b8e46aed8631402574a3e700a232
3,135
cpp
C++
src/RJChorus.cpp
netboy3/RJModules-rack-plugins
0ec265da4d7cff14c2b7fc6749e3f4e81241f093
[ "MIT" ]
null
null
null
src/RJChorus.cpp
netboy3/RJModules-rack-plugins
0ec265da4d7cff14c2b7fc6749e3f4e81241f093
[ "MIT" ]
null
null
null
src/RJChorus.cpp
netboy3/RJModules-rack-plugins
0ec265da4d7cff14c2b7fc6749e3f4e81241f093
[ "MIT" ]
null
null
null
/* Slackback! */ #include "RJModules.hpp" #include "common.hpp" #include "Chorus.h" #include <iostream> #include <cmath> #include <sstream> #include <iomanip> #include <unistd.h> #include <mutex> using namespace std; #define HISTORY_SIZE (1<<21) struct RJChorusRoundSmallBlackKnob : RoundSmallBlackKnob { RJChorusRoundSmallBlackKnob() { setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/KTFRoundSmallBlackKnob.svg"))); } }; struct RJChorus : Module { enum ParamIds { DELAY_PARAM, FREQ_PARAM, DEPTH_PARAM, NUM_PARAMS }; enum InputIds { IN_INPUT, DELAY_CV, FREQ_CV, DEPTH_CV, NUM_INPUTS }; enum OutputIds { OUT_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; int lastDelay = 50; stk::Chorus chorus; RJChorus() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); configParam(RJChorus::DELAY_PARAM, 1, 6000, 50, "Delay Time ms"); configParam(RJChorus::FREQ_PARAM, 0.0, 25.0, 2.0, "Frequency"); configParam(RJChorus::DEPTH_PARAM, 0.00001, 0.99999, 0.99999, "Depth"); chorus = stk::Chorus(50); } void process(const ProcessArgs &args) override { float input = inputs[IN_INPUT].value; int delay = params[DELAY_PARAM].value * clamp(inputs[DELAY_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f); if(delay != lastDelay){ chorus = stk::Chorus(delay); lastDelay = delay; } chorus.setModFrequency( params[FREQ_PARAM].value * clamp(inputs[FREQ_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f) ); chorus.setModDepth( params[DEPTH_PARAM].value * clamp(inputs[DEPTH_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f) ); float processed = chorus.tick( input ); outputs[OUT_OUTPUT].value = processed; } }; struct RJChorusWidget : ModuleWidget { RJChorusWidget(RJChorus *module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Chorus.svg"))); int ONE = -4; addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.5, 38.9593 + ONE)), module, RJChorus::DELAY_PARAM)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 48.74977 + ONE)), module, RJChorus::DELAY_CV)); addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.51398, 62.3 + ONE)), module, RJChorus::FREQ_PARAM)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 73.3 + ONE)), module, RJChorus::FREQ_CV)); int TWO = 45; addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.5, 38.9593 + TWO)), module, RJChorus::DEPTH_PARAM)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 48.74977 + TWO)), module, RJChorus::DEPTH_CV)); addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 62.3 + TWO)), module, RJChorus::IN_INPUT)); addOutput(createOutput<PJ301MPort>(mm2px(Vec(3.51398, 73.3 + TWO)), module, RJChorus::OUT_OUTPUT)); } }; Model *modelRJChorus = createModel<RJChorus, RJChorusWidget>("RJChorus");
30.436893
126
0.649442
netboy3
05bd6ffb0a52b6134088fbd432cc826e23f25524
28,193
cpp
C++
src/helics/shared_api_library/FederateExport.cpp
manoj1511/HELICS
5b085bb4331f943d3fa98eb40056c3e10a1b882d
[ "BSD-3-Clause" ]
null
null
null
src/helics/shared_api_library/FederateExport.cpp
manoj1511/HELICS
5b085bb4331f943d3fa98eb40056c3e10a1b882d
[ "BSD-3-Clause" ]
null
null
null
src/helics/shared_api_library/FederateExport.cpp
manoj1511/HELICS
5b085bb4331f943d3fa98eb40056c3e10a1b882d
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017-2019, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #include "../core/core-exceptions.hpp" #include "../helics.hpp" #include "gmlc/concurrency/TripWire.hpp" #include "helics.h" #include "internal/api_objects.h" #include <iostream> #include <map> #include <mutex> #include <vector> /** this is a random identifier put in place when the federate or core or broker gets created*/ static const int fedValidationIdentifier = 0x2352188; static const char *invalidFedString = "federate object is not valid"; static const std::string nullstr; static constexpr char nullcstr[] = ""; namespace helics { FedObject *getFedObject (helics_federate fed, helics_error *err) noexcept { HELICS_ERROR_CHECK (err, nullptr); if (fed == nullptr) { if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = invalidFedString; } return nullptr; } auto fedObj = reinterpret_cast<helics::FedObject *> (fed); if (fedObj->valid == fedValidationIdentifier) { return fedObj; } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = invalidFedString; } return nullptr; } } // namespace helics helics::Federate *getFed (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); return (fedObj == nullptr) ? nullptr : fedObj->fedptr.get (); } static const char *notValueFedString = "Federate must be a value federate"; helics::ValueFederate *getValueFed (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::value_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = dynamic_cast<helics::ValueFederate *> (fedObj->fedptr.get ()); if (rval != nullptr) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notValueFedString; } return nullptr; } static const char *notMessageFedString = "Federate must be a message federate"; helics::MessageFederate *getMessageFed (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::message_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = dynamic_cast<helics::MessageFederate *> (fedObj->fedptr.get ()); if (rval != nullptr) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notMessageFedString; } return nullptr; } std::shared_ptr<helics::Federate> getFedSharedPtr (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } return fedObj->fedptr; } std::shared_ptr<helics::ValueFederate> getValueFedSharedPtr (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::value_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = std::dynamic_pointer_cast<helics::ValueFederate> (fedObj->fedptr); if (rval) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notValueFedString; } return nullptr; } std::shared_ptr<helics::MessageFederate> getMessageFedSharedPtr (helics_federate fed, helics_error *err) { auto fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } if ((fedObj->type == helics::vtype::message_fed) || (fedObj->type == helics::vtype::combination_fed)) { auto rval = std::dynamic_pointer_cast<helics::MessageFederate> (fedObj->fedptr); if (rval) { return rval; } } if (err != nullptr) { err->error_code = helics_error_invalid_object; err->message = notMessageFedString; } return nullptr; } /* Creation and destruction of Federates */ helics_federate helicsCreateValueFederate (const char *fedName, helics_federate_info fi, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { if (fi == nullptr) { FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (fedName), helics::FederateInfo ()); } else { FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi)); } } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::value_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsCreateValueFederateFromConfig (const char *configFile, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (configFile)); } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::value_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } /* Creation and destruction of Federates */ helics_federate helicsCreateMessageFederate (const char *fedName, helics_federate_info fi, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { if (fi == nullptr) { FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (fedName), helics::FederateInfo ()); } else { FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi)); } } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::message_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsCreateMessageFederateFromConfig (const char *configFile, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (configFile)); } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::message_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } /* Creation and destruction of Federates */ helics_federate helicsCreateCombinationFederate (const char *fedName, helics_federate_info fi, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { if (fi == nullptr) { FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (fedName), helics::FederateInfo ()); } else { FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi)); } } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::combination_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsCreateCombinationFederateFromConfig (const char *configFile, helics_error *err) { HELICS_ERROR_CHECK (err, nullptr); auto FedI = std::make_unique<helics::FedObject> (); try { FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (configFile)); } catch (...) { helicsErrorHandler (err); return nullptr; } FedI->type = helics::vtype::combination_fed; FedI->valid = fedValidationIdentifier; auto fed = reinterpret_cast<helics_federate> (FedI.get ()); getMasterHolder ()->addFed (std::move (FedI)); return (fed); } helics_federate helicsFederateClone (helics_federate fed, helics_error *err) { auto *fedObj = helics::getFedObject (fed, err); if (fedObj == nullptr) { return nullptr; } auto fedClone = std::make_unique<helics::FedObject> (); fedClone->fedptr = fedObj->fedptr; fedClone->type = fedObj->type; fedClone->valid = fedObj->valid; auto fedB = reinterpret_cast<helics_federate> (fedClone.get ()); getMasterHolder ()->addFed (std::move (fedClone)); return (fedB); } helics_bool helicsFederateIsValid (helics_federate fed) { auto fedObj = getFed (fed, nullptr); return (fedObj == nullptr) ? helics_false : helics_true; } helics_core helicsFederateGetCoreObject (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return nullptr; } auto core = std::make_unique<helics::CoreObject> (); core->valid = coreValidationIdentifier; core->coreptr = fedObj->getCorePointer (); auto retcore = reinterpret_cast<helics_core> (core.get ()); getMasterHolder ()->addCore (std::move (core)); return retcore; } static constexpr char invalidFile[] = "Invalid File specification"; void helicsFederateRegisterInterfaces (helics_federate fed, const char *file, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } if (file == nullptr) { if (err != nullptr) { err->error_code = helics_error_invalid_argument; err->message = invalidFile; } return; } try { fedObj->registerInterfaces (file); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateFinalize (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->finalize (); } catch (...) { helicsErrorHandler (err); } } void helicsFederateFinalizeAsync (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->finalizeAsync (); } catch (...) { helicsErrorHandler (err); } } void helicsFederateFinalizeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->finalizeComplete (); } catch (...) { helicsErrorHandler (err); } } /* initialization, execution, and time requests */ void helicsFederateEnterInitializingMode (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterInitializingMode (); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateEnterInitializingModeAsync (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterInitializingModeAsync (); } catch (...) { return helicsErrorHandler (err); } } helics_bool helicsFederateIsAsyncOperationCompleted (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_false; } return (fedObj->isAsyncOperationCompleted ()) ? helics_true : helics_false; } void helicsFederateEnterInitializingModeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterInitializingModeComplete (); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateEnterExecutingMode (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { // printf("current state=%d\n", static_cast<int>(fedObj->getCurrentState())); fedObj->enterExecutingMode (); } catch (...) { return helicsErrorHandler (err); } } static helics::iteration_request getIterationRequest (helics_iteration_request iterate) { switch (iterate) { case helics_iteration_request_no_iteration: default: return helics::iteration_request::no_iterations; case helics_iteration_request_force_iteration: return helics::iteration_request::force_iteration; case helics_iteration_request_iterate_if_needed: return helics::iteration_request::iterate_if_needed; } } static helics_iteration_result getIterationStatus (helics::iteration_result iterationState) { switch (iterationState) { case helics::iteration_result::next_step: return helics_iteration_result_next_step; case helics::iteration_result::iterating: return helics_iteration_result_iterating; case helics::iteration_result::error: default: return helics_iteration_result_error; case helics::iteration_result::halted: return helics_iteration_result_halted; } } helics_iteration_result helicsFederateEnterExecutingModeIterative (helics_federate fed, helics_iteration_request iterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_iteration_result_error; } try { auto val = fedObj->enterExecutingMode (getIterationRequest (iterate)); return getIterationStatus (val); } catch (...) { helicsErrorHandler (err); return helics_iteration_result_error; } } void helicsFederateEnterExecutingModeAsync (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterExecutingModeAsync (); } catch (...) { helicsErrorHandler (err); } } void helicsFederateEnterExecutingModeIterativeAsync (helics_federate fed, helics_iteration_request iterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterExecutingModeAsync (getIterationRequest (iterate)); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateEnterExecutingModeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->enterExecutingModeComplete (); } catch (...) { return helicsErrorHandler (err); } } helics_iteration_result helicsFederateEnterExecutingModeIterativeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_iteration_result_error; } try { auto val = fedObj->enterExecutingModeComplete (); return getIterationStatus (val); } catch (...) { helicsErrorHandler (err); return helics_iteration_result_error; } } helics_time helicsFederateRequestTime (helics_federate fed, helics_time requestTime, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestTime (requestTime); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_time helicsFederateRequestTimeAdvance (helics_federate fed, helics_time timeDelta, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestTimeAdvance (timeDelta); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_time helicsFederateRequestNextStep (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestNextStep (); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_time helicsFederateRequestTimeIterative (helics_federate fed, helics_time requestTime, helics_iteration_request iterate, helics_iteration_result *outIterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { if (outIterate != nullptr) { *outIterate = helics_iteration_result_error; } return helics_time_invalid; } try { auto val = fedObj->requestTimeIterative (requestTime, getIterationRequest (iterate)); if (outIterate != nullptr) { *outIterate = getIterationStatus (val.state); } return (val.grantedTime < helics::Time::maxVal ()) ? static_cast<double> (val.grantedTime) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); if (outIterate != nullptr) { *outIterate = helics_iteration_result_error; } return helics_time_invalid; } } void helicsFederateRequestTimeAsync (helics_federate fed, helics_time requestTime, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->requestTimeAsync (requestTime); } catch (...) { return helicsErrorHandler (err); } } helics_time helicsFederateRequestTimeComplete (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto timeret = fedObj->requestTimeComplete (); return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } void helicsFederateRequestTimeIterativeAsync (helics_federate fed, helics_time requestTime, helics_iteration_request iterate, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->requestTimeIterative (requestTime, getIterationRequest (iterate)); } catch (...) { return helicsErrorHandler (err); } } helics_time helicsFederateRequestTimeIterativeComplete (helics_federate fed, helics_iteration_result *outIteration, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto val = fedObj->requestTimeIterativeComplete (); if (outIteration != nullptr) { *outIteration = getIterationStatus (val.state); } return (val.grantedTime < helics::Time::maxVal ()) ? static_cast<double> (val.grantedTime) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } static const std::map<helics::Federate::modes, helics_federate_state> modeEnumConversions{ {helics::Federate::modes::error, helics_federate_state::helics_state_error}, {helics::Federate::modes::startup, helics_federate_state::helics_state_startup}, {helics::Federate::modes::executing, helics_federate_state::helics_state_execution}, {helics::Federate::modes::finalize, helics_federate_state::helics_state_finalize}, {helics::Federate::modes::pending_exec, helics_federate_state::helics_state_pending_exec}, {helics::Federate::modes::pending_init, helics_federate_state::helics_state_pending_init}, {helics::Federate::modes::pending_iterative_time, helics_federate_state::helics_state_pending_iterative_time}, {helics::Federate::modes::pending_time, helics_federate_state::helics_state_pending_time}, {helics::Federate::modes::initializing, helics_federate_state::helics_state_initialization}, {helics::Federate::modes::pending_finalize, helics_federate_state::helics_state_pending_finalize}}; helics_federate_state helicsFederateGetState (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_state_error; } try { auto FedMode = fedObj->getCurrentMode (); return modeEnumConversions.at (FedMode); } catch (...) { helicsErrorHandler (err); return helics_state_error; } } const char *helicsFederateGetName (helics_federate fed) { auto fedObj = getFed (fed, nullptr); if (fedObj == nullptr) { return nullcstr; } auto &ident = fedObj->getName (); return ident.c_str (); } void helicsFederateSetTimeProperty (helics_federate fed, int timeProperty, helics_time time, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setProperty (timeProperty, time); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateSetFlagOption (helics_federate fed, int flag, helics_bool flagValue, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setFlagOption (flag, (flagValue != helics_false)); } catch (...) { return helicsErrorHandler (err); } } void helicsFederateSetIntegerProperty (helics_federate fed, int intProperty, int propVal, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setProperty (intProperty, propVal); } catch (...) { return helicsErrorHandler (err); } } helics_time helicsFederateGetTimeProperty (helics_federate fed, int timeProperty, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto T = fedObj->getTimeProperty (timeProperty); return (T < helics::Time::maxVal ()) ? static_cast<double> (T) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } helics_bool helicsFederateGetFlagOption (helics_federate fed, int flag, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_false; } try { bool res = fedObj->getFlagOption (flag); return (res) ? helics_true : helics_false; } catch (...) { helicsErrorHandler (err); return helics_false; } } int helicsFederateGetIntegerProperty (helics_federate fed, int intProperty, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return -101; } try { return fedObj->getIntegerProperty (intProperty); } catch (...) { helicsErrorHandler (err); return -101; } } void helicsFederateSetSeparator (helics_federate fed, char separator, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } try { fedObj->setSeparator (separator); } catch (...) { helicsErrorHandler (err); } } helics_time helicsFederateGetCurrentTime (helics_federate fed, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return helics_time_invalid; } try { auto T = fedObj->getCurrentTime (); return (T < helics::Time::maxVal ()) ? static_cast<double> (T) : helics_time_maxtime; } catch (...) { helicsErrorHandler (err); return helics_time_invalid; } } static constexpr char invalidGlobalString[] = "Global name cannot be null"; void helicsFederateSetGlobal (helics_federate fed, const char *valueName, const char *value, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } if (valueName == nullptr) { if (err != nullptr) { err->error_code = helics_error_invalid_argument; err->message = invalidGlobalString; } return; } fedObj->setGlobal (valueName, AS_STRING (value)); } static constexpr char invalidFederateCore[] = "Federate core is not connected"; void helicsFederateSetLogFile (helics_federate fed, const char *logFile, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } auto cr = fedObj->getCorePointer (); try { if (cr) { cr->setLogFile (AS_STRING (logFile)); } else { if (err != nullptr) { err->error_code = helics_error_invalid_function_call; err->message = invalidFederateCore; } return; } } catch (...) { helicsErrorHandler (err); } } void helicsFederateLogErrorMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_error, logmessage, err); } void helicsFederateLogWarningMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_warning, logmessage, err); } void helicsFederateLogInfoMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_summary, logmessage, err); } void helicsFederateLogDebugMessage (helics_federate fed, const char *logmessage, helics_error *err) { helicsFederateLogLevelMessage (fed, helics_log_level_data, logmessage, err); } void helicsFederateLogLevelMessage (helics_federate fed, int loglevel, const char *logmessage, helics_error *err) { auto fedObj = getFed (fed, err); if (fedObj == nullptr) { return; } fedObj->logMessage (loglevel, AS_STRING (logmessage)); }
26.447467
140
0.630582
manoj1511
05c047501cbc80390d8e93d1cd7bd27cd77666f8
11,268
cpp
C++
ofApp.cpp
2552Software/music2
fcefe78029104214e8174cd5cf16bc690ce5bda4
[ "MIT" ]
null
null
null
ofApp.cpp
2552Software/music2
fcefe78029104214e8174cd5cf16bc690ce5bda4
[ "MIT" ]
null
null
null
ofApp.cpp
2552Software/music2
fcefe78029104214e8174cd5cf16bc690ce5bda4
[ "MIT" ]
null
null
null
#include "ofApp.h" //https://commons.wikimedia.org/wiki/File:Beer_in_glass_close_up.jpg // This is the most basic pdsp example // we set up everything and check that everything is working // before running this also check that the basic oF audio output example is working // ofxx_folder/examples/sound/audioOutputExample/ // for documentation of the modules and functions: // http://npisanti.com/ofxPDSP/md__modules.html /* roate ofPushMatrix(); ofTranslate(leafImg.width/2, leafImg.height/2, 0);//move pivot to centre ofRotate(ofGetFrameNum() * .01, 0, 0, 1);//rotate from centre ofPushMatrix(); ofTranslate(-leafImg.width/2,-leafImg.height/2,0);//move back by the centre offset leafImg.draw(0,0); ofPopMatrix(); ofPopMatrix(); https://www.vidsplay.com/ */ int AudioPlayer::number = 0; void AudioPlayer::patch() { addModuleOutput("0", fader0); addModuleOutput("1", fader1); pitchControl >> sampler0.in_pitch(); pitchControl >> sampler1.in_pitch(); sampleTrig >> sampler0 >> amp0; envGate >> env >> amp0.in_mod(); sampleTrig >> sampler1 >> amp1; env >> amp1.in_mod(); sampler0 >> amp0 >> fader0; sampler1 >> amp1 >> fader1; faderControl >> dBtoLin >> fader0.in_mod(); dBtoLin >> fader1.in_mod(); sampler0.addSample(&sample, 0); sampler1.addSample(&sample, 1); smoothControl >> env.in_attack(); smoothControl >> env.in_release(); ui.setName("pdsp player " + ofToString(++number)); ui.add(faderControl.set("volume", 0, -48, 24)); ui.add(loadButton.set("load", false)); ui.add(sampleName.set("sample", "no sample")); ui.add(samplePath.set("path", "no path")); ui.add(pitchControl.set("pitch", 0, -24, 24)); ui.add(smoothControl.set("fade ms", 0, 0, 50)); ui.add(bPlay.set("play", false)); ui.add(bPause.set("pause", false)); ui.add(bStop.set("stop", true)); loadButton.addListener(this, &AudioPlayer::loadButtonCall); samplePath.addListener(this, &AudioPlayer::sampleChangedCall); bPlay.addListener(this, &AudioPlayer::onPlay); bPause.addListener(this, &AudioPlayer::onPause); bStop.addListener(this, &AudioPlayer::onStop); bSemaphore = true; sample.setVerbose(true); } void AudioPlayer::onPlay(bool & value) { if (bSemaphore) { bSemaphore = false; if (bStop) { bPlay = true; bStop = false; envGate.trigger(1.0f); sampleTrig.trigger(1.0f); ofLogVerbose() << "[pdsp] player: playing\n"; } else if (bPause) { ofLogVerbose() << "[pdsp] player: unpaused\n"; bPlay = true; bPause = false; envGate.trigger(1.0f); } else { bPlay = true; sampleTrig.trigger(1.0f); } bSemaphore = true; } } void AudioPlayer::onPause(bool & value) { if (bSemaphore) { bSemaphore = false; if (bPlay) { bPause = true; bPlay = false; ofLogVerbose() << "[pdsp] player: paused\n"; envGate.off(); } else if (bStop) { bPause = false; ofLogVerbose() << "[pdsp] player: impossible to pause on stop"; } else { ofLogVerbose() << "[pdsp] player: unpaused\n"; bPlay = true; bPause = false; envGate.trigger(1.0f); } bSemaphore = true; } } void AudioPlayer::onStop(bool & value) { if (bSemaphore) { bSemaphore = false; if (bPlay || bPause) { bStop = true; bPlay = false; bPause = false; ofLogVerbose() << "[pdsp] player: stopped\n"; envGate.off(); } bSemaphore = true; } } void AudioPlayer::loadButtonCall(bool & value) { if (value) { float fvalue = faderControl.get(); faderControl.setv(0.0f); //Open the Open File Dialog ofFileDialogResult openFileResult = ofSystemLoadDialog("select an audio sample"); //Check if the user opened a file if (openFileResult.bSuccess) { string path = openFileResult.getPath(); samplePath = path; ofLogVerbose("file loaded"); } else { ofLogVerbose("User hit cancel"); } // switch to mono if the sample has just one channel if (sample.channels == 1) { sampler1.setSample(&sample, 0, 0); } else { sampler1.setSample(&sample, 0, 1); } loadButton = false; faderControl.setv(fvalue); bool dummy = true; onStop(dummy); } } void AudioPlayer::sampleChangedCall(string & value) { ofLogVerbose("loading" + value); loadSample(samplePath); auto v = ofSplitString(samplePath, "/"); sampleName = v[v.size() - 1]; } void AudioPlayer::loadSample(string path) { sample.load(path); } void AudioPlayer::load(string path) { samplePath = path; } void AudioPlayer::play() { bPlay = bPlay ? false : true; } void AudioPlayer::pause() { bPause = bPause ? false : true; } void AudioPlayer::stop() { bStop = bStop ? false : true; } //-------------------------------------------------------------- void ofApp::setup() { player.load(ofToDataPath("song3.wav")); player.play(); //-------------------GRAPHIC SETUP-------------- ofBackground(0); ofSetFrameRate(30); videos.add("Beer_Pour_Videvo.mp4", ofColor(255, 255, 255), 32.0f, 52.0f); videos.add("lighthouse.mp4", ofColor(255, 255, 255)); videos.setNext(); background1.load("beer1.jpg"); beer.load("beer2.jpg"); popcorn.load("popcorn.jpg"); burger.load("burger.jpg"); ignore = 0; //--------PATCHING------- // a pdsp::ADSR is an ADSR envelope that makes a one-shot modulation when triggered // pdsp::ADSR require an output sending trigger signals // remember, in pdsp out_trig() always have to be connected to in_trig() // in_trig() is the default pdsp::ADSR input signal // a pdsp::Amp multiply in_signal() and in_mod() player.out("0") >> engine.audio_out(0); player.out("1") >> engine.audio_out(1); gate_ctrl.out_trig() >> adsrEnvelop; adsrEnvelop >> amp.in_mod(); pitch_ctrl >> oscillator.in_pitch(); //oscillator >> amp * dB(-12.0f) >> engine.audio_out(0); //amp * dB(-12.0f) >> engine.audio_out(1); // we patch the pdsp::Parameter to control pitch and amp // and then patch the oscillator to the engine outs osc1_pitch_ctrl >> fm1.in_pitch(); osc2_pitch_ctrl >> fm2.in_pitch(); osc3_pitch_ctrl >> fm3.in_pitch(); // pdsp::ParameterGain can be added to gui like an ofParameter // and has an input and output for signals // it is used to control volume as it has control in deciBel // pdsp::ParameterAmp instead just multiply the input for the parameter value // it is usefule for scaling modulation signals fm1 >> osc1_amp >> engine.audio_out(0); osc1_amp >> engine.audio_out(1); //fm2 >> osc2_gain >> engine.audio_out(0); // osc2_gain >> engine.audio_out(1); //fm3 >> osc3_gain >> engine.audio_out(0); // osc3_gain >> engine.audio_out(1); osc1_pitch_ctrl.set("pitch", 60.0f, 24.0f, 96.0f); osc1_amp.set("amp", 0.25f, 0.0f, 1.0f); osc2_pitch_ctrl.set("pitch", 60, 24, 96); osc2_gain.set("active", false, -48.0f, -12.0f); osc3_pitch_ctrl.set("pitch coarse", 60, 24, 96); osc3_pitch_ctrl.set("pitch fine ", 0.0f, -0.5f, 0.5f); osc3_gain.set("gain", -24.f, -48.0f, 0.0f); osc2_pitch_ctrl.setv(ofRandom(48.0f, 96.0f)); 1.0f >> adsrEnvelop.in_attack(); 50.0f >> adsrEnvelop.in_decay(); 0.5f >> adsrEnvelop.in_sustain(); 500.0f >> adsrEnvelop.in_release(); gate_ctrl.trigger(1.0f); pitch_ctrl.setv(36.0f); // we control the value of an pdsp::Parameter directly with the setv function // you can smooth out an pdsp::Parameter changes, decomment this for less "grainy" pitch changes pitch_ctrl.enableSmoothing(50.0f); // 50ms smoothing //----------------------AUDIO SETUP------------- // set up the audio output device engine.listDevices(); engine.setDeviceID(0); // REMEMBER TO SET THIS AT THE RIGHT INDEX!!!! // start your audio engine ! engine.setup(44100, 512, 3); // arguments are : sample rate, buffer size, and how many buffer there are in the audio callback queue // 512 is the minimum buffer size for the raspberry Pi to work // 3 buffers queue is the minimum for the rPi to work // if you are using JACK you have to set this number to the bufferSize you set in JACK // on Windows you have to set the sample rate to the system sample rate, usually 44100hz // on iOS sometimes the systems forces the sample rate to 48khz, so if you have problems set 48000 } //-------------------------------------------------------------- void ofApp::update() { videos.update(); pitch_ctrl.setv(videos.getPitch()); osc1_pitch_ctrl.setv(videos.getPitch()); } //-------------------------------------------------------------- void ofApp::draw() { ofPushMatrix(); if (!ignore) { background1.draw(0, 0, ofGetScreenWidth(), ofGetScreenHeight()); } ofEnableAlphaBlending(); ofSetColor(videos.getColor().r, videos.getColor().g, videos.getColor().b, videos.getAlpha()); videos.draw(0, 0, ofGetScreenWidth(), ofGetScreenHeight()); ofDisableAlphaBlending(); ofPopMatrix(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { float pitch = ofMap(x, 0, ofGetWidth(), 36.0f, 72.0f); pitch_ctrl.setv(pitch); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { float pitch = ofMap(x, 0, ofGetWidth(), 36.0f, 72.0f); pitch_ctrl.setv(pitch); // y value controls the trigger intensity float trig = ofMap(y, 0, ofGetHeight(), 1.0f, 0.000001f); gate_ctrl.trigger(trig); // we send a trigger to the envelope } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { gate_ctrl.off(); // we send an "off" trigger to the envelope } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) { }
30.619565
124
0.564164
2552Software
05c5a3aeba06470baf5f2934446b9061e2844011
30,479
cpp
C++
isis/src/base/apps/nocam2map/nocam2map.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
1
2022-02-17T01:07:03.000Z
2022-02-17T01:07:03.000Z
isis/src/base/apps/nocam2map/nocam2map.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
isis/src/base/apps/nocam2map/nocam2map.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
#include <algorithm> #include <QList> #include <QString> #include <QStringList> #include <QVector> #include <SpiceUsr.h> #include "Cube.h" #include "Brick.h" #include "Constants.h" #include "Cube.h" #include "IString.h" #include "LeastSquares.h" #include "NaifStatus.h" #include "nocam2map.h" #include "PolynomialBivariate.h" #include "ProcessRubberSheet.h" #include "ProjectionFactory.h" #include "Statistics.h" #include "Target.h" #include "TextFile.h" #include "TProjection.h" using namespace std; using namespace Isis; namespace Isis { static void DeleteTables(Pvl *label, PvlGroup kernels); void nocam2map(UserInterface &ui, Pvl *log) { QString inputFileName = ui.GetCubeName("FROM"); Cube iCube(inputFileName); nocam2map(&iCube, ui, log); } void nocam2map(Cube *inCube, UserInterface &ui, Pvl *log) { //Create a process to create the input cubes Process p; //Create the input cubes, matching sample/lines Cube *latCube = p.SetInputCube(ui.GetCubeName("LATCUB"), ui.GetInputAttribute("LATCUB"), SpatialMatch); Cube *lonCube = p.SetInputCube(ui.GetCubeName("LONCUB"), ui.GetInputAttribute("LONCUB"), SpatialMatch); //A 1x1 brick to read in the latitude and longitude DN values from //the specified cubes Brick latBrick(1, 1, 1, latCube->pixelType()); Brick lonBrick(1, 1, 1, lonCube->pixelType()); //Set the sample and line increments float sinc = (inCube->sampleCount() * 0.10); if (ui.WasEntered("SINC")) { sinc = ui.GetInteger("SINC"); } float linc = (inCube->lineCount() * 0.10); if (ui.WasEntered("LINC")) { linc = ui.GetInteger("LINC"); } //Set the degree of the polynomial to use in our functions int degree = ui.GetInteger("DEGREE"); //We are using a polynomial with two variables PolynomialBivariate sampFunct(degree); PolynomialBivariate lineFunct(degree); //We will be solving the function using the least squares method LeastSquares sampSol(sampFunct); LeastSquares lineSol(lineFunct); //Setup the variables for solving the stereographic projection //x = cos(latitude) * sin(longitude - lon_center) //y = cos(lat_center) * sin(latitude) - sin(lat_center) * cos(latitude) * cos(longitude - lon_center) //Get the center lat and long from the input cubes double lat_center = latCube->statistics()->Average() * PI / 180.0; double lon_center = lonCube->statistics()->Average() * PI / 180.0; /** * Loop through lines and samples projecting the latitude and longitude at those * points to stereographic x and y and adding these points to the LeastSquares * matrix. */ for (float i = 1; i <= inCube->lineCount(); i += linc) { for (float j = 1; j <= inCube->sampleCount(); j += sinc) { latBrick.SetBasePosition(j, i, 1); latCube->read(latBrick); if (IsSpecial(latBrick.at(0))) continue; double lat = latBrick.at(0) * PI / 180.0; lonBrick.SetBasePosition(j, i, 1); lonCube->read(lonBrick); if (IsSpecial(lonBrick.at(0))) continue; double lon = lonBrick.at(0) * PI / 180.0; //Project lat and lon to x and y using a stereographic projection double k = 2 / (1 + sin(lat_center) * sin(lat) + cos(lat_center) * cos(lat) * cos(lon - lon_center)); double x = k * cos(lat) * sin(lon - lon_center); double y = k * (cos(lat_center) * sin(lat)) - (sin(lat_center) * cos(lat) * cos(lon - lon_center)); //Add x and y to the least squares matrix vector<double> data; data.push_back(x); data.push_back(y); sampSol.AddKnown(data, j); lineSol.AddKnown(data, i); //If the sample increment goes past the last sample in the line, we want to //always read the last sample.. if (j != inCube->sampleCount() && j + sinc > inCube->sampleCount()) { j = inCube->sampleCount() - sinc; } } //If the line increment goes past the last line in the cube, we want to //always read the last line.. if (i != inCube->lineCount() && i + linc > inCube->lineCount()) { i = inCube->lineCount() - linc; } } //Solve the least squares functions using QR Decomposition try { sampSol.Solve(LeastSquares::QRD); lineSol.Solve(LeastSquares::QRD); } catch (IException &e) { FileName inFile = inCube->fileName(); QString msg = "Unable to calculate transformation of projection for [" + inFile.expanded() + "]."; throw IException(e, IException::Unknown, msg, _FILEINFO_); } //If the user wants to save the residuals to a file, create a file and write //the column titles to it. TextFile oFile; if (ui.WasEntered("RESIDUALS")) { oFile.Open(ui.GetFileName("RESIDUALS"), "overwrite"); oFile.PutLine("Sample,\tLine,\tX,\tY,\tSample Error,\tLine Error\n"); } //Gather the statistics for the residuals from the least squares solutions Statistics sampErr; Statistics lineErr; vector<double> sampResiduals = sampSol.Residuals(); vector<double> lineResiduals = lineSol.Residuals(); for (int i = 0; i < (int)sampResiduals.size(); i++) { sampErr.AddData(sampResiduals[i]); lineErr.AddData(lineResiduals[i]); } //If a residuals file was specified, write the previous data, and the errors to the file. if (ui.WasEntered("RESIDUALS")) { for (int i = 0; i < sampSol.Rows(); i++) { vector<double> data = sampSol.GetInput(i); QString tmp = ""; tmp += toString(sampSol.GetExpected(i)); tmp += ",\t"; tmp += toString(lineSol.GetExpected(i)); tmp += ",\t"; tmp += toString(data[0]); tmp += ",\t"; tmp += toString(data[1]); tmp += ",\t"; tmp += toString(sampResiduals[i]); tmp += ",\t"; tmp += toString(lineResiduals[i]); oFile.PutLine(tmp + "\n"); } } oFile.Close(); //Records the error to the log PvlGroup error("Error"); error += PvlKeyword("Degree", toString(degree)); error += PvlKeyword("NumberOfPoints", toString((int)sampResiduals.size())); error += PvlKeyword("SampleMinimumError", toString(sampErr.Minimum())); error += PvlKeyword("SampleAverageError", toString(sampErr.Average())); error += PvlKeyword("SampleMaximumError", toString(sampErr.Maximum())); error += PvlKeyword("SampleStdDeviationError", toString(sampErr.StandardDeviation())); error += PvlKeyword("LineMinimumError", toString(lineErr.Minimum())); error += PvlKeyword("LineAverageError", toString(lineErr.Average())); error += PvlKeyword("LineMaximumError", toString(lineErr.Maximum())); error += PvlKeyword("LineStdDeviationError", toString(lineErr.StandardDeviation())); if (log) { log->addGroup(error); } //Close the input cubes for cleanup p.EndProcess(); //If we want to warp the image, then continue, otherwise return if (!ui.GetBoolean("NOWARP")) { //Creates the mapping group Pvl mapFile; mapFile.read(ui.GetFileName("MAP")); PvlGroup &mapGrp = mapFile.findGroup("Mapping", Pvl::Traverse); //Reopen the lat and long cubes latCube = new Cube(); latCube->setVirtualBands(ui.GetInputAttribute("LATCUB").bands()); latCube->open(ui.GetCubeName("LATCUB")); lonCube = new Cube(); lonCube->setVirtualBands(ui.GetInputAttribute("LONCUB").bands()); lonCube->open(ui.GetCubeName("LONCUB")); PvlKeyword targetName; //If the user entered the target name if (ui.WasEntered("TARGET")) { targetName = PvlKeyword("TargetName", ui.GetString("TARGET")); } //Else read the target name from the input cube else { Pvl fromFile; fromFile.read(inCube->fileName()); targetName = fromFile.findKeyword("TargetName", Pvl::Traverse); } mapGrp.addKeyword(targetName, Pvl::Replace); PvlKeyword equRadius; PvlKeyword polRadius; //If the user entered the equatorial and polar radii if (ui.WasEntered("EQURADIUS") && ui.WasEntered("POLRADIUS")) { equRadius = PvlKeyword("EquatorialRadius", toString(ui.GetDouble("EQURADIUS"))); polRadius = PvlKeyword("PolarRadius", toString(ui.GetDouble("POLRADIUS"))); } //Else read them from the pck else { PvlGroup radii = Target::radiiGroup(targetName[0]); equRadius = radii["EquatorialRadius"]; polRadius = radii["PolarRadius"]; } mapGrp.addKeyword(equRadius, Pvl::Replace); mapGrp.addKeyword(polRadius, Pvl::Replace); //If the latitude type is not in the mapping group, copy it from the input if (!mapGrp.hasKeyword("LatitudeType")) { if (ui.GetString("LATTYPE") == "PLANETOCENTRIC") { mapGrp.addKeyword(PvlKeyword("LatitudeType", "Planetocentric"), Pvl::Replace); } else { mapGrp.addKeyword(PvlKeyword("LatitudeType", "Planetographic"), Pvl::Replace); } } //If the longitude direction is not in the mapping group, copy it from the input if (!mapGrp.hasKeyword("LongitudeDirection")) { if (ui.GetString("LONDIR") == "POSITIVEEAST") { mapGrp.addKeyword(PvlKeyword("LongitudeDirection", "PositiveEast"), Pvl::Replace); } else { mapGrp.addKeyword(PvlKeyword("LongitudeDirection", "PositiveWest"), Pvl::Replace); } } //If the longitude domain is not in the mapping group, assume it is 360 if (!mapGrp.hasKeyword("LongitudeDomain")) { mapGrp.addKeyword(PvlKeyword("LongitudeDomain", "360"), Pvl::Replace); } //If the default range is to be computed, use the input lat/long cubes to determine the range if (ui.GetString("DEFAULTRANGE") == "COMPUTE") { //NOTE - When computing the min/max longitude this application does not account for the //longitude seam if it exists. Since the min/max are calculated from the statistics of //the input longitude cube and then converted to the mapping group's domain they may be //invalid for cubes containing the longitude seam. Statistics *latStats = latCube->statistics(); Statistics *lonStats = lonCube->statistics(); double minLat = latStats->Minimum(); double maxLat = latStats->Maximum(); bool isOcentric = ((QString)mapGrp.findKeyword("LatitudeType")) == "Planetocentric"; if (isOcentric) { if (ui.GetString("LATTYPE") != "PLANETOCENTRIC") { minLat = TProjection::ToPlanetocentric(minLat, (double)equRadius, (double)polRadius); maxLat = TProjection::ToPlanetocentric(maxLat, (double)equRadius, (double)polRadius); } } else { if (ui.GetString("LATTYPE") == "PLANETOCENTRIC") { minLat = TProjection::ToPlanetographic(minLat, (double)equRadius, (double)polRadius); maxLat = TProjection::ToPlanetographic(maxLat, (double)equRadius, (double)polRadius); } } int lonDomain = (int)mapGrp.findKeyword("LongitudeDomain"); double minLon = lonDomain == 360 ? TProjection::To360Domain(lonStats->Minimum()) : TProjection::To180Domain(lonStats->Minimum()); double maxLon = lonDomain == 360 ? TProjection::To360Domain(lonStats->Maximum()) : TProjection::To180Domain(lonStats->Maximum()); bool isPosEast = ((QString)mapGrp.findKeyword("LongitudeDirection")) == "PositiveEast"; if (isPosEast) { if (ui.GetString("LONDIR") != "POSITIVEEAST") { minLon = TProjection::ToPositiveEast(minLon, lonDomain); maxLon = TProjection::ToPositiveEast(maxLon, lonDomain); } } else { if (ui.GetString("LONDIR") == "POSITIVEEAST") { minLon = TProjection::ToPositiveWest(minLon, lonDomain); maxLon = TProjection::ToPositiveWest(maxLon, lonDomain); } } if (minLon > maxLon) { double temp = minLon; minLon = maxLon; maxLon = temp; } mapGrp.addKeyword(PvlKeyword("MinimumLatitude", toString(minLat)), Pvl::Replace); mapGrp.addKeyword(PvlKeyword("MaximumLatitude", toString(maxLat)), Pvl::Replace); mapGrp.addKeyword(PvlKeyword("MinimumLongitude", toString(minLon)), Pvl::Replace); mapGrp.addKeyword(PvlKeyword("MaximumLongitude", toString(maxLon)), Pvl::Replace); } //If the user decided to enter a ground range then override if (ui.WasEntered("MINLAT")) { mapGrp.addKeyword(PvlKeyword("MinimumLatitude", toString(ui.GetDouble("MINLAT"))), Pvl::Replace); } if (ui.WasEntered("MAXLAT")) { mapGrp.addKeyword(PvlKeyword("MaximumLatitude", toString(ui.GetDouble("MAXLAT"))), Pvl::Replace); } if (ui.WasEntered("MINLON")) { mapGrp.addKeyword(PvlKeyword("MinimumLongitude", toString(ui.GetDouble("MINLON"))), Pvl::Replace); } if (ui.WasEntered("MAXLON")) { mapGrp.addKeyword(PvlKeyword("MaximumLongitude", toString(ui.GetDouble("MAXLON"))), Pvl::Replace); } //If the pixel resolution is to be computed, compute the pixels/degree from the input if (ui.GetString("PIXRES") == "COMPUTE") { latBrick.SetBasePosition(1, 1, 1); latCube->read(latBrick); lonBrick.SetBasePosition(1, 1, 1); lonCube->read(lonBrick); //Read the lat and long at the upper left corner double a = latBrick.at(0) * PI / 180.0; double c = lonBrick.at(0) * PI / 180.0; latBrick.SetBasePosition(latCube->sampleCount(), latCube->lineCount(), 1); latCube->read(latBrick); lonBrick.SetBasePosition(lonCube->sampleCount(), lonCube->lineCount(), 1); lonCube->read(lonBrick); //Read the lat and long at the lower right corner double b = latBrick.at(0) * PI / 180.0; double d = lonBrick.at(0) * PI / 180.0; //Determine the angle between the two points double angle = acos(cos(a) * cos(b) * cos(c - d) + sin(a) * sin(b)); //double angle = acos((cos(a1) * cos(b1) * cos(b2)) + (cos(a1) * sin(b1) * cos(a2) * sin(b2)) + (sin(a1) * sin(a2))); angle *= 180 / PI; //Determine the number of pixels between the two points double pixels = sqrt(pow(latCube->sampleCount() - 1.0, 2.0) + pow(latCube->lineCount() - 1.0, 2.0)); //Add the scale in pixels/degree to the mapping group mapGrp.addKeyword(PvlKeyword("Scale", toString(pixels / angle), "pixels/degree"), Pvl::Replace); if (mapGrp.hasKeyword("PixelResolution")) { mapGrp.deleteKeyword("PixelResolution"); } } // If the user decided to enter a resolution then override if (ui.GetString("PIXRES") == "MPP") { mapGrp.addKeyword(PvlKeyword("PixelResolution", toString(ui.GetDouble("RESOLUTION")), "meters/pixel"), Pvl::Replace); if (mapGrp.hasKeyword("Scale")) { mapGrp.deleteKeyword("Scale"); } } else if (ui.GetString("PIXRES") == "PPD") { mapGrp.addKeyword(PvlKeyword("Scale", toString(ui.GetDouble("RESOLUTION")), "pixels/degree"), Pvl::Replace); if (mapGrp.hasKeyword("PixelResolution")) { mapGrp.deleteKeyword("PixelResolution"); } } //Create a projection using the map file we created int samples, lines; TProjection *outmap = (TProjection *) ProjectionFactory::CreateForCube(mapFile, samples, lines, false); //Create a process rubber sheet ProcessRubberSheet r; //Set the input cube r.SetInputCube(inCube); double tolerance = ui.GetDouble("TOLERANCE") * outmap->Resolution(); //Create a new transform object Transform *transform = new NoCam2Map(sampSol, lineSol, outmap, latCube, lonCube, ui.GetString("LATTYPE") == "PLANETOCENTRIC", ui.GetString("LONDIR") == "POSITIVEEAST", tolerance, ui.GetInteger("ITERATIONS"), inCube->sampleCount(), inCube->lineCount(), samples, lines); //Allocate the output cube and add the mapping labels Cube *oCube = r.SetOutputCube(ui.GetCubeName("TO"), ui.GetOutputAttribute("TO"), transform->OutputSamples(), transform->OutputLines(), inCube->bandCount()); oCube->putGroup(mapGrp); PvlGroup kernels; Pvl *label=oCube->label(); if ( oCube->hasGroup("Kernels") ) { kernels=oCube->group("Kernels"); DeleteTables(label, kernels); oCube->deleteGroup("Kernels"); } if ( label->hasObject("NaifKeywords") ) { label->deleteObject("NaifKeywords"); } //Determine which interpolation to use Interpolator *interp = NULL; if (ui.GetString("INTERP") == "NEARESTNEIGHBOR") { interp = new Interpolator(Interpolator::NearestNeighborType); } else if (ui.GetString("INTERP") == "BILINEAR") { interp = new Interpolator(Interpolator::BiLinearType); } else if (ui.GetString("INTERP") == "CUBICCONVOLUTION") { interp = new Interpolator(Interpolator::CubicConvolutionType); } //Warp the cube r.StartProcess(*transform, *interp); r.EndProcess(); // add mapping to print.prt PvlGroup mapping = outmap->Mapping(); if (log) { log->addGroup(mapping); } //Clean up delete latCube; delete lonCube; delete outmap; delete transform; delete interp; } } // Transform object constructor NoCam2Map::NoCam2Map(LeastSquares sample, LeastSquares line, TProjection *outmap, Cube *latCube, Cube *lonCube, bool isOcentric, bool isPosEast, double tolerance, int iterations, const int inputSamples, const int inputLines, const int outputSamples, const int outputLines) { p_sampleSol = &sample; p_lineSol = &line; p_outmap = outmap; p_inputSamples = inputSamples; p_inputLines = inputLines; p_outputSamples = outputSamples; p_outputLines = outputLines; p_latCube = latCube; p_lonCube = lonCube; p_isOcentric = isOcentric; p_isPosEast = isPosEast; p_tolerance = tolerance; p_iterations = iterations; p_latCenter = p_latCube->statistics()->Average() * PI / 180.0; p_lonCenter = p_lonCube->statistics()->Average() * PI / 180.0; p_radius = p_outmap->LocalRadius(p_latCenter); } // Transform method mapping output line/samps to lat/lons to input line/samps bool NoCam2Map::Xform(double &inSample, double &inLine, const double outSample, const double outLine) { if (!p_outmap->SetWorld(outSample, outLine)) return false; if (outSample > p_outputSamples) return false; if (outLine > p_outputLines) return false; //Get the known latitude and longitudes from the projection //Convert to the input's latitude/longitude domain if necessary double lat_known, lon_known; if (p_outmap->IsPlanetocentric()) { if (!p_isOcentric) lat_known = p_outmap->ToPlanetographic(p_outmap->Latitude()); else lat_known = p_outmap->Latitude(); } else { if (p_isOcentric) lat_known = p_outmap->ToPlanetocentric(p_outmap->Latitude()); else lat_known = p_outmap->Latitude(); } if (p_outmap->IsPositiveEast()) { if (!p_isPosEast) lon_known = p_outmap->ToPositiveWest(p_outmap->Longitude(), 360); else lon_known = p_outmap->Longitude(); } else { if (p_isPosEast) lon_known = p_outmap->ToPositiveEast(p_outmap->Longitude(), 360); else lon_known = p_outmap->Longitude(); } lat_known *= PI / 180.0; lon_known *= PI / 180.0; //Project the known lat/long to x/y using the stereographic projection double k_known = 2 / (1 + sin(p_latCenter) * sin(lat_known) + cos(p_latCenter) * cos(lat_known) * cos(lon_known - p_lonCenter)); double x_known = k_known * cos(lat_known) * sin(lon_known - p_lonCenter); double y_known = k_known * (cos(p_latCenter) * sin(lat_known)) - (sin(p_latCenter) * cos(lat_known) * cos(lon_known - p_lonCenter)); vector<double> data_known; data_known.push_back(x_known); data_known.push_back(y_known); //Get the sample/line guess from the least squares solutions double sample_guess = p_sampleSol->Evaluate(data_known); double line_guess = p_lineSol->Evaluate(data_known); //If the sample/line guess is out of bounds return false if (sample_guess < -1.5) return false; if (line_guess < -1.5) return false; if (sample_guess > p_inputSamples + 1.5) return false; if (line_guess > p_inputLines + 1.5) return false; if (sample_guess < 0.5) sample_guess = 1; if (line_guess < 0.5) line_guess = 1; if (sample_guess > p_inputSamples + 0.5) sample_guess = p_inputSamples; if (line_guess > p_inputLines + 0.5) line_guess = p_inputLines; //Create a bilinear interpolator Interpolator interp(Interpolator::BiLinearType); //Create a 2x2 buffer to read the lat and long cubes Portal latPortal(interp.Samples(), interp.Lines(), p_latCube->pixelType() , interp.HotSample(), interp.HotLine()); Portal lonPortal(interp.Samples(), interp.Lines(), p_lonCube->pixelType() , interp.HotSample(), interp.HotLine()); //Set the buffers positions to the sample/line guess and read from the lat/long cubes latPortal.SetPosition(sample_guess, line_guess, 1); p_latCube->read(latPortal); lonPortal.SetPosition(sample_guess, line_guess, 1); p_lonCube->read(lonPortal); //Get the lat/long guess from the interpolator double lat_guess = interp.Interpolate(sample_guess, line_guess, latPortal.DoubleBuffer()) * PI / 180.0; double lon_guess = interp.Interpolate(sample_guess, line_guess, lonPortal.DoubleBuffer()) * PI / 180.0; //Project the lat/long guess to x/y using the stereographic projection double k_guess = 2 / (1 + sin(p_latCenter) * sin(lat_guess) + cos(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); double x_guess = k_guess * cos(lat_guess) * sin(lon_guess - p_lonCenter); double y_guess = k_guess * (cos(p_latCenter) * sin(lat_guess)) - (sin(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); //Calculate the difference between the known x/y to the x/y from our least squares solutions double x_diff = abs(x_guess - x_known) * p_radius; double y_diff = abs(y_guess - y_known) * p_radius; //If the difference is above the tolerance, correct it until it is below the tolerance or we have iterated through a set amount of times int iteration = 0; while (x_diff > p_tolerance || y_diff > p_tolerance) { if (iteration++ >= p_iterations) return false; //Create a 1st order polynomial function PolynomialBivariate sampFunct(1); PolynomialBivariate lineFunct(1); //Create a least squares solution LeastSquares sampConverge(sampFunct); LeastSquares lineConverge(lineFunct); //Add the points around the line/sample guess point to the least squares matrix for (int i = (int)(line_guess + 0.5) - 1; i <= (int)(line_guess + 0.5) + 1; i++) { //If the line is out of bounds, then skip it if (i < 1 || i > p_inputLines) continue; for (int j = (int)(sample_guess + 0.5) - 1; j <= (int)(sample_guess + 0.5) + 1; j++) { //If the sample is out of bounds, then skip it if (j < 1 || j > p_inputSamples) continue; latPortal.SetPosition(j, i, 1); p_latCube->read(latPortal); if (IsSpecial(latPortal.at(0))) continue; double n_lat = latPortal.at(0) * PI / 180.0; lonPortal.SetPosition(j, i, 1); p_lonCube->read(lonPortal); if (IsSpecial(lonPortal.at(0))) continue; double n_lon = lonPortal.at(0) * PI / 180.0; //Conver the lat/lon to x/y using the stereographic projection double n_k = 2 / (1 + sin(p_latCenter) * sin(n_lat) + cos(p_latCenter) * cos(n_lat) * cos(n_lon - p_lonCenter)); double n_x = n_k * cos(n_lat) * sin(n_lon - p_lonCenter); double n_y = n_k * (cos(p_latCenter) * sin(n_lat)) - (sin(p_latCenter) * cos(n_lat) * cos(n_lon - p_lonCenter)); //Add the points to the least squares solution vector<double> data; data.push_back(n_x); data.push_back(n_y); sampConverge.AddKnown(data, j); lineConverge.AddKnown(data, i); } } //TODO: What if solve can't and throws an error? //Solve the least squares functions sampConverge.Solve(LeastSquares::QRD); lineConverge.Solve(LeastSquares::QRD); //Try to solve the known data with our new function sample_guess = sampConverge.Evaluate(data_known); line_guess = lineConverge.Evaluate(data_known); //If the new sample/line is out of bounds return false if (sample_guess < -1.5) return false; if (line_guess < -1.5) return false; if (sample_guess > p_inputSamples + 1.5) return false; if (line_guess > p_inputLines + 1.5) return false; if (sample_guess < 0.5) sample_guess = 1; if (line_guess < 0.5) line_guess = 1; if (sample_guess > p_inputSamples + 0.5) sample_guess = p_inputSamples; if (line_guess > p_inputLines + 0.5) line_guess = p_inputLines; //Set the buffers positions to the sample/line guess and read from the lat/long cubes latPortal.SetPosition(sample_guess, line_guess, 1); p_latCube->read(latPortal); lonPortal.SetPosition(sample_guess, line_guess, 1); p_lonCube->read(lonPortal); //Get the lat/long guess from the interpolator lat_guess = interp.Interpolate(sample_guess, line_guess, latPortal.DoubleBuffer()) * PI / 180.0; lon_guess = interp.Interpolate(sample_guess, line_guess, lonPortal.DoubleBuffer()) * PI / 180.0; //Project the lat/long guess to x/y using the stereographic projection k_guess = 2 / (1 + sin(p_latCenter) * sin(lat_guess) + cos(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); x_guess = k_guess * cos(lat_guess) * sin(lon_guess - p_lonCenter); y_guess = k_guess * (cos(p_latCenter) * sin(lat_guess)) - (sin(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter)); //Calculate the difference between the known x/y to the x/y from our least squares solutions x_diff = abs(x_guess - x_known) * p_radius; y_diff = abs(y_guess - y_known) * p_radius; } //Set the input sample/line to the sample/line we've determined to be the closest fit inSample = sample_guess; inLine = line_guess; return true; } // Function to delete unwanted tables in header void DeleteTables(Pvl *label, PvlGroup kernels) { //Delete any tables in header corresponding to the Kernel const QString tableStr("Table"); const QString nameStr("Name"); //Setup a list of tables to delete with predetermined values and any tables in the kernel. //If additional tables need to be removed, they can be added to the list of tables that //detine the 'tmpTablesToDelete' QString array directly below. QString tmpTablesToDelete[] = {"SunPosition","BodyRotation","InstrumentPointing", "InstrumentPosition"}; std::vector<QString> tablesToDelete; int sizeOfTablesToDelete = (int) sizeof(tmpTablesToDelete)/sizeof(*tmpTablesToDelete); for (int i = 0; i < sizeOfTablesToDelete; i++) { tablesToDelete.push_back( tmpTablesToDelete[i] ); } for (int j=0; j < kernels.keywords(); j++) { if (kernels[j].operator[](0) == tableStr) { bool newTableToDelete=true; for (int k = 0; k<sizeOfTablesToDelete; k++) { if ( tablesToDelete[k] == kernels[j].name() ) { newTableToDelete=false; break; } } if (newTableToDelete) { tablesToDelete.push_back( kernels[j].name() ); sizeOfTablesToDelete++; } } } int tablesToDeleteSize = (int) tablesToDelete.size(); //Now go through and find all entries in the label corresponding to our unwanted keywords std::vector<int> indecesToDelete; int indecesToDeleteSize=0; for (int k=0; k < label->objects(); k++) { PvlObject &currentObject=(*label).object(k); if (currentObject.name() == tableStr) { PvlKeyword &nameKeyword = currentObject.findKeyword(nameStr); for (int l=0; l < tablesToDeleteSize; l++) { if ( nameKeyword[0] == tablesToDelete[l] ) { indecesToDelete.push_back(k-indecesToDeleteSize); indecesToDeleteSize++; //(*label).deleteObject(k); //tableDeleted = true; break; } } } } //Now go through and delete the corresponding tables for (int k=0; k < indecesToDeleteSize; k++) { (*label).deleteObject(indecesToDelete[k]); } } int NoCam2Map::OutputSamples() const { return p_outputSamples; } int NoCam2Map::OutputLines() const { return p_outputLines; } }
40.103947
140
0.616556
gknorman
fe4ae5e44e1eeb8c963dd883d513875033e811f2
876
cpp
C++
judge_client/1/uoj_judger/builtin/checker/wcmp.cpp
TRCYX/UOJ-System
a70283a4ee309f5485ec00c4cd1143fbf87d616a
[ "MIT" ]
483
2016-07-18T16:40:58.000Z
2022-03-31T04:29:12.000Z
judger/uoj_judger/builtin/checker/wcmp.cpp
chy-2003/UOJ-System
8ca70fc87c36b81a37d3a437c319348710404181
[ "MIT" ]
102
2019-04-14T05:40:54.000Z
2022-02-07T13:21:36.000Z
judger/uoj_judger/builtin/checker/wcmp.cpp
chy-2003/UOJ-System
8ca70fc87c36b81a37d3a437c319348710404181
[ "MIT" ]
166
2017-04-07T01:04:35.000Z
2022-03-30T04:59:25.000Z
#include "testlib.h" using namespace std; int main(int argc, char * argv[]) { setName("compare sequences of tokens"); registerTestlibCmd(argc, argv); int n = 0; string j, p; while (!ans.seekEof() && !ouf.seekEof()) { n++; ans.readWordTo(j); ouf.readWordTo(p); if (j != p) quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str()); } if (ans.seekEof() && ouf.seekEof()) { if (n == 1) quitf(_ok, "\"%s\"", compress(j).c_str()); else quitf(_ok, "%d tokens", n); } else { if (ans.seekEof()) quitf(_wa, "Participant output contains extra tokens"); else quitf(_wa, "Unexpected EOF in the participants output"); } }
22.461538
145
0.505708
TRCYX
fe4aec1898da27ecc3d02c703e90ee52deebd955
5,753
cc
C++
quic/quic_transport/quic_transport_server_session.cc
fcharlie/quiche
56835aa2c2e3645e0eec85bff07f9d58e3bace63
[ "BSD-3-Clause" ]
1
2019-11-05T05:26:53.000Z
2019-11-05T05:26:53.000Z
quic/quic_transport/quic_transport_server_session.cc
fcharlie/quiche
56835aa2c2e3645e0eec85bff07f9d58e3bace63
[ "BSD-3-Clause" ]
null
null
null
quic/quic_transport/quic_transport_server_session.cc
fcharlie/quiche
56835aa2c2e3645e0eec85bff07f9d58e3bace63
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/quic_transport/quic_transport_server_session.h" #include <memory> #include "url/gurl.h" #include "net/third_party/quiche/src/quic/core/quic_error_codes.h" #include "net/third_party/quiche/src/quic/core/quic_stream.h" #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h" #include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h" #include "net/third_party/quiche/src/quic/quic_transport/quic_transport_protocol.h" #include "net/third_party/quiche/src/quic/quic_transport/quic_transport_stream.h" namespace quic { namespace { class QuicTransportServerCryptoHelper : public QuicCryptoServerStream::Helper { public: bool CanAcceptClientHello(const CryptoHandshakeMessage& /*message*/, const QuicSocketAddress& /*client_address*/, const QuicSocketAddress& /*peer_address*/, const QuicSocketAddress& /*self_address*/, std::string* /*error_details*/) const override { return true; } }; } // namespace QuicTransportServerSession::QuicTransportServerSession( QuicConnection* connection, Visitor* owner, const QuicConfig& config, const ParsedQuicVersionVector& supported_versions, const QuicCryptoServerConfig* crypto_config, QuicCompressedCertsCache* compressed_certs_cache, ServerVisitor* visitor) : QuicSession(connection, owner, config, supported_versions, /*num_expected_unidirectional_static_streams*/ 0), visitor_(visitor) { for (const ParsedQuicVersion& version : supported_versions) { QUIC_BUG_IF(version.handshake_protocol != PROTOCOL_TLS1_3) << "QuicTransport requires TLS 1.3 handshake"; } static QuicTransportServerCryptoHelper* helper = new QuicTransportServerCryptoHelper(); crypto_stream_ = std::make_unique<QuicCryptoServerStream>( crypto_config, compressed_certs_cache, this, helper); } QuicStream* QuicTransportServerSession::CreateIncomingStream(QuicStreamId id) { if (id == ClientIndicationStream()) { auto indication = std::make_unique<ClientIndication>(this); ClientIndication* indication_ptr = indication.get(); ActivateStream(std::move(indication)); return indication_ptr; } auto stream = std::make_unique<QuicTransportStream>(id, this, this); QuicTransportStream* stream_ptr = stream.get(); ActivateStream(std::move(stream)); return stream_ptr; } QuicTransportServerSession::ClientIndication::ClientIndication( QuicTransportServerSession* session) : QuicStream(ClientIndicationStream(), session, /* is_static= */ false, StreamType::READ_UNIDIRECTIONAL), session_(session) {} void QuicTransportServerSession::ClientIndication::OnDataAvailable() { sequencer()->Read(&buffer_); if (buffer_.size() > ClientIndicationMaxSize()) { session_->connection()->CloseConnection( QUIC_TRANSPORT_INVALID_CLIENT_INDICATION, QuicStrCat("Client indication size exceeds ", ClientIndicationMaxSize(), " bytes"), ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); return; } if (sequencer()->IsClosed()) { session_->ProcessClientIndication(buffer_); OnFinRead(); } } bool QuicTransportServerSession::ClientIndicationParser::Parse() { bool origin_received = false; while (!reader_.IsDoneReading()) { uint16_t key; if (!reader_.ReadUInt16(&key)) { ParseError("Expected 16-bit key"); return false; } QuicStringPiece value; if (!reader_.ReadStringPiece16(&value)) { ParseError(QuicStrCat("Failed to read value for key ", key)); return false; } switch (static_cast<QuicTransportClientIndicationKeys>(key)) { case QuicTransportClientIndicationKeys::kOrigin: { GURL origin_url{std::string(value)}; if (!origin_url.is_valid()) { Error("Unable to parse the specified origin"); return false; } url::Origin origin = url::Origin::Create(origin_url); QUIC_DLOG(INFO) << "QuicTransport server received origin " << origin; if (!session_->visitor_->CheckOrigin(origin)) { Error("Origin check failed"); return false; } origin_received = true; break; } default: QUIC_DLOG(INFO) << "Unknown client indication key: " << key; break; } } if (!origin_received) { Error("No origin received"); return false; } return true; } void QuicTransportServerSession::ClientIndicationParser::Error( const std::string& error_message) { session_->connection()->CloseConnection( QUIC_TRANSPORT_INVALID_CLIENT_INDICATION, error_message, ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); } void QuicTransportServerSession::ClientIndicationParser::ParseError( QuicStringPiece error_message) { Error(QuicStrCat("Failed to parse the client indication stream: ", error_message, reader_.DebugString())); } void QuicTransportServerSession::ProcessClientIndication( QuicStringPiece indication) { ClientIndicationParser parser(this, indication); if (!parser.Parse()) { return; } // Don't set the ready bit if we closed the connection due to any error // beforehand. if (!connection()->connected()) { return; } ready_ = true; } } // namespace quic
33.643275
89
0.695116
fcharlie
fe4b3b929e3b82ad887618942b909fd2b68529f6
191
cpp
C++
exercises/3/week15/src/Animal.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
19
2020-02-21T16:46:50.000Z
2022-01-26T19:59:49.000Z
exercises/3/week15/src/Animal.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
1
2020-03-14T08:09:45.000Z
2020-03-14T08:09:45.000Z
exercises/3/week15/src/Animal.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
11
2020-02-23T12:29:58.000Z
2021-04-11T08:30:12.000Z
#include"Animal.h" Animal::Animal(int health){ this->health=health; } void Animal::eat(Food& f,int quantity){ health+=f.eat(quantity); }; int Animal::getHealth()const{ return health; };
17.363636
39
0.696335
triffon
fe4cc6b9f11183e5b1ded0e42c9c7c3c0716f818
1,059
cpp
C++
src/arch/riscv64/intr/timer.cpp
KehRoche/SimpleKernel
91ebac7e350b39555998c54f93e9d4b879230c26
[ "MIT" ]
820
2018-05-18T15:06:41.000Z
2022-03-04T03:30:01.000Z
src/arch/riscv64/intr/timer.cpp
KehRoche/SimpleKernel
91ebac7e350b39555998c54f93e9d4b879230c26
[ "MIT" ]
10
2018-06-01T09:43:07.000Z
2021-12-29T14:37:00.000Z
src/arch/riscv64/intr/timer.cpp
KehRoche/SimpleKernel
91ebac7e350b39555998c54f93e9d4b879230c26
[ "MIT" ]
92
2018-07-15T13:45:54.000Z
2021-12-29T14:24:12.000Z
/** * @file timer.h * @brief 中断抽象头文件 * @author Zone.N (Zone.Niuzh@hotmail.com) * @version 1.0 * @date 2021-09-18 * @copyright MIT LICENSE * https://github.com/Simple-XX/SimpleKernel * @par change log: * <table> * <tr><th>Date<th>Author<th>Description * <tr><td>2021-09-18<td>digmouse233<td>迁移到 doxygen * </table> */ #include "stdint.h" #include "stdio.h" #include "cpu.hpp" #include "opensbi.h" #include "intr.h" /// timer interrupt interval /// @todo 从 dts 读取 static constexpr const uint64_t INTERVAL = 390000000 / 20; /** * @brief 设置下一次时钟 */ void set_next(void) { // 调用 opensbi 提供的接口设置时钟 OPENSBI::set_timer(CPU::READ_TIME() + INTERVAL); return; } /** * @brief 时钟中断 */ void timer_intr(void) { // 每次执行中断时设置下一次中断的时间 set_next(); return; } void TIMER::init(void) { // 注册中断函数 CLINT::register_interrupt_handler(CLINT::INTR_S_TIMER, timer_intr); // 设置初次中断 OPENSBI::set_timer(CPU::READ_TIME()); // 开启时钟中断 CPU::WRITE_SIE(CPU::READ_SIE() | CPU::SIE_STIE); info("timer init.\n"); return; }
19.254545
71
0.643059
KehRoche
fe50adbac7649eaa5e13242529fa6e9f78b9ac8d
3,235
cpp
C++
sdk/object/entity.cpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
sdk/object/entity.cpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
sdk/object/entity.cpp
jrnh/herby
bf0e90b850e2f81713e4dbc21c8d8b9af78ad203
[ "MIT" ]
null
null
null
#include "sdk/object/entity.hpp" #include "sdk/object/weapon.hpp" #include "csgo/engine.hpp" C_BaseEntity* C_BaseEntity::GetBaseEntity( const int index ) { const auto client_entity = csgo::m_client_entity_list->GetClientEntity( index ); return (client_entity ? client_entity->GetBaseEntity() : nullptr); } C_BaseEntity* C_BaseEntity::GetBaseEntityFromHandle( const CBaseHandle base_handle ) { const auto client_entity = csgo::m_client_entity_list->GetClientEntityFromHandle( base_handle ); return (client_entity ? client_entity->GetBaseEntity() : nullptr); } void C_BaseEntity::SetPredictionSeed(CUserCmd* cmd) { static auto m_pPredictionRandomSeed = memory::scan< int* >(XorStr("client.dll"), XorStr("8B 0D ? ? ? ? BA ? ? ? ? E8 ? ? ? ? 83 C4 04"), 2, 1u); if (cmd) *m_pPredictionRandomSeed = cmd->random_seed; else *m_pPredictionRandomSeed = -1; } bool C_BaseAnimating::GetBoneTransform(matrix3x4_t* output, float time /*= 0.f*/) { return SetupBones(output, 128, 256, time); } bool C_BaseAnimating::GetBonePosition( matrix3x4_t* bone_transform, const int bone, Vector& output ) { if( bone_transform ) { for( auto i = 0; i < 3; i++ ) output[ i ] = bone_transform[ bone ][ i ][ 3 ]; } return ( !output.IsZero() && output.IsValid() ); } bool C_BaseAnimating::GetBoneWorld(int index, matrix3x4_t* transform, Vector& output) { if (transform) { for (auto i = 0; i < 3; i++) output[i] = transform[index][i][3]; } return !output.IsZero(); } bool C_BaseAnimating::GetBoxBoundWorld(int index, matrix3x4_t* transform, Vector& min, Vector& max) { if (transform) { auto model = GetModel(); if (model) { auto studio = csgo::m_model_info_client->GetStudioModel(model); if (studio) { auto box = studio->pHitbox(index, m_nHitboxSet()); if (box) { min = box->bbmin.Transform(transform[box->bone]); max = box->bbmax.Transform(transform[box->bone]); } } } } return (!min.IsZero() && !max.IsZero()); } bool C_BaseAnimating::GetBoxWorld(int index, matrix3x4_t* transform, Vector& output) { Vector min = { }; Vector max = { }; if (GetBoxBoundWorld(index, transform, min, max)) output = (min + max) * 0.5f; return !output.IsZero(); } bool C_BaseAnimating::GetHitboxVector(int hitbox, Vector& out) { matrix3x4_t mat[128]; if (!GetBoneTransform(mat)) return false; auto studio = csgo::m_model_info_client->GetStudioModel(GetModel()); if (!studio) return false; auto set = studio->pHitboxSet(m_nHitboxSet()); if (!set) return false; auto box = set->pHitbox(hitbox); if (!box) return false; Vector mins = { }, maxs = { }; mins = box->bbmin.Transform(mat[box->bone]); maxs = box->bbmax.Transform(mat[box->bone]); if (mins.IsZero() || maxs.IsZero()) return false; out = (mins + maxs) * 0.5f; return !(out.IsZero()); } Vector C_BaseAnimating::GetHitboxPosition(int index) { matrix3x4_t transform[128] = { }; if (!GetBoneTransform(transform)) return Vector::Zero; Vector position = { }; if (!GetBoxWorld(index, transform, position)) return Vector::Zero; return position; } C_BaseViewModel* C_BaseAttributeItem::GetBaseModel() { auto base_model = reinterpret_cast<C_BaseViewModel*>(this); return base_model; }
22.310345
145
0.686553
jrnh
fe52d7540754426ae6925e6573b1141897093ef6
6,296
hpp
C++
android-28/android/media/MediaCodecInfo_CodecProfileLevel.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/media/MediaCodecInfo_CodecProfileLevel.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/media/MediaCodecInfo_CodecProfileLevel.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JObject; namespace android::media { class MediaCodecInfo_CodecProfileLevel : public JObject { public: // Fields static jint AACObjectELD(); static jint AACObjectERLC(); static jint AACObjectERScalable(); static jint AACObjectHE(); static jint AACObjectHE_PS(); static jint AACObjectLC(); static jint AACObjectLD(); static jint AACObjectLTP(); static jint AACObjectMain(); static jint AACObjectSSR(); static jint AACObjectScalable(); static jint AACObjectXHE(); static jint AVCLevel1(); static jint AVCLevel11(); static jint AVCLevel12(); static jint AVCLevel13(); static jint AVCLevel1b(); static jint AVCLevel2(); static jint AVCLevel21(); static jint AVCLevel22(); static jint AVCLevel3(); static jint AVCLevel31(); static jint AVCLevel32(); static jint AVCLevel4(); static jint AVCLevel41(); static jint AVCLevel42(); static jint AVCLevel5(); static jint AVCLevel51(); static jint AVCLevel52(); static jint AVCProfileBaseline(); static jint AVCProfileConstrainedBaseline(); static jint AVCProfileConstrainedHigh(); static jint AVCProfileExtended(); static jint AVCProfileHigh(); static jint AVCProfileHigh10(); static jint AVCProfileHigh422(); static jint AVCProfileHigh444(); static jint AVCProfileMain(); static jint DolbyVisionLevelFhd24(); static jint DolbyVisionLevelFhd30(); static jint DolbyVisionLevelFhd60(); static jint DolbyVisionLevelHd24(); static jint DolbyVisionLevelHd30(); static jint DolbyVisionLevelUhd24(); static jint DolbyVisionLevelUhd30(); static jint DolbyVisionLevelUhd48(); static jint DolbyVisionLevelUhd60(); static jint DolbyVisionProfileDvavPen(); static jint DolbyVisionProfileDvavPer(); static jint DolbyVisionProfileDvavSe(); static jint DolbyVisionProfileDvheDen(); static jint DolbyVisionProfileDvheDer(); static jint DolbyVisionProfileDvheDtb(); static jint DolbyVisionProfileDvheDth(); static jint DolbyVisionProfileDvheDtr(); static jint DolbyVisionProfileDvheSt(); static jint DolbyVisionProfileDvheStn(); static jint H263Level10(); static jint H263Level20(); static jint H263Level30(); static jint H263Level40(); static jint H263Level45(); static jint H263Level50(); static jint H263Level60(); static jint H263Level70(); static jint H263ProfileBackwardCompatible(); static jint H263ProfileBaseline(); static jint H263ProfileH320Coding(); static jint H263ProfileHighCompression(); static jint H263ProfileHighLatency(); static jint H263ProfileISWV2(); static jint H263ProfileISWV3(); static jint H263ProfileInterlace(); static jint H263ProfileInternet(); static jint HEVCHighTierLevel1(); static jint HEVCHighTierLevel2(); static jint HEVCHighTierLevel21(); static jint HEVCHighTierLevel3(); static jint HEVCHighTierLevel31(); static jint HEVCHighTierLevel4(); static jint HEVCHighTierLevel41(); static jint HEVCHighTierLevel5(); static jint HEVCHighTierLevel51(); static jint HEVCHighTierLevel52(); static jint HEVCHighTierLevel6(); static jint HEVCHighTierLevel61(); static jint HEVCHighTierLevel62(); static jint HEVCMainTierLevel1(); static jint HEVCMainTierLevel2(); static jint HEVCMainTierLevel21(); static jint HEVCMainTierLevel3(); static jint HEVCMainTierLevel31(); static jint HEVCMainTierLevel4(); static jint HEVCMainTierLevel41(); static jint HEVCMainTierLevel5(); static jint HEVCMainTierLevel51(); static jint HEVCMainTierLevel52(); static jint HEVCMainTierLevel6(); static jint HEVCMainTierLevel61(); static jint HEVCMainTierLevel62(); static jint HEVCProfileMain(); static jint HEVCProfileMain10(); static jint HEVCProfileMain10HDR10(); static jint HEVCProfileMainStill(); static jint MPEG2LevelH14(); static jint MPEG2LevelHL(); static jint MPEG2LevelHP(); static jint MPEG2LevelLL(); static jint MPEG2LevelML(); static jint MPEG2Profile422(); static jint MPEG2ProfileHigh(); static jint MPEG2ProfileMain(); static jint MPEG2ProfileSNR(); static jint MPEG2ProfileSimple(); static jint MPEG2ProfileSpatial(); static jint MPEG4Level0(); static jint MPEG4Level0b(); static jint MPEG4Level1(); static jint MPEG4Level2(); static jint MPEG4Level3(); static jint MPEG4Level3b(); static jint MPEG4Level4(); static jint MPEG4Level4a(); static jint MPEG4Level5(); static jint MPEG4Level6(); static jint MPEG4ProfileAdvancedCoding(); static jint MPEG4ProfileAdvancedCore(); static jint MPEG4ProfileAdvancedRealTime(); static jint MPEG4ProfileAdvancedScalable(); static jint MPEG4ProfileAdvancedSimple(); static jint MPEG4ProfileBasicAnimated(); static jint MPEG4ProfileCore(); static jint MPEG4ProfileCoreScalable(); static jint MPEG4ProfileHybrid(); static jint MPEG4ProfileMain(); static jint MPEG4ProfileNbit(); static jint MPEG4ProfileScalableTexture(); static jint MPEG4ProfileSimple(); static jint MPEG4ProfileSimpleFBA(); static jint MPEG4ProfileSimpleFace(); static jint MPEG4ProfileSimpleScalable(); static jint VP8Level_Version0(); static jint VP8Level_Version1(); static jint VP8Level_Version2(); static jint VP8Level_Version3(); static jint VP8ProfileMain(); static jint VP9Level1(); static jint VP9Level11(); static jint VP9Level2(); static jint VP9Level21(); static jint VP9Level3(); static jint VP9Level31(); static jint VP9Level4(); static jint VP9Level41(); static jint VP9Level5(); static jint VP9Level51(); static jint VP9Level52(); static jint VP9Level6(); static jint VP9Level61(); static jint VP9Level62(); static jint VP9Profile0(); static jint VP9Profile1(); static jint VP9Profile2(); static jint VP9Profile2HDR(); static jint VP9Profile3(); static jint VP9Profile3HDR(); jint level(); jint profile(); // QJniObject forward template<typename ...Ts> explicit MediaCodecInfo_CodecProfileLevel(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} MediaCodecInfo_CodecProfileLevel(QJniObject obj); // Constructors MediaCodecInfo_CodecProfileLevel(); // Methods jboolean equals(JObject arg0) const; jint hashCode() const; }; } // namespace android::media
32.287179
173
0.760642
YJBeetle
fe53cbdac0756585f7fe8e257890ca1334f1fe07
1,346
cpp
C++
system-test/mxs1947_composite_roles.cpp
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
system-test/mxs1947_composite_roles.cpp
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
system-test/mxs1947_composite_roles.cpp
Daniel-Xu/MaxScale
35d12c0c9b75c4571dbbeb983c740de098661de6
[ "BSD-3-Clause" ]
null
null
null
/** * MXS-1947: Composite roles are not supported * * https://jira.mariadb.org/browse/MXS-1947 */ #include <maxtest/testconnections.hh> int main(int argc, char** argv) { TestConnections test(argc, argv); test.repl->connect(); auto prepare = { "DROP USER test@'%'", "CREATE USER test@'%' IDENTIFIED BY 'test';", "CREATE ROLE a;", "CREATE ROLE b;", "CREATE DATABASE db;", "GRANT ALL ON db.* TO a;", "GRANT a TO b;", "GRANT b TO test@'%';", "SET DEFAULT ROLE b FOR test@'%';" }; for (auto a : prepare) { execute_query_silent(test.repl->nodes[0], a); } // Wait for the users to replicate test.repl->sync_slaves(); test.tprintf("Connect with a user that has a composite role as the default role"); MYSQL* conn = open_conn_db(test.maxscales->rwsplit_port[0], test.maxscales->ip4(), "db", "test", "test"); test.expect(mysql_errno(conn) == 0, "Connection failed: %s", mysql_error(conn)); mysql_close(conn); auto cleanup = { "DROP DATABASE IF EXISTS db;", "DROP ROLE IF EXISTS a;", "DROP ROLE IF EXISTS b;", "DROP USER 'test'@'%';" }; for (auto a : cleanup) { execute_query_silent(test.repl->nodes[0], a); } return test.global_result; }
24.035714
109
0.571322
Daniel-Xu