hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses 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 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c0a85d85b9a9db48247620e73d9af2698fa24d24 | 3,101 | cpp | C++ | libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_copy_n.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_copy_n.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_copy_n.cpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file unit_test_fnd_algorithm_ranges_copy_n.cpp
*
* @brief ranges::copy_n のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/algorithm/ranges/copy_n.hpp>
#include <bksge/fnd/algorithm/ranges/equal.hpp>
#include <bksge/fnd/iterator/ranges/next.hpp>
#include <gtest/gtest.h>
#include "constexpr_test.hpp"
#include "ranges_test.hpp"
namespace bksge_algorithm_test
{
namespace ranges_copy_n_test
{
#define VERIFY(...) if (!(__VA_ARGS__)) { return false; }
inline BKSGE_CXX14_CONSTEXPR bool test01()
{
namespace ranges = bksge::ranges;
int const x[7] = { 1, 2, 3, 4, 5, 6, 7 };
{
int w[7] = {};
auto res = ranges::copy_n(x, -1, w);
VERIFY(res.in == x+0);
VERIFY(res.out == w+0);
}
{
int w[7] = {};
auto res = ranges::copy_n(x, 0, w);
VERIFY(res.in == x+0);
VERIFY(res.out == w+0);
}
{
int w[7] = {};
auto res = ranges::copy_n(x, 1, w);
VERIFY(res.in == x+1);
VERIFY(res.out == w+1);
int const y[7] = { 1, 0, 0, 0, 0, 0, 0 };
VERIFY(ranges::equal(w, y));
}
{
int w[7] = {};
auto res = ranges::copy_n(x, 7, w);
VERIFY(res.in == x+7);
VERIFY(res.out == w+7);
int const y[7] = { 1, 2, 3, 4, 5, 6, 7 };
VERIFY(ranges::equal(w, y));
}
return true;
}
template <
template <typename> class in_wrapper,
template <typename> class out_wrapper
>
inline BKSGE_CXX14_CONSTEXPR bool test02()
{
namespace ranges = bksge::ranges;
int x[7] = { 1, 2, 3, 4, 5, 6, 7 };
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), -1, rw.begin());
VERIFY(res.in == rx.begin());
VERIFY(res.out.m_ptr == w);
}
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), 0, rw.begin());
VERIFY(res.in == rx.begin());
VERIFY(res.out.m_ptr == w);
}
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), 1, rw.begin());
VERIFY(res.in == ranges::next(rx.begin(), 1));
VERIFY(res.out.m_ptr == w+1);
int const y[7] = { 1, 0, 0, 0, 0, 0, 0 };
VERIFY(ranges::equal(w, y));
}
{
int w[7] = {};
test_range<int, in_wrapper> rx(x);
test_range<int, out_wrapper> rw(w);
auto res = ranges::copy_n(rx.begin(), 7, rw.begin());
VERIFY(res.in == rx.end());
VERIFY(res.out == rw.end());
int const y[7] = { 1, 2, 3, 4, 5, 6, 7 };
VERIFY(ranges::equal(w, y));
}
return true;
}
#undef VERIFY
GTEST_TEST(AlgorithmTest, RangesCopyNTest)
{
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(test01());
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(
(test02<input_iterator_wrapper, output_iterator_wrapper>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(
(test02<random_access_iterator_wrapper, output_iterator_wrapper>()));
BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(
(test02<random_access_iterator_wrapper, random_access_iterator_wrapper>()));
}
} // namespace ranges_copy_n_test
} // namespace bksge_algorithm_test
| 25.418033 | 79 | 0.610448 | myoukaku |
c0ac3c7e1842e42aa82dc05fc477a5a50b9e0e4f | 400 | cpp | C++ | MaxConsecutiveOnes/main.cpp | warjiang/leetcode | 2c00b1406fc3680a7a0ecf1842b3544a0ca28185 | [
"MIT"
] | null | null | null | MaxConsecutiveOnes/main.cpp | warjiang/leetcode | 2c00b1406fc3680a7a0ecf1842b3544a0ca28185 | [
"MIT"
] | null | null | null | MaxConsecutiveOnes/main.cpp | warjiang/leetcode | 2c00b1406fc3680a7a0ecf1842b3544a0ca28185 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "Solution.cpp"
using namespace std;
void tranverseVector(vector<int> v){
for(int i = 0; i < v.size(); i++){
cout << v[i] << endl;
}
}
int main(){
Solution* s = new Solution;
int arr[] = {1,1,0,1,1,1};
vector<int> v(arr, arr+sizeof(arr)/sizeof(int));
int n = s->findMaxConsecutiveOnes(v);
cout << n << endl;
//tranverseVector(v);
return 0;
} | 20 | 49 | 0.625 | warjiang |
c0ae4574ae381f12ddf0c1ef0010c75694420436 | 10,944 | cpp | C++ | grasp_generation/graspitmodified_lm/SoQt-1.5.0/src/Inventor/Qt/SoQtMaterialList.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/SoQt-1.5.0/src/Inventor/Qt/SoQtMaterialList.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/SoQt-1.5.0/src/Inventor/Qt/SoQtMaterialList.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
#include <qmetaobject.h>
#include <Inventor/Qt/moc_SoQtMaterialList.icc>
#include <stdlib.h>
#include <Inventor/SbPList.h>
#include <Inventor/errors/SoDebugError.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/nodes/SoMaterial.h>
#include <soqtdefs.h>
#include <Inventor/Qt/SoQt.h>
#include <Inventor/Qt/SoAnyMaterialList.h>
#include <Inventor/Qt/SoQtMaterialList.h>
// *************************************************************************
/*!
\class SoQtMaterialList Inventor/Qt/SoQtMaterialList.h
\brief The SoQtMaterialList class is a component for adding material
selection to scene graph editors.
*/
// *************************************************************************
SOQT_OBJECT_SOURCE(SoQtMaterialList);
// *************************************************************************
/*!
Public constructor.
*/
SoQtMaterialList::SoQtMaterialList(
QWidget * parent,
const char * const name,
SbBool embed,
const char * const dir)
: inherited(parent, name, embed)
{
this->constructor(dir, TRUE);
} // SoQtMaterialList()
/*!
Protected constructor.
*/
SoQtMaterialList::SoQtMaterialList(// protected
QWidget * parent,
const char * const name,
SbBool embed,
const char * const dir,
SbBool build)
: inherited(parent, name, embed)
{
this->constructor(dir, build);
} // SoQtMaterialList()
/*!
Common constructor code.
*/
void
SoQtMaterialList::constructor(// private
const char * const dir,
const SbBool build)
{
this->common = new SoAnyMaterialList(dir);
this->setSize(SbVec2s(200, 300));
if (build) {
this->setClassName("SoQtMaterialList");
QWidget * materials = this->buildWidget(this->getParentWidget());
this->setBaseWidget(materials);
}
} // constructor()
/*!
Destructor.
*/
SoQtMaterialList::~SoQtMaterialList(
void)
{
delete this->common;
} // ~SoQtMaterialList()
// *************************************************************************
/*!
FIXME: write doc
*/
void
SoQtMaterialList::addCallback(
SoQtMaterialListCB * const callback,
void * const closure)
{
common->addCallback(callback, closure);
} // addCallback()
/*!
FIXME: write doc
*/
void
SoQtMaterialList::removeCallback(
SoQtMaterialListCB * const callback,
void * const closure)
{
common->removeCallback(callback, closure);
} // removeCallback()
// *************************************************************************
/*!
FIXME: write doc
*/
const char *
SoQtMaterialList::getDefaultWidgetName(// virtual, protected
void) const
{
static const char defaultWidgetName[] = "SoQtMaterialList";
return defaultWidgetName;
} // getDefaultWidgetName()
/*!
FIXME: write doc
*/
const char *
SoQtMaterialList::getDefaultTitle(// virtual, protected
void) const
{
static const char defaultTitle[] = "Material List";
return defaultTitle;
} // getDefaultTitle()
/*!
FIXME: write doc
*/
const char *
SoQtMaterialList::getDefaultIconTitle(// virtual, protected
void) const
{
static const char defaultIconTitle[] = "Material List";
return defaultIconTitle;
} // getDefaultIconTitle()
// *************************************************************************
/*!
FIXME: write doc
*/
QWidget *
SoQtMaterialList::buildWidget(// protected
QWidget * parent)
{
/*
// we're building pulldown menu automatically...
QWidget * root = XtVaCreateManagedWidget(this->getClassName(),
xmFormWidgetClass, parent,
NULL);
QWidget * menubar = XtVaCreateManagedWidget("menubar",
xmRowColumnWidgetClass, root,
XmNleftAttachment, XmATTACH_FORM,
XmNtopAttachment, XmATTACH_FORM,
XmNrightAttachment, XmATTACH_FORM,
XmNrowColumnType, XmMENU_BAR,
NULL);
QWidget * palettemenu = this->buildPulldownMenu(menubar);
SoQtMaterialDirectory * dir = common->getMaterialDirectory();
int group, materials;
XmStringTable list;
if (dir->numGroups > 0) {
group = dir->current;
materials = dir->groups[group]->numMaterials;
list = (XmStringTable) XtMalloc(sizeof(XmString) * materials);
for (int i = 0; i < materials; i++)
list[i] =
SoQt::encodeString(dir->groups[group]->materials[i]->name);
} else {
materials = 0;
list = NULL;
}
Arg argv[10];
int argc = 0;
XtSetArg(argv[argc], XmNleftAttachment, XmATTACH_FORM); argc++;
XtSetArg(argv[argc], XmNtopAttachment, XmATTACH_WIDGET); argc++;
XtSetArg(argv[argc], XmNtopWidget, menubar); argc++;
XtSetArg(argv[argc], XmNrightAttachment, XmATTACH_FORM); argc++;
XtSetArg(argv[argc], XmNbottomAttachment, XmATTACH_FORM); argc++;
XtSetArg(argv[argc], XmNselectionPolicy, XmSINGLE_SELECT); argc++;
XtSetArg(argv[argc], XmNscrollBarDisplayPolicy, XmSTATIC); argc++;
XtSetArg(argv[argc], XmNitems, list); argc++;
XtSetArg(argv[argc], XmNitemCount, materials); argc++;
this->listwidget = XmCreateScrolledList(root, "materials", argv, argc);
XtManageChild(this->listwidget);
XtAddCallback(this->listwidget, XmNdefaultActionCallback,
SoQtMaterialList::selection_cb, (void *) this);
for (int i = 0; i < materials; i++)
XmStringFree(list[i]);
XtFree((char *) list);
return root;
*/
return NULL;
} // buildWidget()
// *************************************************************************
/*!
\internal
FIXME: write doc
*/
void
SoQtMaterialList::selectionCallback(// private
int materialid)
{
materialid--; // get index
SoQtMaterialDirectory * data = common->getMaterialDirectory();
assert(materialid >= 0 &&
materialid < data->groups[data->current]->numMaterials);
const char * materialdata =
data->groups[data->current]->materials[materialid]->data;
SoInput reader;
if (data->flags & SOQT_BUILTIN_MATERIALS) {
reader.setBuffer((void *) materialdata, strlen(materialdata));
} else {
if (! reader.openFile(materialdata, FALSE)) {
SoDebugError::postWarning("SoQtMaterialList::selectionCallback",
"could not open file: \"%s\"", materialdata);
return;
}
}
SoNode * material = NULL;
if (! SoDB::read(&reader, material)) {
SoDebugError::postWarning("SoQtMaterialList::selectionCallback",
"failed to read material");
return;
}
if (! material) {
SoDebugError::postWarning("SoQtMaterialList::selectionCallback",
"read returned no data");
return;
}
material->ref();
if (! material->isOfType(SoMaterial::getClassTypeId())) {
SoDebugError::postWarning("SoQtMaterialList::selectionCallback",
"not a material node!");
material->unref();
return;
}
common->invokeCallbacks((SoMaterial *) material);
material->unref();
} // selectionCallback()
/*!
\internal
FIXME: write doc
*/
void
SoQtMaterialList::selection_cb(// static, private
QWidget *,
void * closure,
void * call_data)
{
/*
SoQtMaterialList * component = (SoQtMaterialList *) closure;
XmListCallbackStruct * data = (XmListCallbackStruct *) call_data;
component->selectionCallback(data->item_position);
*/
} // selection_cb()
// *************************************************************************
/*!
\internal
FIXME: write doc
*/
void
SoQtMaterialList::paletteMenuCallback(// private
QWidget * menuitem)
{
/*
SoQtMaterialDirectory * data = common->getMaterialDirectory();
int i, j;
for (i = 0; i < data->numGroups; i++) {
if (data->groups[i]->menuitem == menuitem) {
XmStringTable list = (XmStringTable) XtMalloc(sizeof(XmString) *
data->groups[i]->numMaterials);
for (j = 0; j < data->groups[i]->numMaterials; j++)
list[j] = SoQt::encodeString(data->groups[i]->materials[j]->name);
XtVaSetValues(this->listwidget,
XmNitemCount, data->groups[i]->numMaterials,
XmNitems, list,
NULL);
for (j = 0; j < data->groups[i]->numMaterials; j++)
XmStringFree(list[j]);
XtFree((char *) list);
data->current = i;
return;
}
}
*/
} // paletteMenuCallback()
/*!
\internal
FIXME: write doc
*/
void
SoQtMaterialList::palette_menu_cb(// static, private
QWidget * widget,
void * closure,
void *)
{
assert(closure != NULL);
SoQtMaterialList * component = (SoQtMaterialList *) closure;
component->paletteMenuCallback(widget);
} /* palette_menu_cb */
// *************************************************************************
/*!
This method builds the pulldown menu.
The current implementation demands that the \a parent argument should be
the menubar RowColumn widget - only the "Palettes" menubar button and the
pulldown menu is built by this method.
*/
QWidget *
SoQtMaterialList::buildPulldownMenu(// protected
QWidget * parent)
{
/*
QWidget * palettes = XtVaCreateManagedWidget("palettes",
xmCascadeButtonGadgetClass, parent,
XtVaTypedArg,
XmNlabelString, XmRString,
"Palettes", sizeof("Palettes") + 1,
NULL);
QWidget * shell = SoQt::getShellWidget(parent);
assert(shell != (Widget) NULL);
Visual * visual;
Colormap colormap;
int depth;
XtVaGetValues(shell,
XmNvisual, &visual,
XmNcolormap, &colormap,
XmNdepth, &depth,
NULL);
QWidget * menu =
XmVaCreateSimplePulldownMenu(parent, "materialsmenu", 0, NULL, NULL);
SoQtMaterialDirectory * data = common->getMaterialDirectory();
for (int i = 0; i < data->numGroups; i++) {
QWidget * item;
item = XtVaCreateManagedWidget(data->groups[i]->name,
xmPushButtonGadgetClass, menu,
XtVaTypedArg,
XmNlabelString, XmRString,
data->groups[i]->name, strlen(data->groups[i]->name) + 1,
NULL);
data->groups[i]->menuitem = item;
XtAddCallback(item, XmNactivateCallback,
SoQtMaterialList::palette_menu_cb, (void *) this);
}
return palettes;
*/
return NULL;
} // buildPulldownMenu()
// *************************************************************************
| 26.057143 | 76 | 0.631305 | KraftOreo |
c0b18217d10fea0be0191a63a200aa18e9f3ed3b | 444 | cpp | C++ | src/nexus_http_interface/src/nexus_http_interface/create_component.cpp | Nexusoft/LLL-HPP | e5eec2fc402ac222d5b81438f3f3e8e490ba869d | [
"MIT"
] | 1 | 2021-12-06T15:05:28.000Z | 2021-12-06T15:05:28.000Z | src/nexus_http_interface/src/nexus_http_interface/create_component.cpp | Nexusoft/Mining-Pool | 6b112a951088164c965bfd879fd097538de12aa9 | [
"MIT"
] | null | null | null | src/nexus_http_interface/src/nexus_http_interface/create_component.cpp | Nexusoft/Mining-Pool | 6b112a951088164c965bfd879fd097538de12aa9 | [
"MIT"
] | 1 | 2021-12-06T15:05:36.000Z | 2021-12-06T15:05:36.000Z | #include "nexus_http_interface/create_component.hpp"
#include "nexus_http_interface/component_impl.hpp"
namespace nexuspool {
namespace nexus_http_interface {
Component::Sptr create_component(std::shared_ptr<spdlog::logger> logger,
std::string wallet_ip,
std::string auth_user,
std::string auth_pw)
{
return std::make_shared<Component_impl>(std::move(logger), std::move(wallet_ip), std::move(auth_user), std::move(auth_pw));
}
}
}
| 26.117647 | 127 | 0.77027 | Nexusoft |
c0b22e9afc40aa14c293cad55ca091272311ddba | 5,413 | cpp | C++ | src/statespace/SO3.cpp | usc-csci-545/aikido | afd8b203c17cb0b05d7db436f8bffbbe2111a75a | [
"BSD-3-Clause"
] | null | null | null | src/statespace/SO3.cpp | usc-csci-545/aikido | afd8b203c17cb0b05d7db436f8bffbbe2111a75a | [
"BSD-3-Clause"
] | null | null | null | src/statespace/SO3.cpp | usc-csci-545/aikido | afd8b203c17cb0b05d7db436f8bffbbe2111a75a | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
#include <dart/math/Geometry.hpp>
#include <aikido/statespace/SO3.hpp>
namespace aikido {
namespace statespace {
//==============================================================================
SO3::SO3::State::State() : mValue(1., 0., 0., 0.)
{
}
//==============================================================================
SO3::SO3::State::State(const Quaternion& _quaternion) : mValue(_quaternion)
{
// TODO: Check if normalized.
}
//==============================================================================
auto SO3::State::getQuaternion() const -> const Quaternion&
{
return mValue;
}
//==============================================================================
void SO3::State::setQuaternion(const Quaternion& _quaternion)
{
// TODO: Check if normalized.
mValue = _quaternion;
}
//==============================================================================
auto SO3::createState() const -> ScopedState
{
return ScopedState(this);
}
//==============================================================================
auto SO3::cloneState(const StateSpace::State* stateIn) const -> ScopedState
{
auto newState = createState();
copyState(stateIn, newState);
return newState;
}
//==============================================================================
auto SO3::getQuaternion(const State* _state) const -> const Quaternion&
{
return _state->mValue;
}
//==============================================================================
void SO3::setQuaternion(State* _state, const Quaternion& _quaternion) const
{
_state->mValue = _quaternion;
}
//==============================================================================
std::size_t SO3::getStateSizeInBytes() const
{
return sizeof(State);
}
//==============================================================================
StateSpace::State* SO3::allocateStateInBuffer(void* _buffer) const
{
return new (_buffer) State;
}
//==============================================================================
void SO3::freeStateInBuffer(StateSpace::State* _state) const
{
static_cast<State*>(_state)->~State();
}
//==============================================================================
void SO3::compose(
const StateSpace::State* _state1,
const StateSpace::State* _state2,
StateSpace::State* _out) const
{
// TODO: Disable this in release mode.
if (_state1 == _out || _state2 == _out)
throw std::invalid_argument("Output aliases input.");
auto state1 = static_cast<const State*>(_state1);
auto state2 = static_cast<const State*>(_state2);
auto out = static_cast<State*>(_out);
out->mValue = state1->mValue * state2->mValue;
}
//==============================================================================
void SO3::getIdentity(StateSpace::State* _out) const
{
auto out = static_cast<State*>(_out);
setQuaternion(out, Quaternion::Identity());
}
//==============================================================================
void SO3::getInverse(
const StateSpace::State* _in, StateSpace::State* _out) const
{
// TODO: Disable this in release mode.
if (_out == _in)
throw std::invalid_argument("Output aliases input.");
auto in = static_cast<const State*>(_in);
auto out = static_cast<State*>(_out);
setQuaternion(out, getQuaternion(in).inverse());
}
//==============================================================================
std::size_t SO3::getDimension() const
{
return 3;
}
//==============================================================================
void SO3::copyState(
const StateSpace::State* _source, StateSpace::State* _destination) const
{
auto destination = static_cast<State*>(_destination);
auto source = static_cast<const State*>(_source);
setQuaternion(destination, getQuaternion(source));
}
//==============================================================================
void SO3::expMap(const Eigen::VectorXd& _tangent, StateSpace::State* _out) const
{
auto out = static_cast<State*>(_out);
// TODO: Skip these checks in release mode.
if (_tangent.rows() != 3)
{
std::stringstream msg;
msg << "_tangent has incorrect size: expected 3"
<< ", got " << _tangent.rows() << ".\n";
throw std::runtime_error(msg.str());
}
Eigen::Vector6d tangent(Eigen::Vector6d::Zero());
tangent.head<3>() = _tangent;
Eigen::Isometry3d transform = dart::math::expMap(tangent);
out->setQuaternion(Quaternion(transform.rotation()));
}
//==============================================================================
void SO3::logMap(const StateSpace::State* _in, Eigen::VectorXd& _tangent) const
{
if (_tangent.rows() != 3)
{
_tangent.resize(3);
}
auto in = static_cast<const State*>(_in);
// Compute rotation matrix from quaternion
Eigen::Matrix3d rotMat = getQuaternion(in).toRotationMatrix();
_tangent = dart::math::logMap(rotMat);
}
//==============================================================================
void SO3::print(const StateSpace::State* _state, std::ostream& _os) const
{
auto state = static_cast<const State*>(_state);
Eigen::IOFormat cleanFmt(
Eigen::StreamPrecision, Eigen::DontAlignCols, ",", ",", "", "", "[", "]");
auto quat = getQuaternion(state);
_os << Eigen::Vector4d(quat.w(), quat.x(), quat.y(), quat.z())
.format(cleanFmt);
}
} // namespace statespace
} // namespace aikido
| 30.240223 | 80 | 0.493257 | usc-csci-545 |
c0b3730a485cea58f9b7267d32eebe31173629f2 | 559 | hpp | C++ | src/local/LocalParamController.hpp | ademuri/colordance | ff1bec2096ca72ffeab4defaca188c05e452eedc | [
"MIT"
] | 1 | 2019-09-02T21:21:02.000Z | 2019-09-02T21:21:02.000Z | src/local/LocalParamController.hpp | ademuri/colordance | ff1bec2096ca72ffeab4defaca188c05e452eedc | [
"MIT"
] | null | null | null | src/local/LocalParamController.hpp | ademuri/colordance | ff1bec2096ca72ffeab4defaca188c05e452eedc | [
"MIT"
] | 1 | 2018-05-23T05:08:30.000Z | 2018-05-23T05:08:30.000Z | #ifndef __LOCAL_PARAM_CONTROLLER_HPP__
#define __LOCAL_PARAM_CONTROLLER_HPP__
#include <map>
#include "../controller/ParamController.hpp"
/**
* Reads params from a serial port, if present. Allows direct reading and
* setting params.
*/
class LocalParamController : public ParamController {
public:
LocalParamController();
int16_t Get(Params param) override;
void Set(Params param, int16_t val) override;
bool Boost() override;
void SetBoost(bool boost);
private:
std::map<const Params, int16_t> params;
bool boost = false;
};
#endif
| 19.964286 | 73 | 0.747764 | ademuri |
c0b5516f3e0580986004863dc2d8ac01f4e63195 | 32,072 | cc | C++ | chrome/browser/chromeos/file_system_provider/provided_file_system.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | chrome/browser/chromeos/file_system_provider/provided_file_system.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2016-07-11T15:19:20.000Z | 2017-04-02T20:38:55.000Z | chrome/browser/chromeos/file_system_provider/provided_file_system.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2014 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 "chrome/browser/chromeos/file_system_provider/provided_file_system.h"
#include <utility>
#include <vector>
#include "base/files/file.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/trace_event/trace_event.h"
#include "chrome/browser/chromeos/file_system_provider/notification_manager.h"
#include "chrome/browser/chromeos/file_system_provider/operations/abort.h"
#include "chrome/browser/chromeos/file_system_provider/operations/add_watcher.h"
#include "chrome/browser/chromeos/file_system_provider/operations/close_file.h"
#include "chrome/browser/chromeos/file_system_provider/operations/configure.h"
#include "chrome/browser/chromeos/file_system_provider/operations/copy_entry.h"
#include "chrome/browser/chromeos/file_system_provider/operations/create_directory.h"
#include "chrome/browser/chromeos/file_system_provider/operations/create_file.h"
#include "chrome/browser/chromeos/file_system_provider/operations/delete_entry.h"
#include "chrome/browser/chromeos/file_system_provider/operations/execute_action.h"
#include "chrome/browser/chromeos/file_system_provider/operations/get_actions.h"
#include "chrome/browser/chromeos/file_system_provider/operations/get_metadata.h"
#include "chrome/browser/chromeos/file_system_provider/operations/move_entry.h"
#include "chrome/browser/chromeos/file_system_provider/operations/open_file.h"
#include "chrome/browser/chromeos/file_system_provider/operations/read_directory.h"
#include "chrome/browser/chromeos/file_system_provider/operations/read_file.h"
#include "chrome/browser/chromeos/file_system_provider/operations/remove_watcher.h"
#include "chrome/browser/chromeos/file_system_provider/operations/truncate.h"
#include "chrome/browser/chromeos/file_system_provider/operations/unmount.h"
#include "chrome/browser/chromeos/file_system_provider/operations/write_file.h"
#include "chrome/browser/chromeos/file_system_provider/request_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/file_system_provider.h"
#include "extensions/browser/event_router.h"
namespace net {
class IOBuffer;
} // namespace net
namespace chromeos {
namespace file_system_provider {
namespace {
// Discards the result of Abort() when called from the destructor.
void EmptyStatusCallback(base::File::Error /* result */) {
}
} // namespace
AutoUpdater::AutoUpdater(const base::Closure& update_callback)
: update_callback_(update_callback),
created_callbacks_(0),
pending_callbacks_(0) {
}
base::Closure AutoUpdater::CreateCallback() {
++created_callbacks_;
++pending_callbacks_;
return base::Bind(&AutoUpdater::OnPendingCallback, this);
}
void AutoUpdater::OnPendingCallback() {
DCHECK_LT(0, pending_callbacks_);
if (--pending_callbacks_ == 0)
update_callback_.Run();
}
AutoUpdater::~AutoUpdater() {
// If no callbacks are created, then we need to invoke updating in the
// destructor.
if (!created_callbacks_)
update_callback_.Run();
else if (pending_callbacks_)
LOG(ERROR) << "Not all callbacks called. This may happen on shutdown.";
}
struct ProvidedFileSystem::AddWatcherInQueueArgs {
AddWatcherInQueueArgs(size_t token,
const GURL& origin,
const base::FilePath& entry_path,
bool recursive,
bool persistent,
const storage::AsyncFileUtil::StatusCallback& callback,
const storage::WatcherManager::NotificationCallback&
notification_callback)
: token(token),
origin(origin),
entry_path(entry_path),
recursive(recursive),
persistent(persistent),
callback(callback),
notification_callback(notification_callback) {}
~AddWatcherInQueueArgs() {}
const size_t token;
const GURL origin;
const base::FilePath entry_path;
const bool recursive;
const bool persistent;
const storage::AsyncFileUtil::StatusCallback callback;
const storage::WatcherManager::NotificationCallback notification_callback;
};
struct ProvidedFileSystem::NotifyInQueueArgs {
NotifyInQueueArgs(
size_t token,
const base::FilePath& entry_path,
bool recursive,
storage::WatcherManager::ChangeType change_type,
std::unique_ptr<ProvidedFileSystemObserver::Changes> changes,
const std::string& tag,
const storage::AsyncFileUtil::StatusCallback& callback)
: token(token),
entry_path(entry_path),
recursive(recursive),
change_type(change_type),
changes(std::move(changes)),
tag(tag),
callback(callback) {}
~NotifyInQueueArgs() {}
const size_t token;
const base::FilePath entry_path;
const bool recursive;
const storage::WatcherManager::ChangeType change_type;
const std::unique_ptr<ProvidedFileSystemObserver::Changes> changes;
const std::string tag;
const storage::AsyncFileUtil::StatusCallback callback;
private:
DISALLOW_COPY_AND_ASSIGN(NotifyInQueueArgs);
};
ProvidedFileSystem::ProvidedFileSystem(
Profile* profile,
const ProvidedFileSystemInfo& file_system_info)
: profile_(profile),
event_router_(extensions::EventRouter::Get(profile)), // May be NULL.
file_system_info_(file_system_info),
notification_manager_(
new NotificationManager(profile_, file_system_info_)),
request_manager_(new RequestManager(profile,
file_system_info.extension_id(),
notification_manager_.get())),
watcher_queue_(1),
weak_ptr_factory_(this) {
}
ProvidedFileSystem::~ProvidedFileSystem() {
const std::vector<int> request_ids = request_manager_->GetActiveRequestIds();
for (size_t i = 0; i < request_ids.size(); ++i) {
Abort(request_ids[i]);
}
}
void ProvidedFileSystem::SetEventRouterForTesting(
extensions::EventRouter* event_router) {
event_router_ = event_router;
}
void ProvidedFileSystem::SetNotificationManagerForTesting(
std::unique_ptr<NotificationManagerInterface> notification_manager) {
notification_manager_ = std::move(notification_manager);
request_manager_.reset(new RequestManager(
profile_, file_system_info_.extension_id(), notification_manager_.get()));
}
AbortCallback ProvidedFileSystem::RequestUnmount(
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
REQUEST_UNMOUNT,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::Unmount(event_router_, file_system_info_, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::GetMetadata(
const base::FilePath& entry_path,
MetadataFieldMask fields,
const GetMetadataCallback& callback) {
const int request_id = request_manager_->CreateRequest(
GET_METADATA,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::GetMetadata(event_router_, file_system_info_,
entry_path, fields, callback)));
if (!request_id) {
callback.Run(base::WrapUnique<EntryMetadata>(NULL),
base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::GetActions(
const std::vector<base::FilePath>& entry_paths,
const GetActionsCallback& callback) {
const int request_id = request_manager_->CreateRequest(
GET_ACTIONS,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::GetActions(event_router_, file_system_info_,
entry_paths, callback)));
if (!request_id) {
callback.Run(Actions(), base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(),
request_id);
}
AbortCallback ProvidedFileSystem::ExecuteAction(
const std::vector<base::FilePath>& entry_paths,
const std::string& action_id,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
EXECUTE_ACTION,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::ExecuteAction(event_router_, file_system_info_,
entry_paths, action_id, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(),
request_id);
}
AbortCallback ProvidedFileSystem::ReadDirectory(
const base::FilePath& directory_path,
const storage::AsyncFileUtil::ReadDirectoryCallback& callback) {
const int request_id = request_manager_->CreateRequest(
READ_DIRECTORY,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::ReadDirectory(event_router_, file_system_info_,
directory_path, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY,
storage::AsyncFileUtil::EntryList(),
false /* has_more */);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::ReadFile(
int file_handle,
net::IOBuffer* buffer,
int64_t offset,
int length,
const ReadChunkReceivedCallback& callback) {
TRACE_EVENT1(
"file_system_provider", "ProvidedFileSystem::ReadFile", "length", length);
const int request_id = request_manager_->CreateRequest(
READ_FILE, base::WrapUnique<RequestManager::HandlerInterface>(
new operations::ReadFile(event_router_, file_system_info_,
file_handle, buffer, offset,
length, callback)));
if (!request_id) {
callback.Run(0 /* chunk_length */,
false /* has_more */,
base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::OpenFile(const base::FilePath& file_path,
OpenFileMode mode,
const OpenFileCallback& callback) {
const int request_id = request_manager_->CreateRequest(
OPEN_FILE, std::unique_ptr<RequestManager::HandlerInterface>(
new operations::OpenFile(
event_router_, file_system_info_, file_path, mode,
base::Bind(&ProvidedFileSystem::OnOpenFileCompleted,
weak_ptr_factory_.GetWeakPtr(), file_path,
mode, callback))));
if (!request_id) {
callback.Run(0 /* file_handle */, base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(),
request_id);
}
AbortCallback ProvidedFileSystem::CloseFile(
int file_handle,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
CLOSE_FILE, std::unique_ptr<RequestManager::HandlerInterface>(
new operations::CloseFile(
event_router_, file_system_info_, file_handle,
base::Bind(&ProvidedFileSystem::OnCloseFileCompleted,
weak_ptr_factory_.GetWeakPtr(),
file_handle, callback))));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::CreateDirectory(
const base::FilePath& directory_path,
bool recursive,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
CREATE_DIRECTORY, std::unique_ptr<RequestManager::HandlerInterface>(
new operations::CreateDirectory(
event_router_, file_system_info_,
directory_path, recursive, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::DeleteEntry(
const base::FilePath& entry_path,
bool recursive,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
DELETE_ENTRY,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::DeleteEntry(event_router_, file_system_info_,
entry_path, recursive, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::CreateFile(
const base::FilePath& file_path,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
CREATE_FILE,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::CreateFile(event_router_, file_system_info_,
file_path, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::CopyEntry(
const base::FilePath& source_path,
const base::FilePath& target_path,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
COPY_ENTRY,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::CopyEntry(event_router_, file_system_info_,
source_path, target_path, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::WriteFile(
int file_handle,
net::IOBuffer* buffer,
int64_t offset,
int length,
const storage::AsyncFileUtil::StatusCallback& callback) {
TRACE_EVENT1("file_system_provider",
"ProvidedFileSystem::WriteFile",
"length",
length);
const int request_id = request_manager_->CreateRequest(
WRITE_FILE,
base::WrapUnique<RequestManager::HandlerInterface>(
new operations::WriteFile(event_router_, file_system_info_,
file_handle, make_scoped_refptr(buffer),
offset, length, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::MoveEntry(
const base::FilePath& source_path,
const base::FilePath& target_path,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
MOVE_ENTRY,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::MoveEntry(event_router_, file_system_info_,
source_path, target_path, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::Truncate(
const base::FilePath& file_path,
int64_t length,
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
TRUNCATE, std::unique_ptr<RequestManager::HandlerInterface>(
new operations::Truncate(event_router_, file_system_info_,
file_path, length, callback)));
if (!request_id) {
callback.Run(base::File::FILE_ERROR_SECURITY);
return AbortCallback();
}
return base::Bind(
&ProvidedFileSystem::Abort, weak_ptr_factory_.GetWeakPtr(), request_id);
}
AbortCallback ProvidedFileSystem::AddWatcher(
const GURL& origin,
const base::FilePath& entry_path,
bool recursive,
bool persistent,
const storage::AsyncFileUtil::StatusCallback& callback,
const storage::WatcherManager::NotificationCallback&
notification_callback) {
const size_t token = watcher_queue_.NewToken();
watcher_queue_.Enqueue(
token, base::Bind(&ProvidedFileSystem::AddWatcherInQueue,
base::Unretained(this), // Outlived by the queue.
AddWatcherInQueueArgs(token, origin, entry_path,
recursive, persistent, callback,
notification_callback)));
return AbortCallback();
}
void ProvidedFileSystem::RemoveWatcher(
const GURL& origin,
const base::FilePath& entry_path,
bool recursive,
const storage::AsyncFileUtil::StatusCallback& callback) {
const size_t token = watcher_queue_.NewToken();
watcher_queue_.Enqueue(
token, base::Bind(&ProvidedFileSystem::RemoveWatcherInQueue,
base::Unretained(this), // Outlived by the queue.
token, origin, entry_path, recursive, callback));
}
const ProvidedFileSystemInfo& ProvidedFileSystem::GetFileSystemInfo() const {
return file_system_info_;
}
RequestManager* ProvidedFileSystem::GetRequestManager() {
return request_manager_.get();
}
Watchers* ProvidedFileSystem::GetWatchers() {
return &watchers_;
}
const OpenedFiles& ProvidedFileSystem::GetOpenedFiles() const {
return opened_files_;
}
void ProvidedFileSystem::AddObserver(ProvidedFileSystemObserver* observer) {
DCHECK(observer);
observers_.AddObserver(observer);
}
void ProvidedFileSystem::RemoveObserver(ProvidedFileSystemObserver* observer) {
DCHECK(observer);
observers_.RemoveObserver(observer);
}
void ProvidedFileSystem::Notify(
const base::FilePath& entry_path,
bool recursive,
storage::WatcherManager::ChangeType change_type,
std::unique_ptr<ProvidedFileSystemObserver::Changes> changes,
const std::string& tag,
const storage::AsyncFileUtil::StatusCallback& callback) {
const size_t token = watcher_queue_.NewToken();
watcher_queue_.Enqueue(
token, base::Bind(&ProvidedFileSystem::NotifyInQueue,
base::Unretained(this), // Outlived by the queue.
base::Passed(base::WrapUnique(new NotifyInQueueArgs(
token, entry_path, recursive, change_type,
std::move(changes), tag, callback)))));
}
void ProvidedFileSystem::Configure(
const storage::AsyncFileUtil::StatusCallback& callback) {
const int request_id = request_manager_->CreateRequest(
CONFIGURE, std::unique_ptr<RequestManager::HandlerInterface>(
new operations::Configure(event_router_, file_system_info_,
callback)));
if (!request_id)
callback.Run(base::File::FILE_ERROR_SECURITY);
}
void ProvidedFileSystem::Abort(int operation_request_id) {
if (!request_manager_->CreateRequest(
ABORT, std::unique_ptr<RequestManager::HandlerInterface>(
new operations::Abort(
event_router_, file_system_info_, operation_request_id,
base::Bind(&ProvidedFileSystem::OnAbortCompleted,
weak_ptr_factory_.GetWeakPtr(),
operation_request_id))))) {
// If the aborting event is not handled, then the operation should simply
// be not aborted. Instead we'll wait until it completes.
LOG(ERROR) << "Failed to create an abort request.";
}
}
void ProvidedFileSystem::OnAbortCompleted(int operation_request_id,
base::File::Error result) {
if (result != base::File::FILE_OK) {
// If an error in aborting happens, then do not abort the request in the
// request manager, as the operation is supposed to complete. The only case
// it wouldn't complete is if there is a bug in the extension code, and
// the extension never calls the callback. We consiously *do not* handle
// bugs in extensions here.
return;
}
request_manager_->RejectRequest(operation_request_id,
base::WrapUnique(new RequestValue()),
base::File::FILE_ERROR_ABORT);
}
AbortCallback ProvidedFileSystem::AddWatcherInQueue(
const AddWatcherInQueueArgs& args) {
if (args.persistent && (!file_system_info_.supports_notify_tag() ||
!args.notification_callback.is_null())) {
OnAddWatcherInQueueCompleted(args.token, args.entry_path, args.recursive,
Subscriber(), args.callback,
base::File::FILE_ERROR_INVALID_OPERATION);
return AbortCallback();
}
// Create a candidate subscriber. This could be done in OnAddWatcherCompleted,
// but base::Bind supports only up to 7 arguments.
Subscriber subscriber;
subscriber.origin = args.origin;
subscriber.persistent = args.persistent;
subscriber.notification_callback = args.notification_callback;
const WatcherKey key(args.entry_path, args.recursive);
const Watchers::const_iterator it = watchers_.find(key);
if (it != watchers_.end()) {
const bool exists = it->second.subscribers.find(args.origin) !=
it->second.subscribers.end();
OnAddWatcherInQueueCompleted(
args.token, args.entry_path, args.recursive, subscriber, args.callback,
exists ? base::File::FILE_ERROR_EXISTS : base::File::FILE_OK);
return AbortCallback();
}
const int request_id = request_manager_->CreateRequest(
ADD_WATCHER,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::AddWatcher(
event_router_, file_system_info_, args.entry_path, args.recursive,
base::Bind(&ProvidedFileSystem::OnAddWatcherInQueueCompleted,
weak_ptr_factory_.GetWeakPtr(), args.token,
args.entry_path, args.recursive, subscriber,
args.callback))));
if (!request_id) {
OnAddWatcherInQueueCompleted(args.token, args.entry_path, args.recursive,
subscriber, args.callback,
base::File::FILE_ERROR_SECURITY);
}
return AbortCallback();
}
AbortCallback ProvidedFileSystem::RemoveWatcherInQueue(
size_t token,
const GURL& origin,
const base::FilePath& entry_path,
bool recursive,
const storage::AsyncFileUtil::StatusCallback& callback) {
const WatcherKey key(entry_path, recursive);
const Watchers::iterator it = watchers_.find(key);
if (it == watchers_.end() ||
it->second.subscribers.find(origin) == it->second.subscribers.end()) {
OnRemoveWatcherInQueueCompleted(token, origin, key, callback,
false /* extension_response */,
base::File::FILE_ERROR_NOT_FOUND);
return AbortCallback();
}
// If there are other subscribers, then do not remove the observer, but simply
// return a success.
if (it->second.subscribers.size() > 1) {
OnRemoveWatcherInQueueCompleted(token, origin, key, callback,
false /* extension_response */,
base::File::FILE_OK);
return AbortCallback();
}
// Otherwise, emit an event, and remove the watcher.
request_manager_->CreateRequest(
REMOVE_WATCHER,
std::unique_ptr<RequestManager::HandlerInterface>(
new operations::RemoveWatcher(
event_router_, file_system_info_, entry_path, recursive,
base::Bind(&ProvidedFileSystem::OnRemoveWatcherInQueueCompleted,
weak_ptr_factory_.GetWeakPtr(), token, origin, key,
callback, true /* extension_response */))));
return AbortCallback();
}
AbortCallback ProvidedFileSystem::NotifyInQueue(
std::unique_ptr<NotifyInQueueArgs> args) {
const WatcherKey key(args->entry_path, args->recursive);
const auto& watcher_it = watchers_.find(key);
if (watcher_it == watchers_.end()) {
OnNotifyInQueueCompleted(std::move(args), base::File::FILE_ERROR_NOT_FOUND);
return AbortCallback();
}
// The tag must be provided if and only if it's explicitly supported.
if (file_system_info_.supports_notify_tag() == args->tag.empty()) {
OnNotifyInQueueCompleted(std::move(args),
base::File::FILE_ERROR_INVALID_OPERATION);
return AbortCallback();
}
// It's illegal to provide a tag which is not unique.
if (!args->tag.empty() && args->tag == watcher_it->second.last_tag) {
OnNotifyInQueueCompleted(std::move(args),
base::File::FILE_ERROR_INVALID_OPERATION);
return AbortCallback();
}
// The object is owned by AutoUpdated, so the reference is valid as long as
// callbacks created with AutoUpdater::CreateCallback().
const ProvidedFileSystemObserver::Changes& changes_ref = *args->changes.get();
const storage::WatcherManager::ChangeType change_type = args->change_type;
scoped_refptr<AutoUpdater> auto_updater(
new AutoUpdater(base::Bind(&ProvidedFileSystem::OnNotifyInQueueCompleted,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(&args), base::File::FILE_OK)));
// Call all notification callbacks (if any).
for (const auto& subscriber_it : watcher_it->second.subscribers) {
const storage::WatcherManager::NotificationCallback& notification_callback =
subscriber_it.second.notification_callback;
if (!notification_callback.is_null())
notification_callback.Run(change_type);
}
// Notify all observers.
FOR_EACH_OBSERVER(ProvidedFileSystemObserver,
observers_,
OnWatcherChanged(file_system_info_,
watcher_it->second,
change_type,
changes_ref,
auto_updater->CreateCallback()));
return AbortCallback();
}
base::WeakPtr<ProvidedFileSystemInterface> ProvidedFileSystem::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void ProvidedFileSystem::OnAddWatcherInQueueCompleted(
size_t token,
const base::FilePath& entry_path,
bool recursive,
const Subscriber& subscriber,
const storage::AsyncFileUtil::StatusCallback& callback,
base::File::Error result) {
if (result != base::File::FILE_OK) {
callback.Run(result);
watcher_queue_.Complete(token);
return;
}
const WatcherKey key(entry_path, recursive);
const Watchers::iterator it = watchers_.find(key);
if (it != watchers_.end()) {
callback.Run(base::File::FILE_OK);
watcher_queue_.Complete(token);
return;
}
Watcher* const watcher = &watchers_[key];
watcher->entry_path = entry_path;
watcher->recursive = recursive;
watcher->subscribers[subscriber.origin] = subscriber;
FOR_EACH_OBSERVER(ProvidedFileSystemObserver,
observers_,
OnWatcherListChanged(file_system_info_, watchers_));
callback.Run(base::File::FILE_OK);
watcher_queue_.Complete(token);
}
void ProvidedFileSystem::OnRemoveWatcherInQueueCompleted(
size_t token,
const GURL& origin,
const WatcherKey& key,
const storage::AsyncFileUtil::StatusCallback& callback,
bool extension_response,
base::File::Error result) {
if (!extension_response && result != base::File::FILE_OK) {
watcher_queue_.Complete(token);
callback.Run(result);
return;
}
// Even if the extension returns an error, the callback is called with base::
// File::FILE_OK.
const auto it = watchers_.find(key);
DCHECK(it != watchers_.end());
DCHECK(it->second.subscribers.find(origin) != it->second.subscribers.end());
it->second.subscribers.erase(origin);
FOR_EACH_OBSERVER(ProvidedFileSystemObserver, observers_,
OnWatcherListChanged(file_system_info_, watchers_));
// If there are no more subscribers, then remove the watcher.
if (it->second.subscribers.empty())
watchers_.erase(it);
callback.Run(base::File::FILE_OK);
watcher_queue_.Complete(token);
}
void ProvidedFileSystem::OnNotifyInQueueCompleted(
std::unique_ptr<NotifyInQueueArgs> args,
base::File::Error result) {
if (result != base::File::FILE_OK) {
args->callback.Run(result);
watcher_queue_.Complete(args->token);
return;
}
// Check if the entry is still watched.
const WatcherKey key(args->entry_path, args->recursive);
const Watchers::iterator it = watchers_.find(key);
if (it == watchers_.end()) {
args->callback.Run(base::File::FILE_ERROR_NOT_FOUND);
watcher_queue_.Complete(args->token);
return;
}
it->second.last_tag = args->tag;
FOR_EACH_OBSERVER(ProvidedFileSystemObserver,
observers_,
OnWatcherTagUpdated(file_system_info_, it->second));
// If the watched entry is deleted, then remove the watcher.
if (args->change_type == storage::WatcherManager::DELETED) {
// Make a copy, since the |it| iterator will get invalidated on the last
// subscriber.
Subscribers subscribers = it->second.subscribers;
for (const auto& subscriber_it : subscribers) {
RemoveWatcher(subscriber_it.second.origin, args->entry_path,
args->recursive, base::Bind(&EmptyStatusCallback));
}
}
args->callback.Run(base::File::FILE_OK);
watcher_queue_.Complete(args->token);
}
void ProvidedFileSystem::OnOpenFileCompleted(const base::FilePath& file_path,
OpenFileMode mode,
const OpenFileCallback& callback,
int file_handle,
base::File::Error result) {
if (result != base::File::FILE_OK) {
callback.Run(file_handle, result);
return;
}
opened_files_[file_handle] = OpenedFile(file_path, mode);
callback.Run(file_handle, base::File::FILE_OK);
}
void ProvidedFileSystem::OnCloseFileCompleted(
int file_handle,
const storage::AsyncFileUtil::StatusCallback& callback,
base::File::Error result) {
// Closing files is final. Even if an error happened, we remove it from the
// list of opened files.
opened_files_.erase(file_handle);
callback.Run(result);
}
} // namespace file_system_provider
} // namespace chromeos
| 38.363636 | 85 | 0.67679 | Wzzzx |
c0b5561bc6ff68f760a1d06832f171148a86e135 | 3,998 | cpp | C++ | proyectofinal/TiempoDijkstra.cpp | Jofemago/Estructura-de-datos | 96e2fb5c3ff651a97ff5b2916e3b800e75f98b27 | [
"MIT"
] | null | null | null | proyectofinal/TiempoDijkstra.cpp | Jofemago/Estructura-de-datos | 96e2fb5c3ff651a97ff5b2916e3b800e75f98b27 | [
"MIT"
] | null | null | null | proyectofinal/TiempoDijkstra.cpp | Jofemago/Estructura-de-datos | 96e2fb5c3ff651a97ff5b2916e3b800e75f98b27 | [
"MIT"
] | null | null | null | #include "graph.hh"
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <ctime>
#include <random>
#include <ctime>
#include <cmath>
using namespace std;
void Hora(){
time_t tSac = time(NULL); // instante actual
tm tms = *localtime(&tSac);
cout << "hh:mm:ss " << tms.tm_hour << ":" << tms.tm_min << ":"
<< tms.tm_sec << endl;
cout << "dd-mm-aaaa: " << tms.tm_mday << "-" << tms.tm_mon+1 << "-"
<< tms.tm_year+1900 << endl;
}
int ObtenerNodo(const unordered_set<int> &NC,const int &pos){
int it = 0;
assert(pos < NC.size());
for( const int& h : NC){
if(it == pos){
return h;
}
it ++;
}
}
int main (){
random_device rDevice;
mt19937 rEngine(rDevice());
uniform_int_distribution<int> dist;
cout << "TODO USA"<< endl;
AdjList<int, int> g("USA-road-d.USA.gr",true);
cout << "El numero de Vertices es: " << g.numNodes() << endl;
cout << "El numero de Arcos es: " << g.numEdges() << endl;
cout << endl;
//------------------------------------------------------------
//Se escoge en este momento para disminuir la complejidad de kruskal y kargerMincut
unordered_map<pair<int,int>,int, WeightHash<int>, EdgeEqual<int>> TableEdges = g.getEdges();
cout << "CONVERTIMOS EL GRAFO A NO DIRIGIDO"<< endl;
Hora();
g.ConverToNotDirected();
cout << endl;
//---------------------------------------------------------------------------------------------------------------
cout << "CALCULAMOS LAS COMPONENTES CONEXAS" << endl;
Hora();
pair<int,int> BiggerCc = {1,0};//pareja de la componente conexa mas grande y su numero de elementos
int NumCc = 1;
unordered_map<int, int> CompConect = connectedComponents(g,BiggerCc,NumCc);
cout <<"El numero de componentes conexas es: "<< NumCc << endl;
cout <<"El numero de elementos que tiene la componente conexa mas grande es: "<< BiggerCc.second << endl;
cout << endl;
cout << "EL GRADO PROMEDIO ES: " << g.OutDegree() << endl;
//TIEMPO PROMEDIO DE DIJKSTRA
//------------------------------------------------------------------------------------------------------------
unordered_map<int,int> distancias;
unordered_map<int,int> padre;
unordered_map<int,bool> visited;
unordered_set<int> NodesComponentC;
int b =0;
for(const int& n: g.getNodes()){
if(CompConect[n] == BiggerCc.first){
NodesComponentC.insert(n);
padre[n] = n;
distancias[n] = numeric_limits<int>::max();
visited[n]=false;
}
}
clock_t result = 0;
int elements = 30;//numero de elementos con los que queremos scar la medida
for(int i = 0 ; i < elements ; i++){
int pos = dist(rEngine) % NodesComponentC.size();//del numero generado me devuelve un numero entre 0 - numnodes - 1
//cantidad de componentes de la CC mas grande
int NODO = ObtenerNodo(NodesComponentC,pos);
clock_t t=clock();
dijkstraDiameter(g,distancias,padre,visited,NODO,&b);
t=clock() - t ;
result += t;
}
result = result / elements;
cout <<"El tiempo promedio de Dijkstra sobre un nodo es: "<< (result/CLOCKS_PER_SEC) << " segundos" << endl;
cout <<"El tiempo del diametro sobre la componente es en promedio: " << ((result/CLOCKS_PER_SEC)) * NodesComponentC.size() << endl;
//---------------------------------------------------------------------------------------------------------------
//TIEMPO PROMEDIO DE EJECUCION DE KRUSKAL
random_device rD;
mt19937 rE(rD());
uniform_int_distribution<int> ale;
clock_t result2 = 0;
int veces = 30;
for(int i = 0; i < veces ; i++){
clock_t t=clock();
int n = KargerCut(g,TableEdges,CompConect , BiggerCc,rE ,ale);
t=clock() - t ;
result2 += t;
}
result2 = result2 / veces;
cout <<"El tiempo promedio de KRUSKAL sobre un grafo o Componente C es: "<< (result2/CLOCKS_PER_SEC) << " segundos" << endl;
cout <<"El tiempo del KARGERMINCUT sobre la componente es en promedio: " << ((result2/CLOCKS_PER_SEC)) * pow(BiggerCc.second,2) << endl;
}
| 34.765217 | 138 | 0.582791 | Jofemago |
c0b65582bb32698c2510ab746992245917b1b519 | 3,103 | cc | C++ | media/base/user_input_monitor.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | media/base/user_input_monitor.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | media/base/user_input_monitor.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2013 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 "media/base/user_input_monitor.h"
#include <utility>
#include "base/atomicops.h"
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
namespace media {
uint32_t ReadKeyPressMonitorCount(
const base::ReadOnlySharedMemoryMapping& readonly_mapping) {
if (!readonly_mapping.IsValid())
return 0;
// No ordering constraints between Load/Store operations, a temporary
// inconsistent value is fine.
return base::subtle::NoBarrier_Load(
reinterpret_cast<const base::subtle::Atomic32*>(
readonly_mapping.memory()));
}
void WriteKeyPressMonitorCount(
const base::WritableSharedMemoryMapping& writable_mapping,
uint32_t count) {
if (!writable_mapping.IsValid())
return;
// No ordering constraints between Load/Store operations, a temporary
// inconsistent value is fine.
base::subtle::NoBarrier_Store(
static_cast<base::subtle::Atomic32*>(writable_mapping.memory()), count);
}
#ifdef DISABLE_USER_INPUT_MONITOR
// static
std::unique_ptr<UserInputMonitor> UserInputMonitor::Create(
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner) {
return nullptr;
}
#endif // DISABLE_USER_INPUT_MONITOR
UserInputMonitor::UserInputMonitor() = default;
UserInputMonitor::~UserInputMonitor() = default;
UserInputMonitorBase::UserInputMonitorBase() {
DETACH_FROM_SEQUENCE(owning_sequence_);
}
UserInputMonitorBase::~UserInputMonitorBase() {
// |references_| may be non-zero as it's decremented due to Mojo messages from
// the renderer, and they may not reach the browser always in tests.
}
void UserInputMonitorBase::EnableKeyPressMonitoring() {
DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_);
if (++references_ == 1) {
StartKeyboardMonitoring();
DVLOG(2) << "Started keyboard monitoring.";
}
}
base::ReadOnlySharedMemoryRegion
UserInputMonitorBase::EnableKeyPressMonitoringWithMapping() {
DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_);
if (++references_ == 1) {
base::MappedReadOnlyRegion shmem =
base::ReadOnlySharedMemoryRegion::Create(sizeof(uint32_t));
if (!shmem.IsValid()) {
DVLOG(2) << "Error mapping key press count shmem.";
return base::ReadOnlySharedMemoryRegion();
}
key_press_count_region_ =
base::ReadOnlySharedMemoryRegion(std::move(shmem.region));
WriteKeyPressMonitorCount(shmem.mapping, 0u);
StartKeyboardMonitoring(std::move(shmem.mapping));
DVLOG(2) << "Started keyboard monitoring.";
}
return key_press_count_region_.Duplicate();
}
void UserInputMonitorBase::DisableKeyPressMonitoring() {
DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_);
DCHECK_NE(references_, 0u);
if (--references_ == 0) {
key_press_count_region_ = base::ReadOnlySharedMemoryRegion();
StopKeyboardMonitoring();
DVLOG(2) << "Stopped keyboard monitoring.";
}
}
} // namespace media
| 31.03 | 80 | 0.750564 | sarang-apps |
c0b700887c45e60309776b904abf5458b0837f04 | 3,267 | cpp | C++ | Projects/HW1P3/URLParser.cpp | iamjeffx/CSCE-463 | c9724a993909db2f9cb58e9835e8c0ec6efa49e5 | [
"MIT"
] | null | null | null | Projects/HW1P3/URLParser.cpp | iamjeffx/CSCE-463 | c9724a993909db2f9cb58e9835e8c0ec6efa49e5 | [
"MIT"
] | null | null | null | Projects/HW1P3/URLParser.cpp | iamjeffx/CSCE-463 | c9724a993909db2f9cb58e9835e8c0ec6efa49e5 | [
"MIT"
] | 1 | 2022-01-24T09:01:59.000Z | 2022-01-24T09:01:59.000Z | /** CSCE 463 Homework 1 Part 3: Spring 2021
*
Author: Jeffrey Xu
UIN: 527008162
Email: jeffreyxu@tamu.edu
Professor Dmitri Loguinov
Filename: URLParser.cpp
Definition of URLParser functions. Note that fragments are not included in this parser.
**/
#include "pch.h"
#include "URLParser.h"
using namespace std;
#define MAX_HOST_LEN 256
URLParser::URLParser(std::string url) {
// Set values to default values (except for URL)
reset(url);
};
URLParser::~URLParser() {
// Clear all fields to default values
reset("");
};
void URLParser::reset(string URL) {
this->url = URL;
this->host = "";
this->path = "/";
this->port = 80;
this->query = "";
};
int URLParser::parse() {
string URL = this->url;
// Check that the HTTP protocol is being used (HTTPS not considered at this stage)
if (URL.substr(0, 7) != "http://") {
reset("");
return -1;
}
// Remove the HTTP scheme and fragments
URL = URL.substr(7, (int)URL.size());
int fragmentIndex = (int)URL.find_first_of("#");
URL = URL.substr(0, fragmentIndex);
// Extract query
int queryIndex = (int)URL.find_first_of("?");
if (queryIndex != -1) {
setQuery(URL.substr(queryIndex, (int)URL.size()));
URL = URL.substr(0, queryIndex);
}
// Extract path
int pathIndex = (int)URL.find_first_of("/");
if (pathIndex != -1) {
setPath(URL.substr(pathIndex, (int)URL.size()));
URL = URL.substr(0, pathIndex);
}
// Extract host and port number
int portIndex = (int)URL.find_first_of(":");
if (portIndex == -1) {
setHost(URL);
}
else {
// No port specified
if (portIndex == URL.size() - 1) {
reset("");
return -2;
}
// Initialize port number
this->port = atoi(URL.substr((size_t)portIndex + 1, (int)URL.size()).c_str());
// Invalid port number provided (handles case if port number is negative or isn't numeric)
if (port <= 0) {
reset("");
return -2;
}
setHost(URL.substr(0, portIndex));
}
if (this->getHost().size() > MAX_HOST_LEN) {
return -1;
}
// URL successfully parsed
return 0;
};
string URLParser::generateQuery() {
// Concatenates path and query to generate the entire query
return getPath() + getQuery();
}
string URLParser::generateRequest(string requestType) {
// Generates entire HTTP request
string request = requestType + " " + generateQuery() + " HTTP/1.0\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
string URLParser::bonusGenerateRobotsRequest() {
string request = "HEAD /robots.txt HTTP/1.1\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
string URLParser::bonusGenerateRequest(string requestType) {
// Generates entire HTTP request
string request = requestType + " " + generateQuery() + " HTTP/1.1\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
}
string URLParser::generateRobotsRequest() {
string request = "HEAD /robots.txt HTTP/1.0\r\n";
request += "User-agent: JXCrawler/1.2\r\n";
request += "Host: " + getHost() + "\r\n";
request += "Connection: close\r\n\r\n";
return request;
} | 25.130769 | 92 | 0.655647 | iamjeffx |
c0b7a6df226bbee4791a4cd6732a3f240379872e | 6,489 | cpp | C++ | src/mf.cpp | durgeshra/libDAI-1 | f72414d4381e302c0655f4055dbf526c738bf485 | [
"BSD-2-Clause"
] | null | null | null | src/mf.cpp | durgeshra/libDAI-1 | f72414d4381e302c0655f4055dbf526c738bf485 | [
"BSD-2-Clause"
] | null | null | null | src/mf.cpp | durgeshra/libDAI-1 | f72414d4381e302c0655f4055dbf526c738bf485 | [
"BSD-2-Clause"
] | null | null | null | /* This file is part of libDAI - http://www.libdai.org/
*
* Copyright (c) 2006-2011, The libDAI 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 <iostream>
#include <sstream>
#include <map>
#include <set>
#include <dai/mf.h>
#include <dai/util.h>
namespace dai {
using namespace std;
void MF::setProperties( const PropertySet &opts ) {
DAI_ASSERT( opts.hasKey("tol") );
DAI_ASSERT( opts.hasKey("maxiter") );
props.tol = opts.getStringAs<Real>("tol");
props.maxiter = opts.getStringAs<size_t>("maxiter");
if( opts.hasKey("verbose") )
props.verbose = opts.getStringAs<size_t>("verbose");
else
props.verbose = 0U;
if( opts.hasKey("damping") )
props.damping = opts.getStringAs<Real>("damping");
else
props.damping = 0.0;
if( opts.hasKey("maxtime") )
props.maxtime = opts.getStringAs<double>("maxtime");
else
props.maxtime = INFINITY;
if( opts.hasKey("init") )
props.init = opts.getStringAs<Properties::InitType>("init");
else
props.init = Properties::InitType::UNIFORM;
if( opts.hasKey("updates") )
props.updates = opts.getStringAs<Properties::UpdateType>("updates");
else
props.updates = Properties::UpdateType::NAIVE;
}
PropertySet MF::getProperties() const {
PropertySet opts;
opts.set( "tol", props.tol );
opts.set( "maxiter", props.maxiter );
opts.set( "maxtime", props.maxtime );
opts.set( "verbose", props.verbose );
opts.set( "damping", props.damping );
opts.set( "init", props.init );
opts.set( "updates", props.updates );
return opts;
}
string MF::printProperties() const {
stringstream s( stringstream::out );
s << "[";
s << "tol=" << props.tol << ",";
s << "maxiter=" << props.maxiter << ",";
s << "maxtime=" << props.maxtime << ",";
s << "verbose=" << props.verbose << ",";
s << "init=" << props.init << ",";
s << "updates=" << props.updates << ",";
s << "damping=" << props.damping << "]";
return s.str();
}
void MF::construct() {
// create beliefs
_beliefs.clear();
_beliefs.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); ++i )
_beliefs.push_back( Factor( var(i) ) );
}
void MF::init() {
if( props.init == Properties::InitType::UNIFORM )
for( size_t i = 0; i < nrVars(); i++ )
_beliefs[i].fill( 1.0 );
else
for( size_t i = 0; i < nrVars(); i++ )
_beliefs[i].randomize();
}
Factor MF::calcNewBelief( size_t i ) {
Factor result;
bforeach( const Neighbor &I, nbV(i) ) {
Factor belief_I_minus_i;
bforeach( const Neighbor &j, nbF(I) ) // for all j in I \ i
if( j != i )
belief_I_minus_i *= _beliefs[j];
Factor f_I = factor(I);
if( props.updates == Properties::UpdateType::NAIVE )
f_I.takeLog(true);
Factor msg_I_i = (belief_I_minus_i * f_I).marginal( var(i), false );
if( props.updates == Properties::UpdateType::NAIVE )
result *= msg_I_i.exp();
else
result *= msg_I_i;
}
result.normalize();
return result;
}
Real MF::run() {
if( props.verbose >= 1 )
cerr << "Starting " << identify() << "...";
double tic = toc();
vector<size_t> update_seq;
update_seq.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); i++ )
update_seq.push_back( i );
// do several passes over the network until maximum number of iterations has
// been reached or until the maximum belief difference is smaller than tolerance
Real maxDiff = INFINITY;
for( _iters = 0; _iters < props.maxiter && maxDiff > props.tol && (toc()-tic)<props.maxtime; _iters++ ) {
random_shuffle( update_seq.begin(), update_seq.end(), rnd );
maxDiff = -INFINITY;
bforeach( const size_t &i, update_seq ) {
Factor nb = calcNewBelief( i );
if( nb.hasNaNs() ) {
cerr << name() << "::run(): ERROR: new belief of variable " << var(i) << " has NaNs!" << endl;
return 1.0;
}
if( props.damping != 0.0 )
nb = (nb^(1.0 - props.damping)) * (_beliefs[i]^props.damping);
maxDiff = std::max( maxDiff, dist( nb, _beliefs[i], DISTLINF ) );
_beliefs[i] = nb;
}
if( props.verbose >= 3 )
cerr << name() << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
}
if( maxDiff > _maxdiff )
_maxdiff = maxDiff;
if( props.verbose >= 1 ) {
if( maxDiff > props.tol ) {
if( props.verbose == 1 )
cerr << endl;
cerr << name() << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
} else {
if( props.verbose >= 3 )
cerr << name() << "::run: ";
cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
}
}
return maxDiff;
}
Factor MF::beliefV( size_t i ) const {
return _beliefs[i].normalized();
}
Factor MF::belief (const VarSet &ns) const {
if( ns.size() == 0 )
return Factor();
else if( ns.size() == 1 )
return beliefV( findVar( *(ns.begin()) ) );
else {
DAI_THROW(BELIEF_NOT_AVAILABLE);
return Factor();
}
}
vector<Factor> MF::beliefs() const {
vector<Factor> result;
for( size_t i = 0; i < nrVars(); i++ )
result.push_back( beliefV(i) );
return result;
}
Real MF::logZ() const {
Real s = 0.0;
for( size_t i = 0; i < nrVars(); i++ )
s -= beliefV(i).entropy();
for( size_t I = 0; I < nrFactors(); I++ ) {
Factor henk;
bforeach( const Neighbor &j, nbF(I) ) // for all j in I
henk *= _beliefs[j];
henk.normalize();
Factor piet;
piet = factor(I).log(true);
piet *= henk;
s -= piet.sum();
}
return -s;
}
void MF::init( const VarSet &ns ) {
for( size_t i = 0; i < nrVars(); i++ )
if( ns.contains(var(i) ) ) {
if( props.init == Properties::InitType::UNIFORM )
_beliefs[i].fill( 1.0 );
else
_beliefs[i].randomize();
}
}
} // end of namespace dai | 28.213043 | 169 | 0.540145 | durgeshra |
c0b8aea8fc3ce0dae9b3758dccf149f93ceff9f7 | 4,661 | cpp | C++ | cpp/test/frequency_queries_test.cpp | CarnaViire/training | 5a01a022167a88a9c90bc6db4e14347ad60ee9e4 | [
"Unlicense"
] | 3 | 2017-07-08T05:18:33.000Z | 2021-06-11T13:49:37.000Z | cpp/test/frequency_queries_test.cpp | kondratyev-nv/training | ed28507694bc2026867b67c26dc9c4a955b24fb4 | [
"Unlicense"
] | 44 | 2017-10-05T20:23:03.000Z | 2022-02-10T19:50:21.000Z | cpp/test/frequency_queries_test.cpp | CarnaViire/training | 5a01a022167a88a9c90bc6db4e14347ad60ee9e4 | [
"Unlicense"
] | 4 | 2017-10-06T19:29:55.000Z | 2022-01-04T23:25:18.000Z | #include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "helpers/file_based_test_helper.hpp"
#include "frequency_queries.hpp"
#include <vector>
using namespace std;
namespace fs = experimental::filesystem;
vector<int> make_queries(vector<pair<int, int>> const& queries) {
frequency_queries fq;
vector<int> actual_result;
for (auto& query : queries) {
switch (query.first) {
case 1:
fq.add(query.second);
break;
case 2:
fq.remove(query.second);
break;
case 3:
actual_result.push_back(fq.has_element_with_frequency(query.second) ? 1 : 0);
break;
default:
throw invalid_argument("unrecognized query type");
}
}
return actual_result;
}
TEST(frequency_queries, returns_zero_when_no_element_with_frequency_is_present) {
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {1, 1}, {3, 0}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {1, 1}, {3, 1}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {1, 1}, {3, 2}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {1, 1}, {3, 4}}), testing::ElementsAreArray({0}));
}
TEST(frequency_queries, returns_zero_when_no_elements_was_added) {
ASSERT_THAT(make_queries({{3, 0}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{3, 1}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{3, 2}}), testing::ElementsAreArray({0}));
}
TEST(frequency_queries, returns_zero_when_frequency_is_negative) {
ASSERT_THAT(make_queries({{3, 0}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{3, -1}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{3, -2}}), testing::ElementsAreArray({0}));
}
TEST(frequency_queries, returns_true_when_have_elements_with_expected_frequency) {
ASSERT_THAT(make_queries({{3, 4}, {2, 1003}, {1, 16}, {3, 1}}), testing::ElementsAreArray({0, 1}));
ASSERT_THAT(make_queries({{1, 5}, {1, 6}, {3, 2}, {1, 10}, {1, 10}, {1, 6}, {2, 5}, {3, 2}}),
testing::ElementsAreArray({0, 1}));
ASSERT_THAT(make_queries({{1, 3}, {2, 3}, {3, 2}, {1, 4}, {1, 5}, {1, 5}, {1, 4}, {3, 2}, {2, 4}, {3, 2}}),
testing::ElementsAreArray({0, 1, 1}));
}
TEST(frequency_queries, returns_true_when_have_multiple_elements_with_same_frequency) {
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {1, 2}, {1, 2}, {3, 2}}), testing::ElementsAreArray({1}));
}
TEST(frequency_queries, returns_true_when_have_different_elements_with_different_frequency) {
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {1, 2}, {1, 2}, {2, 2}, {3, 1}, {3, 2}}),
testing::ElementsAreArray({1, 1}));
}
TEST(frequency_queries, returns_false_when_elements_only_deleted) {
ASSERT_THAT(make_queries({{2, 1}, {2, 1}, {2, 2}, {2, 2}, {3, 0}, {3, 1}, {3, 2}}),
testing::ElementsAreArray({0, 0, 0}));
}
TEST(frequency_queries, returns_zero_when_elements_was_added_and_removed) {
ASSERT_THAT(make_queries({{1, 1}, {1, 2}, {2, 1}, {2, 2}, {3, 0}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{1, 1}, {1, 2}, {2, 1}, {2, 2}, {3, 1}}), testing::ElementsAreArray({0}));
ASSERT_THAT(make_queries({{1, 1}, {1, 2}, {2, 1}, {2, 2}, {3, 2}}), testing::ElementsAreArray({0}));
}
TEST(frequency_queries, returns_true_when_element_returned_to_collection) {
ASSERT_THAT(make_queries({{1, 1}, {1, 1}, {3, 2}, {2, 1}, {2, 1}, {2, 1}, {3, 0}, {1, 1}, {3, 1}}),
testing::ElementsAreArray({1, 0, 1}));
}
TEST(frequency_queries, returns_correct_result_for_large_input_from_file_01) {
auto queries = file_based_test_helper::read_test_resource<vector<pair<int, int>>>(
fs::path("frequency_queries") / "01.input", [](istream& input) {
int n = 0;
input >> n;
vector<pair<int, int>> values(n);
for (int i = 0; i < n; ++i) {
input >> values[i].first >> values[i].second;
}
return values;
});
auto expected_result = file_based_test_helper::read_test_resource<vector<int>>(
fs::path("frequency_queries") / "01.result", [](ifstream& input) {
int n = 0;
input >> n;
vector<int> values(n);
for (int i = 0; i < n; ++i) {
input >> values[i];
}
return values;
});
auto actual_result = make_queries(queries);
ASSERT_THAT(actual_result, testing::ContainerEq(expected_result));
}
| 41.247788 | 111 | 0.598155 | CarnaViire |
c0b9bc1b7d09c268d1fee8a9f49be94cc20c2e44 | 9,923 | cpp | C++ | Modules/Core/src/Controllers/mitkVtkLayerController.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2022-03-03T12:03:32.000Z | 2022-03-03T12:03:32.000Z | Modules/Core/src/Controllers/mitkVtkLayerController.cpp | zhaomengxiao/MITK | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2021-12-22T10:19:02.000Z | 2021-12-22T10:19:02.000Z | Modules/Core/src/Controllers/mitkVtkLayerController.cpp | zhaomengxiao/MITK_lancet | a09fd849a4328276806008bfa92487f83a9e2437 | [
"BSD-3-Clause"
] | 1 | 2020-11-27T09:41:18.000Z | 2020-11-27T09:41:18.000Z | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkVtkLayerController.h"
#include <algorithm>
#include <vtkObjectFactory.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRendererCollection.h>
mitk::VtkLayerController::vtkLayerControllerMapType mitk::VtkLayerController::s_LayerControllerMap;
mitk::VtkLayerController *mitk::VtkLayerController::GetInstance(vtkSmartPointer<vtkRenderWindow> renWin)
{
for (auto mapit = s_LayerControllerMap.begin(); mapit != s_LayerControllerMap.end(); ++mapit)
{
if ((*mapit).first == renWin)
return (*mapit).second;
}
return nullptr;
}
void mitk::VtkLayerController::AddInstance(vtkSmartPointer<vtkRenderWindow> renWin,
vtkSmartPointer<vtkRenderer> mitkSceneRenderer)
{
// ensure that no vtkRenderWindow is managed twice
mitk::VtkLayerController::RemoveInstance(renWin);
// instanciate controller, add it to the map
mitk::VtkLayerController *ControllerInstance = new mitk::VtkLayerController(renWin);
ControllerInstance->InsertSceneRenderer(mitkSceneRenderer);
s_LayerControllerMap.insert(vtkLayerControllerMapType::value_type(renWin, ControllerInstance));
}
void mitk::VtkLayerController::RemoveInstance(vtkSmartPointer<vtkRenderWindow> renWin)
{
auto mapit = s_LayerControllerMap.find(renWin);
if (mapit != s_LayerControllerMap.end())
{
delete mapit->second;
s_LayerControllerMap.erase(mapit);
}
}
mitk::VtkLayerController::VtkLayerController(vtkSmartPointer<vtkRenderWindow> renderWindow)
{
m_RenderWindow = renderWindow;
m_RenderWindow->Register(nullptr);
m_BackgroundRenderers.clear();
m_ForegroundRenderers.clear();
m_SceneRenderers.clear();
}
mitk::VtkLayerController::~VtkLayerController()
{
if (m_RenderWindow != nullptr)
{
m_RenderWindow->UnRegister(nullptr);
}
}
/**
* Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered in the background.
* With forceAbsoluteBackground set true a renderer can be placed at the absolute background of the scene.
* Multiple calls with forceAbsoluteBackground set true will set the latest registered renderer as background.
*/
void mitk::VtkLayerController::InsertBackgroundRenderer(vtkSmartPointer<vtkRenderer> renderer,
bool forceAbsoluteBackground)
{
if (renderer == nullptr)
return;
// Remove renderer if it already exists
RemoveRenderer(renderer);
if (forceAbsoluteBackground)
{
auto it = m_BackgroundRenderers.begin();
m_BackgroundRenderers.insert(it, renderer);
}
else
m_BackgroundRenderers.push_back(renderer);
UpdateLayers();
}
/**
* Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered in the foreground.
* With forceAbsoluteBackground set true a renderer can be placed at the absolute foreground of the scene.
* Multiple calls with forceAbsoluteForeground set true will set the latest registered renderer as foreground.
*/
void mitk::VtkLayerController::InsertForegroundRenderer(vtkSmartPointer<vtkRenderer> renderer,
bool forceAbsoluteForeground)
{
if (renderer == nullptr)
return;
// Remove renderer if it already exists
RemoveRenderer(renderer);
if (forceAbsoluteForeground)
{
auto it = m_ForegroundRenderers.begin();
m_ForegroundRenderers.insert(it, renderer);
}
else
m_ForegroundRenderers.push_back(renderer);
renderer->PreserveDepthBufferOn();
UpdateLayers();
}
/**
* Returns the Scene Renderer
*/
vtkSmartPointer<vtkRenderer> mitk::VtkLayerController::GetSceneRenderer()
{
if (m_SceneRenderers.size() > 0)
{
auto it = m_SceneRenderers.begin();
return (*it);
}
else
return nullptr;
}
/**
* Connects a VTK renderer with a vtk renderwindow. The renderer will be rendered between background renderers and
* foreground renderers.
*/
void mitk::VtkLayerController::InsertSceneRenderer(vtkSmartPointer<vtkRenderer> renderer)
{
if (renderer == nullptr)
return;
// Remove renderer if it already exists
RemoveRenderer(renderer);
m_SceneRenderers.push_back(renderer);
UpdateLayers();
}
/**
* A renderer which has been inserted via a insert... function can be removed from the vtkRenderWindow with
* RemoveRenderer.
*/
void mitk::VtkLayerController::RemoveRenderer(vtkSmartPointer<vtkRenderer> renderer)
{
RendererVectorType::iterator it;
// background layers
if (m_BackgroundRenderers.size() > 0)
{
it = std::find(m_BackgroundRenderers.begin(), m_BackgroundRenderers.end(), renderer);
if (it != m_BackgroundRenderers.end())
{
m_BackgroundRenderers.erase(it);
UpdateLayers();
return;
}
}
// scene layers
if (m_SceneRenderers.size() > 0)
{
it = std::find(m_SceneRenderers.begin(), m_SceneRenderers.end(), renderer);
if (it != m_SceneRenderers.end())
{
m_SceneRenderers.erase(it);
UpdateLayers();
return;
}
}
// foreground layers
if (m_ForegroundRenderers.size() > 0)
{
it = std::find(m_ForegroundRenderers.begin(), m_ForegroundRenderers.end(), renderer);
if (it != m_ForegroundRenderers.end())
{
m_ForegroundRenderers.erase(it);
UpdateLayers();
return;
}
}
}
/**
* Connects a VtkRenderWindow with the layer controller.
*/
void mitk::VtkLayerController::SetRenderWindow(vtkSmartPointer<vtkRenderWindow> renwin)
{
if (renwin != nullptr)
{
RendererVectorType::iterator it;
// Tell all renderers that there is a new renderwindow
for (it = m_BackgroundRenderers.begin(); it != m_BackgroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(renwin);
}
for (it = m_SceneRenderers.begin(); it != m_SceneRenderers.end(); ++it)
{
(*it)->SetRenderWindow(renwin);
}
for (it = m_ForegroundRenderers.begin(); it != m_ForegroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(renwin);
}
// Set the new RenderWindow
m_RenderWindow = renwin;
}
// Now sort renderers and add them to the renderwindow
UpdateLayers();
}
/**
* Returns true if a renderer has been inserted
*/
bool mitk::VtkLayerController::IsRendererInserted(vtkSmartPointer<vtkRenderer> renderer)
{
RendererVectorType::iterator it;
// background layers
if (m_BackgroundRenderers.size() > 0)
{
it = std::find(m_BackgroundRenderers.begin(), m_BackgroundRenderers.end(), renderer);
if (it != m_BackgroundRenderers.end())
{
return true;
}
}
// scene layers
if (m_SceneRenderers.size() > 0)
{
it = std::find(m_SceneRenderers.begin(), m_SceneRenderers.end(), renderer);
if (it != m_SceneRenderers.end())
{
return true;
}
}
// foreground layers
if (m_ForegroundRenderers.size() > 0)
{
it = std::find(m_ForegroundRenderers.begin(), m_ForegroundRenderers.end(), renderer);
if (it != m_ForegroundRenderers.end())
{
return true;
}
}
return false;
}
/**
* Internally used to sort all registered renderers and to connect the with the vtkRenderWindow.
* Mention that VTK Version 5 and above is rendering higher numbers in the background and VTK
* Verison < 5 in the foreground.
*/
void mitk::VtkLayerController::UpdateLayers()
{
// Remove all Renderers from renderwindow
vtkSmartPointer<vtkRendererCollection> v = m_RenderWindow->GetRenderers();
v->RemoveAllItems();
auto numberOfLayers =
static_cast<unsigned int>(m_BackgroundRenderers.size() + m_SceneRenderers.size() + m_ForegroundRenderers.size());
int currentLayerNumber;
bool traverseUpwards;
currentLayerNumber = 0;
traverseUpwards = true;
m_RenderWindow->SetNumberOfLayers(numberOfLayers);
RendererVectorType::iterator it;
// assign a layer number for the backround renderers
for (it = m_BackgroundRenderers.begin(); it != m_BackgroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(m_RenderWindow);
(*it)->SetLayer(currentLayerNumber);
m_RenderWindow->AddRenderer((*it));
if (traverseUpwards)
currentLayerNumber++;
else
currentLayerNumber--;
}
// assign a layer number for the scene renderers
for (it = m_SceneRenderers.begin(); it != m_SceneRenderers.end(); ++it)
{
(*it)->SetRenderWindow(m_RenderWindow);
(*it)->SetLayer(currentLayerNumber);
m_RenderWindow->AddRenderer((*it));
if (traverseUpwards)
currentLayerNumber++;
else
currentLayerNumber--;
}
// assign a layer number for the foreground renderers
for (it = m_ForegroundRenderers.begin(); it != m_ForegroundRenderers.end(); ++it)
{
(*it)->SetRenderWindow(m_RenderWindow);
(*it)->SetLayer(currentLayerNumber);
m_RenderWindow->AddRenderer((*it));
if (traverseUpwards)
currentLayerNumber++;
else
currentLayerNumber--;
}
}
/**
* Returns the number of renderers in the renderwindow.
*/
unsigned int mitk::VtkLayerController::GetNumberOfRenderers()
{
return static_cast<unsigned int>(m_BackgroundRenderers.size() + m_SceneRenderers.size() +
m_ForegroundRenderers.size());
}
void mitk::VtkLayerController::SetEraseForAllRenderers(int i)
{
this->m_RenderWindow->SetErase(i);
RendererVectorType::iterator it;
for (it = m_BackgroundRenderers.begin(); it != m_BackgroundRenderers.end(); ++it)
(*it)->SetErase(i);
for (it = m_SceneRenderers.begin(); it != m_SceneRenderers.end(); ++it)
(*it)->SetErase(i);
for (it = m_ForegroundRenderers.begin(); it != m_ForegroundRenderers.end(); ++it)
(*it)->SetErase(i);
}
| 29.709581 | 117 | 0.695354 | zhaomengxiao |
c0bb66c2a0e4b93c897664e3a62284459aeac8ee | 3,683 | cpp | C++ | libraries/animation/src/AnimStateMachine.cpp | stojce/hifi | 8e6c860a243131859c0706424097db56e6a604bd | [
"Apache-2.0"
] | null | null | null | libraries/animation/src/AnimStateMachine.cpp | stojce/hifi | 8e6c860a243131859c0706424097db56e6a604bd | [
"Apache-2.0"
] | null | null | null | libraries/animation/src/AnimStateMachine.cpp | stojce/hifi | 8e6c860a243131859c0706424097db56e6a604bd | [
"Apache-2.0"
] | null | null | null | //
// AnimStateMachine.cpp
//
// Created by Anthony J. Thibault on 9/2/15.
// Copyright (c) 2015 High Fidelity, Inc. All rights reserved.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AnimStateMachine.h"
#include "AnimUtil.h"
#include "AnimationLogging.h"
AnimStateMachine::AnimStateMachine(const QString& id) :
AnimNode(AnimNode::Type::StateMachine, id) {
}
AnimStateMachine::~AnimStateMachine() {
}
const AnimPoseVec& AnimStateMachine::evaluate(const AnimVariantMap& animVars, float dt, Triggers& triggersOut) {
QString desiredStateID = animVars.lookup(_currentStateVar, _currentState->getID());
if (_currentState->getID() != desiredStateID) {
// switch states
bool foundState = false;
for (auto& state : _states) {
if (state->getID() == desiredStateID) {
switchState(animVars, state);
foundState = true;
break;
}
}
if (!foundState) {
qCCritical(animation) << "AnimStateMachine could not find state =" << desiredStateID << ", referenced by _currentStateVar =" << _currentStateVar;
}
}
// evaluate currentState transitions
auto desiredState = evaluateTransitions(animVars);
if (desiredState != _currentState) {
switchState(animVars, desiredState);
}
assert(_currentState);
auto currentStateNode = _currentState->getNode();
assert(currentStateNode);
if (_duringInterp) {
_alpha += _alphaVel * dt;
if (_alpha < 1.0f) {
if (_poses.size() > 0 && _nextPoses.size() > 0 && _prevPoses.size() > 0) {
::blend(_poses.size(), &_prevPoses[0], &_nextPoses[0], _alpha, &_poses[0]);
}
} else {
_duringInterp = false;
_prevPoses.clear();
_nextPoses.clear();
}
}
if (!_duringInterp) {
_poses = currentStateNode->evaluate(animVars, dt, triggersOut);
}
return _poses;
}
void AnimStateMachine::setCurrentState(State::Pointer state) {
_currentState = state;
}
void AnimStateMachine::addState(State::Pointer state) {
_states.push_back(state);
}
void AnimStateMachine::switchState(const AnimVariantMap& animVars, State::Pointer desiredState) {
const float FRAMES_PER_SECOND = 30.0f;
auto prevStateNode = _currentState->getNode();
auto nextStateNode = desiredState->getNode();
_duringInterp = true;
_alpha = 0.0f;
float duration = std::max(0.001f, animVars.lookup(desiredState->_interpDurationVar, desiredState->_interpDuration));
_alphaVel = FRAMES_PER_SECOND / duration;
_prevPoses = _poses;
nextStateNode->setCurrentFrame(desiredState->_interpTarget);
// because dt is 0, we should not encounter any triggers
const float dt = 0.0f;
Triggers triggers;
_nextPoses = nextStateNode->evaluate(animVars, dt, triggers);
#if WANT_DEBUG
qCDebug(animation) << "AnimStateMachine::switchState:" << _currentState->getID() << "->" << desiredState->getID() << "duration =" << duration << "targetFrame =" << desiredState->_interpTarget;
#endif
_currentState = desiredState;
}
AnimStateMachine::State::Pointer AnimStateMachine::evaluateTransitions(const AnimVariantMap& animVars) const {
assert(_currentState);
for (auto& transition : _currentState->_transitions) {
if (animVars.lookup(transition._var, false)) {
return transition._state;
}
}
return _currentState;
}
const AnimPoseVec& AnimStateMachine::getPosesInternal() const {
return _poses;
}
| 32.026087 | 196 | 0.661146 | stojce |
c0bc5bd601d19ae6f45567e4e4a1c1bc75e73463 | 1,073 | hpp | C++ | 016_Full_K-means_Clustering/include/Cluster/K_means_rgb_uv_pic.hpp | DreamWaterFound/Codes | e7d80eb8bfd7d6f104abd18724cb4bface419233 | [
"WTFPL"
] | 13 | 2019-02-28T14:28:23.000Z | 2021-12-04T04:55:19.000Z | 016_Full_K-means_Clustering/include/Cluster/K_means_rgb_uv_pic.hpp | DreamWaterFound/Codes | e7d80eb8bfd7d6f104abd18724cb4bface419233 | [
"WTFPL"
] | 1 | 2019-09-07T09:00:50.000Z | 2019-12-04T02:13:25.000Z | 016_Full_K-means_Clustering/include/Cluster/K_means_rgb_uv_pic.hpp | DreamWaterFound/Codes | e7d80eb8bfd7d6f104abd18724cb4bface419233 | [
"WTFPL"
] | 1 | 2020-03-11T16:47:31.000Z | 2020-03-11T16:47:31.000Z | #ifndef __K_MEANS_RGB_UV_PIC_HPP__
#define __K_MEANS_RGB_UV_PIC_HPP__
#include "include/Cluster/K_means_rgb_pic.hpp"
class K_Means_RGB_UV : public K_Means_RGB
{
public:
K_Means_RGB_UV(size_t clusterNum, size_t itNum, double epson, size_t nHeight, size_t nWitdh, std::vector<RGB_PIXEL> vSamples)
:K_Means_RGB(clusterNum,itNum,epson,nHeight,nWitdh,vSamples)
{
;
}
protected:
double ComputeSamplesDistance(RGB_PIXEL s1,RGB_PIXEL s2)
{
//颜色的误差
double dr=s1.r-s2.r;
double dg=s1.g-s2.g;
double db=s1.b-s2.b;
double dist_rgb=(dr*dr+dg*dg+db*db);
//坐标的误差,使用欧式距离
double dist_pos=(s1.u-s2.u)*(s1.u-s2.u)+(s1.v-s2.v)*(s1.v-s2.v);
//REVIEW 在定义这里的距离度量函数的时候有没有考虑过,可以使用时间上的数据?如果一些点更加倾向于符合或者不符合相机运动,把他们聚类到一期?
// 以及,在目前的基础上,使用“聚类图像金字塔”,使用上层图像知道下层图像的聚类操作?
// 类似拓展思想:使用MaskRCNN这种预测特别小的图像(图像金字塔顶层的图像)来提供分类的指导依据(目的是提高实时性),然后在下面几层通过几何的方式逐步恢复聚类效果?
//使用三个差组成向量的均方根作为误差的度量
return sqrt(2*dist_rgb+dist_pos);
}
};
#endif //__K_MEANS_RGB_UV_PIC_HPP__ | 26.825 | 129 | 0.685927 | DreamWaterFound |
c0beae45e099e79ebba6d97e6a20b80f4d545863 | 3,362 | cpp | C++ | codebefore/2016.9.25.4.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | codebefore/2016.9.25.4.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | codebefore/2016.9.25.4.cpp | 1980744819/ACM-code | a697242bc963e682e552e655e3d78527e044e854 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<malloc.h>
#include<cmath>
#include<algorithm>
using namespace::std;
int m;
int n;
struct stu{
char c[200];
int num;
}s[10005];
bool comp(stu a,stu b){
if(strcmp(a.c,b.c)<0)
return true;
else
return false;
}
int main(){
while(~scanf("%d",&n)){
int i,j,k;
char ch[100];
int len;
char a[200];
m=0;
for(i=0;i<n;i++){
scanf("%s",ch);
len=strlen(ch);
k=0;
for(j=0;j<len;j++){
if(ch[j]<='9'&&ch[j]>='0'){
a[k]=ch[j];
k++;
}
else if(ch[j]=='-'){
continue;
}
else{
if(ch[j]=='A'||ch[j]=='B'||ch[j]=='C'){
a[k]='2';
k++;
}
else if(ch[j]=='D'||ch[j]=='E'||ch[j]=='F'){
a[k]='3';
k++;
}
else if(ch[j]=='G'||ch[j]=='H'||ch[j]=='I'){
a[k]='4';
k++;
}
else if(ch[j]=='J'||ch[j]=='K'||ch[j]=='L'){
a[k]='5';
k++;
}
else if(ch[j]=='M'||ch[j]=='N'||ch[j]=='O'){
a[k]='6';
k++;
}
else if(ch[j]=='P'||ch[j]=='R'||ch[j]=='S'){
a[k]='7';
k++;
}
else if(ch[j]=='T'||ch[j]=='U'||ch[j]=='V'){
a[k]='8';
k++;
}
else if(ch[j]=='W'||ch[j]=='X'||ch[j]=='Y'){
a[k]='9';
k++;
}
else continue;
}
}
a[k]='\0';
/*for(j=0;j<k;j++)
printf("%c",a[j]);
printf("\n");*/
int flag;
if(m==0){
strcpy(s[m].c,a);
s[m].num=1;
m++;
}
else{
flag=0;
for(j=0;j<m;j++){
if(strcmp(s[j].c,a)==0){
s[j].num++;
flag=1;
//printf("1111\n");
break;
}
}
if(!flag){
strcpy(s[m].c,a);
s[m].num=1;
m++;
//printf("2222\n");
}
}
//printf("%d\n",m);
}
sort(s,s+m-1,comp);
int flag;
flag=0;
for(i=0;i<m;i++){
if(s[i].num>1){
flag=1;
for(j=0;j<3;j++){
printf("%c",s[i].c[j]);
}
printf("-");
for(j=3;j<7;j++){
printf("%c",s[i].c[j]);
}
printf(" %d\n",s[i].num);
}
}
if(!flag)
printf("No duplicates.\n");
}
return 0;
}
| 26.062016 | 64 | 0.234979 | 1980744819 |
c0bf83e3248888e2752193872664437f5be09efd | 156 | cc | C++ | cmake/code_tests/rt_test.cc | liubangchen/seastar | 5bf108406ae79a5f30383bf8e498dd9d4b51d1a5 | [
"Apache-2.0"
] | 6,526 | 2015-09-22T16:47:59.000Z | 2022-03-31T07:31:07.000Z | cmake/code_tests/rt_test.cc | liubangchen/seastar | 5bf108406ae79a5f30383bf8e498dd9d4b51d1a5 | [
"Apache-2.0"
] | 925 | 2015-09-23T13:52:53.000Z | 2022-03-31T21:33:25.000Z | cmake/code_tests/rt_test.cc | liubangchen/seastar | 5bf108406ae79a5f30383bf8e498dd9d4b51d1a5 | [
"Apache-2.0"
] | 1,473 | 2015-09-22T23:19:04.000Z | 2022-03-31T21:09:00.000Z | extern "C" {
#include <signal.h>
#include <time.h>
}
int main() {
timer_t td;
struct sigevent sev;
timer_create(CLOCK_MONOTONIC, &sev, &td);
}
| 14.181818 | 45 | 0.628205 | liubangchen |
c0c015e72f7221a47940ac067cc945b5efa15aea | 4,423 | cpp | C++ | libraries/ui/src/Tooltip.cpp | mnafees/hifi | d8f0cfa89a1fdf7339bac6af984e940df6265006 | [
"Apache-2.0"
] | 2 | 2018-05-07T16:12:38.000Z | 2019-04-28T17:32:01.000Z | libraries/ui/src/Tooltip.cpp | mnafees/hifi | d8f0cfa89a1fdf7339bac6af984e940df6265006 | [
"Apache-2.0"
] | null | null | null | libraries/ui/src/Tooltip.cpp | mnafees/hifi | d8f0cfa89a1fdf7339bac6af984e940df6265006 | [
"Apache-2.0"
] | null | null | null | //
// Tooltip.cpp
// libraries/ui/src
//
// Created by Bradley Austin Davis on 2015/04/14
// Copyright 2015 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "Tooltip.h"
#include <QtCore/QJsonDocument>
#include <QtCore/QUuid>
#include <AccountManager.h>
#include <AddressManager.h>
HIFI_QML_DEF(Tooltip)
Tooltip::Tooltip(QQuickItem* parent) : QQuickItem(parent) {
connect(this, &Tooltip::titleChanged, this, &Tooltip::requestHyperlinkImage);
}
Tooltip::~Tooltip() {
}
void Tooltip::setTitle(const QString& title) {
if (title != _title) {
_title = title;
emit titleChanged();
}
}
void Tooltip::setDescription(const QString& description) {
if (description != _description) {
_description = description;
emit descriptionChanged();
}
}
void Tooltip::setImageURL(const QString& imageURL) {
if (imageURL != _imageURL) {
_imageURL = imageURL;
emit imageURLChanged();
}
}
QString Tooltip::showTip(const QString& title, const QString& description) {
const QString newTipId = QUuid().createUuid().toString();
Tooltip::show([&](QQmlContext*, QObject* object) {
object->setObjectName(newTipId);
object->setProperty("title", title);
object->setProperty("description", description);
});
return newTipId;
}
void Tooltip::closeTip(const QString& tipId) {
auto rootItem = DependencyManager::get<OffscreenUi>()->getRootItem();
QQuickItem* that = rootItem->findChild<QQuickItem*>(tipId);
if (that) {
that->deleteLater();
}
}
void Tooltip::requestHyperlinkImage() {
if (!_title.isEmpty()) {
// we need to decide if this is a place name - if so we should ask the API for the associated image
// and description (if we weren't given one via the entity properties)
const QString PLACE_NAME_REGEX_STRING = "^[0-9A-Za-z](([0-9A-Za-z]|-(?!-))*[^\\W_]$|$)";
QRegExp placeNameRegex(PLACE_NAME_REGEX_STRING);
if (placeNameRegex.indexIn(_title) != -1) {
// NOTE: I'm currently not 100% sure why the UI library needs networking, but it's linked for now
// so I'm leveraging that here to get the place preview. We could also do this from the interface side
// should the network link be removed from UI at a later date.
// we possibly have a valid place name - so ask the API for the associated info
auto accountManager = DependencyManager::get<AccountManager>();
JSONCallbackParameters callbackParams;
callbackParams.jsonCallbackReceiver = this;
callbackParams.jsonCallbackMethod = "handleAPIResponse";
accountManager->sendRequest(GET_PLACE.arg(_title),
AccountManagerAuth::None,
QNetworkAccessManager::GetOperation,
callbackParams);
}
}
}
void Tooltip::handleAPIResponse(QNetworkReply& requestReply) {
// did a preview image come back?
QJsonObject responseObject = QJsonDocument::fromJson(requestReply.readAll()).object();
QJsonObject dataObject = responseObject["data"].toObject();
const QString PLACE_KEY = "place";
if (dataObject.contains(PLACE_KEY)) {
QJsonObject placeObject = dataObject[PLACE_KEY].toObject();
const QString PREVIEWS_KEY = "previews";
const QString LOBBY_KEY = "lobby";
if (placeObject.contains(PREVIEWS_KEY) && placeObject[PREVIEWS_KEY].toObject().contains(LOBBY_KEY)) {
// we have previews - time to change the image URL
setImageURL(placeObject[PREVIEWS_KEY].toObject()[LOBBY_KEY].toString());
}
if (_description.isEmpty()) {
const QString DESCRIPTION_KEY = "description";
// we have an empty description - did a non-empty description come back?
if (placeObject.contains(DESCRIPTION_KEY)) {
QString placeDescription = placeObject[DESCRIPTION_KEY].toString();
if (!placeDescription.isEmpty()) {
// we got a non-empty description so change our description to that
setDescription(placeDescription);
}
}
}
}
}
| 34.023077 | 114 | 0.639611 | mnafees |
c0c2c49685701c60b8ec7776421c7f6384dd70cb | 7,204 | cpp | C++ | folly/test/BufferedAtomicTest.cpp | yuhonghong66/folly | 60895e074c104264dd26285e5846e80dc215184a | [
"Apache-2.0"
] | 1 | 2020-11-09T12:07:30.000Z | 2020-11-09T12:07:30.000Z | folly/test/BufferedAtomicTest.cpp | yuhonghong66/folly | 60895e074c104264dd26285e5846e80dc215184a | [
"Apache-2.0"
] | null | null | null | folly/test/BufferedAtomicTest.cpp | yuhonghong66/folly | 60895e074c104264dd26285e5846e80dc215184a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013-present Facebook, Inc.
*
* 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 <folly/test/BufferedAtomic.h>
#include <folly/SingletonThreadLocal.h>
#include <folly/portability/GFlags.h>
#include <folly/portability/GTest.h>
#include <random>
using namespace folly::test;
using DSched = DeterministicSchedule;
template <typename T>
class RecordBufferTest : public RecordBuffer<T> {
public:
void assertOldestAllowed(
size_t expected,
std::memory_order mo,
const ThreadTimestamps& acqRelOrder) {
size_t oldestAllowed = RecordBuffer<T>::getOldestAllowed(mo, acqRelOrder);
ASSERT_EQ(expected, RecordBuffer<T>::history_[oldestAllowed].val_);
}
};
struct DSchedTimestampTest : public DSchedTimestamp {
explicit DSchedTimestampTest(size_t v) : DSchedTimestamp(v) {}
};
TEST(BufferedAtomic, basic) {
RecordBufferTest<int> buf;
DSchedThreadId tid(0);
ThreadInfo threadInfo(tid);
ASSERT_TRUE(
threadInfo.acqRelOrder_.atLeastAsRecentAs(tid, DSchedTimestampTest(1)));
ASSERT_FALSE(
threadInfo.acqRelOrder_.atLeastAsRecentAs(tid, DSchedTimestampTest(2)));
// value stored is equal to ts at time of store
for (int i = 2; i < 12; i++) {
buf.store(tid, threadInfo, i, std::memory_order_relaxed);
}
ASSERT_TRUE(
threadInfo.acqRelOrder_.atLeastAsRecentAs(tid, DSchedTimestampTest(11)));
ASSERT_FALSE(
threadInfo.acqRelOrder_.atLeastAsRecentAs(tid, DSchedTimestampTest(12)));
ThreadTimestamps tts;
buf.assertOldestAllowed(2, std::memory_order_relaxed, tts);
tts.setIfNotPresent(tid, DSchedTimestampTest(8));
buf.assertOldestAllowed(8, std::memory_order_relaxed, tts);
tts.clear();
tts.setIfNotPresent(tid, DSchedTimestampTest(10));
buf.assertOldestAllowed(10, std::memory_order_relaxed, tts);
tts.clear();
tts.setIfNotPresent(tid, DSchedTimestampTest(115));
buf.assertOldestAllowed(11, std::memory_order_relaxed, tts);
}
TEST(BufferedAtomic, seq_cst) {
RecordBufferTest<int> buf;
DSchedThreadId tid(0);
ThreadInfo threadInfo(tid);
buf.store(tid, threadInfo, 0, std::memory_order_relaxed);
buf.store(tid, threadInfo, 1, std::memory_order_seq_cst);
buf.store(tid, threadInfo, 2, std::memory_order_relaxed);
ThreadTimestamps tts;
buf.assertOldestAllowed(0, std::memory_order_relaxed, tts);
buf.assertOldestAllowed(0, std::memory_order_acquire, tts);
buf.assertOldestAllowed(1, std::memory_order_seq_cst, tts);
}
TEST(BufferedAtomic, transitive_sync) {
RecordBufferTest<int> buf;
DSchedThreadId tid0(0);
DSchedThreadId tid1(1);
DSchedThreadId tid2(2);
ThreadInfo threadInfo0(tid0);
ThreadInfo threadInfo1(tid1);
ThreadInfo threadInfo2(tid2);
buf.store(tid0, threadInfo0, 0, std::memory_order_relaxed);
buf.store(tid0, threadInfo0, 1, std::memory_order_seq_cst);
int val = buf.load(tid1, threadInfo1, std::memory_order_seq_cst);
ASSERT_EQ(1, val);
buf.assertOldestAllowed(
0, std::memory_order_relaxed, threadInfo2.acqRelOrder_);
threadInfo2.acqRelOrder_.sync(threadInfo1.acqRelOrder_);
buf.assertOldestAllowed(
1, std::memory_order_relaxed, threadInfo2.acqRelOrder_);
}
TEST(BufferedAtomic, acq_rel) {
RecordBufferTest<int> buf;
DSchedThreadId tid0(0);
DSchedThreadId tid1(1);
ThreadInfo threadInfo0(tid0);
ThreadInfo threadInfo1(tid1);
buf.store(tid0, threadInfo0, 0, std::memory_order_relaxed);
buf.store(tid0, threadInfo0, 1, std::memory_order_release);
while (buf.load(tid1, threadInfo1, std::memory_order_relaxed) == 0) {
}
ASSERT_TRUE(threadInfo1.acqFenceOrder_.atLeastAsRecentAs(
tid0, DSchedTimestampTest(3)));
ASSERT_FALSE(threadInfo1.acqFenceOrder_.atLeastAsRecentAs(
tid0, DSchedTimestampTest(4)));
ASSERT_FALSE(
threadInfo1.acqRelOrder_.atLeastAsRecentAs(tid0, DSchedTimestampTest(1)));
}
TEST(BufferedAtomic, atomic_buffer_thread_create_join_sync) {
for (int i = 0; i < 32; i++) {
DSched sched(DSched::uniform(i));
DeterministicAtomicImpl<int, DeterministicSchedule, BufferedAtomic> x;
x.store(0, std::memory_order_relaxed);
x.store(1, std::memory_order_relaxed);
std::thread thread = DeterministicSchedule::thread([&]() {
ASSERT_EQ(1, x.load(std::memory_order_relaxed));
x.store(2, std::memory_order_relaxed);
});
DeterministicSchedule::join(thread);
thread = DeterministicSchedule::thread([&]() {
ASSERT_EQ(2, x.load(std::memory_order_relaxed));
x.store(3, std::memory_order_relaxed);
});
DeterministicSchedule::join(thread);
ASSERT_EQ(3, x.load(std::memory_order_relaxed));
}
}
TEST(BufferedAtomic, atomic_buffer_fence) {
for (int i = 0; i < 1024; i++) {
FOLLY_TEST_DSCHED_VLOG("seed: " << i);
DSched sched(DSched::uniform(i));
DeterministicMutex mutex;
mutex.lock();
DeterministicAtomicImpl<int, DeterministicSchedule, BufferedAtomic> x;
DeterministicAtomicImpl<int, DeterministicSchedule, BufferedAtomic> y;
DeterministicAtomicImpl<int, DeterministicSchedule, BufferedAtomic> z;
x.store(0, std::memory_order_relaxed);
y.store(0, std::memory_order_relaxed);
z.store(0, std::memory_order_relaxed);
std::thread threadA = DeterministicSchedule::thread([&]() {
x.store(1, std::memory_order_relaxed);
DeterministicSchedule::atomic_thread_fence(std::memory_order_release);
y.store(1, std::memory_order_relaxed);
mutex.lock();
ASSERT_EQ(1, z.load(std::memory_order_relaxed));
mutex.unlock();
});
std::thread threadB = DeterministicSchedule::thread([&]() {
while (y.load(std::memory_order_relaxed) != 1) {
}
DeterministicSchedule::atomic_thread_fence(std::memory_order_acquire);
ASSERT_EQ(1, x.load(std::memory_order_relaxed));
});
DeterministicSchedule::join(threadB);
z.store(1, std::memory_order_relaxed);
mutex.unlock();
DeterministicSchedule::join(threadA);
}
}
TEST(BufferedAtomic, single_thread_unguarded_access) {
DSched* sched = new DSched(DSched::uniform(0));
DeterministicAtomicImpl<int, DeterministicSchedule, BufferedAtomic> x(0);
delete sched;
x.store(1);
ASSERT_EQ(1, x.load());
}
TEST(BufferedAtomic, multiple_thread_unguarded_access) {
DSched* sched = new DSched(DSched::uniform(0));
DeterministicAtomicImpl<int, DeterministicSchedule, BufferedAtomic> x(0);
delete sched;
// simulate static construction/destruction or access to shared
// DeterministicAtomic in pthread_setspecific callbacks after
// DeterministicSchedule::beforeThreadAccess() has been run.
ASSERT_EQ(0, x.load());
auto t = std::thread(
[&]() { ASSERT_DEATH(x.store(1), "prev == std::thread::id()"); });
t.join();
}
| 32.745455 | 80 | 0.73126 | yuhonghong66 |
c0c2e51ef67a2a61b1673bba69cb9de169a89972 | 1,089 | hpp | C++ | libs/core/include/fcppt/type_traits/is_value.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/type_traits/is_value.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/type_traits/is_value.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// 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)
#ifndef FCPPT_TYPE_TRAITS_IS_VALUE_HPP_INCLUDED
#define FCPPT_TYPE_TRAITS_IS_VALUE_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace type_traits
{
/**
\brief Checks if the type behaves like a value type.
\ingroup fcppttypetraits
A type is a <em>value type</em> if it is not cv-qualified, it is not void, not
an array, not a function and not a reference. In essence, value types behave
normally regarding copying, moving and assignment.
*/
template<
typename Type
>
using is_value
=
std::integral_constant<
bool,
!std::is_void<
Type
>::value
&&
!std::is_array<
Type
>::value
&&
!std::is_function<
Type
>::value
&&
!std::is_reference<
Type
>::value
&&
!std::is_const<
Type
>::value
&&
!std::is_volatile<
Type
>::value
>;
}
}
#endif
| 16.753846 | 78 | 0.707989 | pmiddend |
c0c6351340585eb3f4d5f036d9ee6128112a4c4d | 4,167 | cpp | C++ | src/http/File.cpp | amoscykl98/Catrine | 300b3bcf33cedd73b634526a581a3fb82e4dd71e | [
"MIT"
] | 4 | 2019-03-22T23:26:49.000Z | 2020-10-14T11:53:26.000Z | src/http/File.cpp | amoscykl98/Catrine | 300b3bcf33cedd73b634526a581a3fb82e4dd71e | [
"MIT"
] | null | null | null | src/http/File.cpp | amoscykl98/Catrine | 300b3bcf33cedd73b634526a581a3fb82e4dd71e | [
"MIT"
] | null | null | null | /*************************************************************************
> File Name: File.cpp
> Author: amoscykl
> Mail: amoscykl@163.com
************************************************************************/
#include "File.h"
#include "Util.h"
#include "Iobuffer.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <fstream>
// 静态成员变量初始化
std::unordered_map<std::string, std::string> File::mime_ = {
{"default", "text/plain"},
{"html", "text/html"},
{"htm", "text/html"},
{"css", "text/css"},
{"js", "text/javascript"},
{"txt", "text/plain"},
{"csv", "text/csv"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"png", "image/png"},
{"gif", "image/gif"},
{"bmp", "image/bmp"},
{"ico", "image/x_icon"},
{"mp3", "audio/mp3"},
{"avi", "video/x-msvideo"},
{"json", "application/json"},
{"doc", "application/msword"},
{"doc", "application/msword"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pdf", "application/pdf"},
{"gz", "application/x-gzip"},
{"tar", "application/x-tar"}
};
File::File(std::string path) :
path_(path)
{
// 将路径后多余的斜杠去掉
if (path_[path_.size() - 1] == '/')
path_.pop_back();
exist_ = (stat(path_.c_str(), &file_stat_) == 0);
}
bool File::Exist()
{
return exist_;
}
bool File::IsFile()
{
if (!exist_)
return false;
return S_ISREG(file_stat_.st_mode);
}
bool File::IsDir()
{
if (!exist_)
return false;
return S_ISDIR(file_stat_.st_mode);
}
bool File::IsLink()
{
if (!exist_)
return false;
return S_ISLNK(file_stat_.st_mode);
}
Timestamp File::GetCreateTime()
{
if (!exist_)
return system_clock::now();
return Util::TimespecToTimestamp(file_stat_.st_ctim);
}
Timestamp File::GetModifyTime()
{
if (!exist_)
return system_clock::now();
return Util::TimespecToTimestamp(file_stat_.st_mtim);
}
std::string File::GetName()
{
std::string absolute_path = path_;
// 取路径最后一个斜杠后的内容
return absolute_path.erase(0, absolute_path.find_last_of("/") + 1);
}
std::string File::GetExt()
{
std::string name = GetName();
int p = name.find_last_of('.');
// 没有拓展名或者为空直接返回“”
if(p == -1 || p == (int)name.length() - 1)
return "";
else
{
std::string ext = name.substr(p + 1);
Util::ToLower(ext);
return ext;
}
}
std::string File::GetMimeType()
{
if (mime_.find(GetExt()) == mime_.end())
{
return mime_["default"];
}
return mime_[GetExt()];
}
off_t File::GetSize()
{
if(!exist_)
return 0;
return file_stat_.st_size;
}
std::string File::ReadAsText()
{
std::ifstream in(path_, std::ios_base::in);
if(!in)
return "";
// 将文件每一行内容读取出来添加到string中
std::string content = "";
std::string line;
while(!in.eof())
{
getline(in, line);
content += line;
content += '\n';
}
content.erase(content.end()-1);
return content;
}
std::vector<File> File::ListDir()
{
std::string absolute_path = path_;
DIR *ptr_dir;
struct dirent *dir_entry;
ptr_dir = opendir(absolute_path.c_str());
std::vector<File> files;
while((dir_entry = readdir(ptr_dir)) != NULL){
// 忽略"." & ".."
if(strcmp(dir_entry->d_name, ".") == 0 || strcmp(dir_entry->d_name, "..") == 0 )
continue;
// 创建文件或子目录的file类
files.push_back(File(absolute_path+"/"+dir_entry->d_name));
}
closedir(ptr_dir);
return files;
}
void File::ReadToBuffer(IOBuffer& buffer)
{
// 打开文件描述符
int src_fd = open(path_.c_str(), O_RDONLY, 0);
if (src_fd < 0)
{
close(src_fd);
return;
}
// 映射文件到内存中
void *mmap_ret = mmap(NULL, file_stat_.st_size, PROT_READ, MAP_PRIVATE, src_fd, 0);
close(src_fd);
if (mmap_ret == (void*)-1)
{
munmap(mmap_ret, file_stat_.st_size);
return;
}
// 读取文件
char *src_addr = static_cast<char*>(mmap_ret);
buffer.Append(src_addr, file_stat_.st_size);
// 取消映射
munmap(mmap_ret, file_stat_.st_size);
return;
}
| 21.152284 | 88 | 0.551956 | amoscykl98 |
c0c6fdce0e03179fef9911f56f741873be3dff85 | 15,491 | cpp | C++ | src/lexer/handlers.cpp | Zoxc/mirb | 14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6 | [
"BSD-3-Clause"
] | 10 | 2016-10-06T06:22:20.000Z | 2022-02-28T05:33:09.000Z | src/lexer/handlers.cpp | Zoxc/mirb | 14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6 | [
"BSD-3-Clause"
] | null | null | null | src/lexer/handlers.cpp | Zoxc/mirb | 14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6 | [
"BSD-3-Clause"
] | 3 | 2018-01-08T03:34:34.000Z | 2021-09-12T12:12:22.000Z | #include "lexer.hpp"
#include "../symbol-pool.hpp"
#include "../parser/parser.hpp"
#include "../tree/nodes.hpp"
namespace Mirb
{
bool Lexer::is_white()
{
return (input.in(1, 9) || input.in(11, 12) || input.in(14, 32));
}
void Lexer::white()
{
input++;
while(is_white())
input++;
restep(true);
}
bool Lexer::whitespace_after()
{
return input.in(1, 32);
}
void Lexer::unknown()
{
input++;
while(jump_table[input] == &Lexer::unknown)
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::NONE;
if (lexeme.length() == 1)
report(lexeme, "Invalid character '" + lexeme.string() + "'");
else
report(lexeme, "Invalid characters '" + lexeme.string() + "'");
restep();
}
void Lexer::skip_line()
{
input++;
if(input == '\n')
{
newline();
return restep();
}
else if(input == '\r')
{
carrige_return();
return restep();
}
input--;
unknown();
}
void Lexer::expand_to_unary()
{
if(input == '@')
{
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::operator_to_unary(lexeme.type);
}
}
void Lexer::parse_delimited_data(Lexeme::Type type)
{
InterpolateState state;
state.type = type;
state.opener = input;
state.terminator = delimiter_mapping.try_get(input, [&]{
return input;
});
if(input != '\0' || !process_null(&input, true))
input++;
parse_interpolate(&state, false);
}
void Lexer::left_shift_to_heredoc()
{
auto heredoc = new (memory_pool) Heredoc;
heredoc->scope = parser.scope;
if(input == '-')
{
input++;
heredoc->remove_ident = true;
}
else
heredoc->remove_ident = false;
CharArray name;
if(is_ident(input))
{
heredoc->type = 0;
while(is_ident(input))
{
name += input;
input++;
}
}
else
{
auto get_name = [&]() {
heredoc->type = input++;
if(input == heredoc->type)
{
input++;
const char_t *start = lexeme.start;
lexeme.start = &input - 2;
lexeme.stop = &input;
report(lexeme, "Expected heredoc delimiter");
lexeme.start = start;
return;
}
while(input != heredoc->type)
{
if(input == 0 && process_null(&input))
return;
if(input == '\n' || input == '\r')
{
lexeme.stop = &input;
report(lexeme, "Unterminated heredoc delimiter");
return;
}
name += input++;
}
input++;
};
switch(input)
{
case '`':
case '"':
case '\'':
get_name();
break;
default:
lexeme.stop = &input;
report(lexeme, "Expected heredoc delimiter");
return;
}
}
heredoc->name.set<MemoryPool>(name, memory_pool);
heredocs.push(heredoc);
heredoc->node = new (Tree::Fragment(*heredoc->scope->fragment)) Tree::HeredocNode;
lexeme.stop = &input;
heredoc->range = lexeme;
lexeme.type = Lexeme::HEREDOC;
lexeme.heredoc = heredoc->node;
}
void Lexer::mod_to_literal()
{
input.set(lexeme.start + 1);
switch(input)
{
case 'r':
input++;
return parse_delimited_data(Lexeme::REGEXP);
case 's':
input++;
return parse_delimited_data(Lexeme::SYMBOL);
case 'x':
input++;
return parse_delimited_data(Lexeme::COMMAND);
case 'Q':
input++;
return parse_delimited_data(Lexeme::STRING);
case 'q':
{
input++;
char_t opener = input;
char_t terminator = delimiter_mapping.try_get(input, [&]{
return input;
});
input++;
return parse_simple_string(opener, terminator, opener != terminator);
}
case 'w':
{
input++;
char_t opener = input;
char_t terminator = delimiter_mapping.try_get(input, [&]{
return input;
});
if(input == 0 && process_null(&input))
return;
input++;
CharArray result;
size_t nested = 0;
while(input != terminator || nested > 0)
{
if(opener != terminator)
{
if(input == opener)
nested++;
else if(input == terminator)
nested--;
}
switch(input)
{
case '\n':
result += input++;
process_newline(false, false);
break;
case '\r':
result += input++;
if(input == '\n')
result += input++;
process_newline(false, false);
break;
case 0:
if(process_null(&input))
{
lexeme.stop = &input;
report(lexeme, "Unterminated array literal");
goto exit_array_literal;
return;
}
// Fallthrough
default:
result += input++;
}
}
input++;
exit_array_literal:
lexeme.stop = &input;
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.data->tail.set<MemoryPool>(result, memory_pool);
lexeme.type = Lexeme::ARRAY;
return;
}
case 'W':
input++;
return parse_delimited_data(Lexeme::ARRAY);
default:
break;
}
if(is_alpha(input))
return;
return parse_delimited_data(Lexeme::STRING);
}
void Lexer::regexp_options()
{
while(is_char(input))
{
switch(input)
{
case 'i':
case 'm':
case 'u':
case 's':
case 'n':
case 'o':
case 'e':
case 'x':
break;
default:
report(range(&input, &input + 1), "Unknown regular expression option '" + CharArray(&input, 1) + "'");
}
input++;
}
}
void Lexer::div_to_regexp()
{
input.set(lexeme.start + 1);
InterpolateState state;
state.type = Lexeme::REGEXP;
state.terminator = state.opener = '/';
parse_interpolate(&state, false);
}
void Lexer::question_to_character()
{
CharArray result;
if(input == '\\')
{
input++;
bool dummy;
if(!parse_escape(result, true, false, dummy))
{
if(input == 0 && process_null(&input))
{
lexeme.stop = &input;
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.type = Lexeme::STRING;
report(lexeme, "Expected escape string");
return;
}
}
else
goto result;
}
else if(input == 0)
{
if(process_null(&input))
{
lexeme.stop = &input;
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.type = Lexeme::STRING;
report(lexeme, "Expected escape string");
return;
}
}
result = input++;
result:
lexeme.data = new (memory_pool) InterpolateData(memory_pool);
lexeme.data->tail.set<MemoryPool>(result, memory_pool);
lexeme.stop = &input;
lexeme.type = Lexeme::STRING;
}
bool Lexer::process_null(const char_t *input, bool expected)
{
bool result = (size_t)(input - input_str) >= length;
if(!result && !expected)
report_null();
return result;
}
void Lexer::null()
{
if(process_null(&input, true))
{
lexeme.stop = &input;
lexeme.type = Lexeme::END;
}
else
unknown();
}
void Lexer::parse_interpolate_heredoc(Heredoc *heredoc)
{
InterpolateState state;
state.type = heredoc->type == '`' ? Lexeme::COMMAND : Lexeme::STRING;
state.heredoc = heredoc;
parse_interpolate(&state, false);
heredoc->node->data = parser.parse_data(Lexeme::STRING);
}
bool Lexer::heredoc_terminates(Heredoc *heredoc)
{
const char_t *start = &input;
size_t line = lexeme.current_line;
const char_t *line_start = lexeme.current_line_start;
if(input == '\n')
{
input++;
line++;
line_start = &input;
}
else if(input == '\r')
{
input++;
line++;
if(input == '\n')
input++;
line_start = &input;
}
if(heredoc->remove_ident)
while(is_white())
input++;
const char_t *str = &input;
while(input != '\n' && input != '\r' && (input != 0 || !process_null(&input)))
input++;
if((size_t)&input - (size_t)str != heredoc->name.length)
{
input.set(start);
return false;
}
if(std::memcmp(str, heredoc->name.data, heredoc->name.length) == 0)
{
lexeme.current_line = line;
lexeme.current_line_start = line_start;
return true;
}
input.set(start);
return false;
}
void Lexer::process_comment()
{
if((std::strncmp((const char *)&input, "=begin", 6) == 0) && !is_ident((&input)[6]))
{
auto terminate = [&]() -> bool {
if((std::strncmp((const char *)&input, "=end", 4) == 0) && !is_ident((&input)[4]))
{
input.set(&input + 4);
return true;
}
else
return false;
};
while(true)
{
switch(input)
{
case '\r':
{
if(input == '\n')
input++;
lexeme.current_line++;
lexeme.current_line_start = &input;
if(terminate())
goto exit_comment;
break;
}
case '\n':
{
input++;
lexeme.current_line++;
lexeme.current_line_start = &input;
if(terminate())
goto exit_comment;
break;
}
case 0:
if(process_null(&input))
{
lexeme.stop = &input;
report(lexeme, "Unterminated multi-line comment");
goto exit_comment;
}
break;
default:
input++;
break;
}
}
exit_comment:;
}
}
void Lexer::process_newline(bool no_heredoc, bool allow_comment)
{
lexeme.current_line++;
lexeme.current_line_start = &input;
if(heredocs.size() && !no_heredoc)
{
Heredoc *heredoc = heredocs.pop();
Lexeme old = lexeme;
lexeme.start = &input;
lexeme.line = lexeme.current_line;
lexeme.line_start = lexeme.current_line_start;
parser.enter_scope(heredoc->scope, [&] {
parse_interpolate_heredoc(heredoc);
});
old.current_line = lexeme.current_line;
old.current_line_start = lexeme.current_line_start;
lexeme = old;
if(input == '\n')
newline();
else if(input == '\r')
carrige_return();
}
if(allow_comment)
process_comment();
}
void Lexer::newline()
{
input++;
lexeme.type = Lexeme::LINE;
process_newline(false, true);
lexeme.start = &input;
lexeme.stop = &input;
}
void Lexer::carrige_return()
{
input++;
lexeme.type = Lexeme::LINE;
if(input == '\n')
input++;
process_newline(false, true);
lexeme.start = &input;
lexeme.stop = &input;
}
void Lexer::eol()
{
while(input != '\n' && input != '\r' && input != 0)
input++;
}
void Lexer::curly_open()
{
input++;
lexeme.curlies.push(nullptr);
lexeme.stop = &input;
lexeme.type = Lexeme::CURLY_OPEN;
}
void Lexer::exclamation()
{
input++;
switch(input)
{
case '=':
{
input++;
lexeme.type = Lexeme::NO_EQUALITY;
break;
}
case '~':
{
input++;
lexeme.type = Lexeme::NOT_MATCHES;
break;
}
default:
{
lexeme.type = Lexeme::LOGICAL_NOT;
break;
}
}
lexeme.stop = &input;
}
void Lexer::colon()
{
input++;
if(input == ':')
{
input++;
lexeme.type = Lexeme::SCOPE;
}
else
lexeme.type = Lexeme::COLON;
lexeme.stop = &input;
}
void Lexer::assign_equal()
{
input++;
switch(input)
{
case '=':
{
input++;
if(input == '=')
{
input++;
lexeme.type = Lexeme::CASE_EQUALITY;
}
else
lexeme.type = Lexeme::EQUALITY;
break;
}
case '>':
{
input++;
lexeme.type = Lexeme::ASSOC;
break;
}
case '~':
{
input++;
lexeme.type = Lexeme::MATCHES;
break;
}
default:
{
lexeme.type = Lexeme::ASSIGN;
break;
}
}
lexeme.stop = &input;
}
void Lexer::compare()
{
input++;
switch(input)
{
case '<':
input++;
if(input == '=')
{
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::ASSIGN_LEFT_SHIFT;
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::LEFT_SHIFT;
}
break;
case '=':
input++;
if(input == '>')
{
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::COMPARE;
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::LESS_OR_EQUAL;
}
break;
default:
lexeme.stop = &input;
lexeme.type = Lexeme::LESS;
}
}
void Lexer::comment()
{
eol();
restep();
}
bool Lexer::is_char(char_t c)
{
return Input::char_in(c, 'a', 'z') || Input::char_in(c, 'A', 'Z');
}
bool Lexer::is_alpha(char_t c)
{
return is_char(c) || Input::char_in(c, '0', '9');
}
bool Lexer::is_start_ident(char_t c)
{
return is_char(c) || c == '_';
}
bool Lexer::is_ident(char_t c)
{
return is_start_ident(c) || Input::char_in(c, '0', '9');
}
void Lexer::skip_ident()
{
while(is_ident(input))
input++;
}
void Lexer::ivar()
{
input++;
if(is_ident(input))
{
bool error = !is_start_ident(input);
input++;
skip_ident();
lexeme.stop = &input;
lexeme.type = Lexeme::IVAR;
lexeme.symbol = symbol_pool.get(lexeme);
if(error)
report(lexeme, "Instance variable names cannot start with a number");
}
else if(input == '@')
{
input++;
if(is_ident(input))
{
bool error = !is_start_ident(input);
input++;
skip_ident();
lexeme.stop = &input;
lexeme.type = Lexeme::CVAR;
lexeme.symbol = symbol_pool.get(lexeme);
if(error)
report(lexeme, "Class variable names cannot start with a number");
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::CVAR;
lexeme.symbol = symbol_pool.get(lexeme);
report(lexeme, "Expected a class variable name");
}
}
else
{
lexeme.stop = &input;
lexeme.type = Lexeme::IVAR;
lexeme.symbol = symbol_pool.get(lexeme);
report(lexeme, "Expected a instance variable name");
}
}
void Lexer::global()
{
input++;
if(!is_ident(input))
{
switch(input)
{
case '-':
{
input++;
if(is_ident(input))
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
break;
};
case ':':
case '>':
case '<':
case '\\':
case '/':
case '@':
case '$':
case '`':
case '&':
case '_':
case '+':
case '.':
case ',':
case '~':
case ';':
case '"':
case '\'':
case '*':
case '?':
case '!':
input++;
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
break;
default:
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
report(lexeme, "Expected a global variable name");
break;
}
return;
}
skip_ident();
lexeme.stop = &input;
lexeme.type = Lexeme::GLOBAL;
lexeme.symbol = symbol_pool.get(lexeme);
}
void Lexer::sub()
{
input++;
switch(input)
{
case '=':
{
input++;
lexeme.type = Lexeme::ASSIGN_SUB;
break;
}
case '>':
{
input++;
lexeme.type = Lexeme::BLOCK_POINT;
break;
}
default:
lexeme.type = Lexeme::SUB;
}
lexeme.stop = &input;
}
void Lexer::ident()
{
input++;
skip_ident();
switch(input)
{
case '?':
case '!':
{
input++;
lexeme.type = Lexeme::EXT_IDENT;
break;
}
default:
{
lexeme.type = Lexeme::IDENT;
break;
}
}
lexeme.stop = &input;
lexeme.symbol = symbol_pool.get(lexeme);
if(lexeme.allow_keywords)
{
Lexeme::Type keyword = keywords.mapping.try_get(lexeme.symbol, [] { return Lexeme::NONE; });
if(keyword != Lexeme::NONE)
lexeme.type = keyword;
}
}
};
| 16.05285 | 107 | 0.556646 | Zoxc |
c0c89e38a9d4bd865f6e0071a68f7328077bd4d3 | 633 | cpp | C++ | src/Distance.cpp | SeanStarkey/map-utilities | bb3b29722c24a784d3f3ad34947042fb7449a1f0 | [
"Apache-2.0"
] | 1 | 2015-06-03T21:59:01.000Z | 2015-06-03T21:59:01.000Z | src/Distance.cpp | SeanStarkey/map-utilities | bb3b29722c24a784d3f3ad34947042fb7449a1f0 | [
"Apache-2.0"
] | null | null | null | src/Distance.cpp | SeanStarkey/map-utilities | bb3b29722c24a784d3f3ad34947042fb7449a1f0 | [
"Apache-2.0"
] | null | null | null |
#include "Distance.h"
#include <math.h>
#include <iostream>
#include "Constants.h"
double distance(const Location* c1, const Location* c2)
{
double dLat = toRadians(c1->getLatitude() - c2->getLatitude());
double dLon = toRadians(c1->getLongitude() - c2->getLongitude());
double lat1 = toRadians(c1->getLatitude());
double lat2 = toRadians(c2->getLatitude());
double halfdLatSin = sin(dLat/2.0);
double halfdLonSin = sin(dLon/2.0);
double a = halfdLatSin * halfdLatSin +
halfdLonSin * halfdLonSin * cos(lat1) * cos(lat2);
double c = 2*atan2(sqrt(a), sqrt(1-a));
return RADIUSEARTH*c;
}
| 28.772727 | 69 | 0.661927 | SeanStarkey |
c0ca738618fb5e4a9c73eeafd585d3fffad04815 | 979 | cpp | C++ | Neps/Problems/Chuva (OBI 2019) - 469.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | Neps/Problems/Chuva (OBI 2019) - 469.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | Neps/Problems/Chuva (OBI 2019) - 469.cpp | lucaswilliamgomes/QuestionsCompetitiveProgramming | f0a2cf42bb5a00e5d677b7f3211ac399fe2bf6a0 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main () {
int N, M;
cin >> N >> M;
char matrix [1010][1010];
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
cin >> matrix[i][j];
}
}
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
if (matrix[i][j] == '.'){
if ((i > 0 && matrix[i-1][j] == 'o') or
(i < N - 1 && j > 0 && matrix[i][j-1] == 'o' and matrix[i+1][j-1] == '#') or
(i < N - 1 && j < M - 1 && matrix[i][j+1] == 'o' and matrix[i+1][j+1] == '#')) {
matrix[i][j] = 'o';
if (j > 0)
j-=2;
}
}
}
}
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
cout << matrix[i][j];
}
cout << endl;
}
return 0;
} | 23.309524 | 97 | 0.277835 | lucaswilliamgomes |
c0d23f9d5daaa8201bc8f80be15c345e6a5a3a70 | 909 | cpp | C++ | tests/Polytope/NormalizePolytopeTestSuite.cpp | modsim/hops | 4285dd75a07dd844295440a0756b3ba25f5819ac | [
"MIT"
] | 7 | 2020-11-26T05:13:03.000Z | 2022-01-12T02:08:40.000Z | tests/Polytope/NormalizePolytopeTestSuite.cpp | modsim/hops | 4285dd75a07dd844295440a0756b3ba25f5819ac | [
"MIT"
] | 1 | 2021-02-20T23:16:34.000Z | 2021-02-20T23:16:34.000Z | tests/Polytope/NormalizePolytopeTestSuite.cpp | modsim/hops | 4285dd75a07dd844295440a0756b3ba25f5819ac | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE NormalizePolytopeTestSuite
#define BOOST_TEST_DYN_LINK
#include <boost/test/included/unit_test.hpp>
#include <cmath>
#include <hops/Polytope/NormalizePolytope.hpp>
BOOST_AUTO_TEST_SUITE(NormalizePolytope)
BOOST_AUTO_TEST_CASE(NormalizeSimplex) {
Eigen::MatrixXd expectedA(4, 3);
expectedA << 1. / std::sqrt(3), 1. / std::sqrt(3), 1. / std::sqrt(3),
1, 0, 0,
0, 1, 0,
0, 0, 1;
Eigen::VectorXd expectedB(4);
expectedB << 1. / std::sqrt(3), 1, 1, 1;
Eigen::MatrixXd A(4, 3);
A << 1, 1, 1,
1, 0, 0,
0, 1, 0,
0, 0, 1;
Eigen::VectorXd b = Eigen::VectorXd::Ones(4);
hops::normalizePolytope(A, b);
BOOST_CHECK(A.isApprox(expectedA));
BOOST_CHECK(b.isApprox(expectedB));
}
BOOST_AUTO_TEST_SUITE_END()
| 27.545455 | 77 | 0.566557 | modsim |
c0d3b7e4daae0a18dda73585d91461202d75845e | 6,336 | hpp | C++ | include/Bit/Graphics/TextureProperties.hpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | include/Bit/Graphics/TextureProperties.hpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | include/Bit/Graphics/TextureProperties.hpp | jimmiebergmann/Bit-Engine | 39324a9e7fb5ab4b1cf3738f871470e0a9ef7575 | [
"Zlib"
] | null | null | null | // ///////////////////////////////////////////////////////////////////////////
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com
//
// This software is provided 'as-is', without any express or
// implied warranty. In no event will the authors be held
// liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute
// it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but
// is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any
// source distribution.
// ///////////////////////////////////////////////////////////////////////////
#ifndef BIT_GRAPHICS_TEXTURE_PROPERTIES_HPP
#define BIT_GRAPHICS_TEXTURE_PROPERTIES_HPP
#include <Bit/Build.hpp>
#include <Bit/NonCopyable.hpp>
namespace Bit
{
////////////////////////////////////////////////////////////////
/// \ingroup Graphics
/// \brief Texture properties class.
///
/// Flag bits:
/// - 0x01 Magnification filter.
/// - 0x02 Minification filter.
/// - 0x04 Wrapping X.
/// - 0x08 Wrapping Y.
/// - 0x10 Anisotrpical level.
///
////////////////////////////////////////////////////////////////
class BIT_API TextureProperties : public NonCopyable
{
public:
////////////////////////////////////////////////////////////////
/// \brief Filter enumerator
///
/// Do not use mipmap filters for magnification.
///
////////////////////////////////////////////////////////////////
enum eFilter
{
Nearest, ///< Nearest neighbor blending.
NearestMipmapNearest, ///< Not linear within mip-level.
NearestMipmapLinear, ///< Same as previous, but linear between mip-levels.
Linear, ///< Linear blend between texels.
LinearMipmapNearest, ///< Linear within mip-level.
LinearMipmapLinear ///< Same as previous, but linear between mip-levels.
};
////////////////////////////////////////////////////////////////
/// \brief Wrapping enumerator
///
////////////////////////////////////////////////////////////////
enum eWarpping
{
Repeat,
Clamp
};
////////////////////////////////////////////////////////////////
/// \brief Default constructor.
///
////////////////////////////////////////////////////////////////
TextureProperties( );
////////////////////////////////////////////////////////////////
/// \brief Set magnification filter
///
////////////////////////////////////////////////////////////////
void SetMagnificationFilter( const eFilter p_Filter );
////////////////////////////////////////////////////////////////
/// \brief Set minification filter
///
////////////////////////////////////////////////////////////////
void SetMinificationFilter( const eFilter p_Filter );
////////////////////////////////////////////////////////////////
/// \brief Set wrapping for
///
////////////////////////////////////////////////////////////////
void SetWrapping( const eWarpping p_WrapX, const eWarpping p_WrapY );
////////////////////////////////////////////////////////////////
/// \brief Set wrapping for X axis.
///
////////////////////////////////////////////////////////////////
void SetWrappingX( const eWarpping p_WrapX );
////////////////////////////////////////////////////////////////
/// \brief Set wrapping for Y axis.
///
////////////////////////////////////////////////////////////////
void SetWrappingY( const eWarpping p_WrapY );
////////////////////////////////////////////////////////////////
/// \brief Set mipmapping status.
///
////////////////////////////////////////////////////////////////
void SetMipmapping( Bool p_Status );
////////////////////////////////////////////////////////////////
/// \brief Set anisotropic level.
///
////////////////////////////////////////////////////////////////
void SetAnisotropic( const Uint32 p_Level );
////////////////////////////////////////////////////////////////
/// \brief Set update flags. For advanced users only.
///
////////////////////////////////////////////////////////////////
void SetFlags( const Uint8 p_Flags );
////////////////////////////////////////////////////////////////
/// \brief Get magnification filter
///
////////////////////////////////////////////////////////////////
eFilter GetMagnificationFilter( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get minification filter
///
////////////////////////////////////////////////////////////////
eFilter GetMinificationFilter( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get wrapping for X axis.
///
////////////////////////////////////////////////////////////////
eWarpping GetWrappingX( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get wrapping for Y axis.
///
////////////////////////////////////////////////////////////////
eWarpping GetWrappingY( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get mipmapping status.
///
////////////////////////////////////////////////////////////////
Bool GetMipmapping( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get anisotropic level.
///
////////////////////////////////////////////////////////////////
Uint32 GetAnisotropic( ) const;
////////////////////////////////////////////////////////////////
/// \brief Get update flags. For advanced users only.
///
////////////////////////////////////////////////////////////////
Uint8 GetFlags( ) const;
private:
eFilter m_MagnificationFilter;
eFilter m_MinificationFilter;
eWarpping m_WrappingX;
eWarpping m_WrappingY;
Bool m_Mipmapping;
Uint32 m_AnisotropicLevel;
Uint8 m_Flags; ///< Update flag.
};
}
#endif | 33.882353 | 78 | 0.395991 | jimmiebergmann |
c0d7f59b8f82d16052ae48c3a72b1ac5ff05af37 | 209 | cpp | C++ | extras/general_pipelines/py2_10_20_20/py2_10_20_20.cpp | nvpro-samples/vk_compute_mipmaps | 613b94e4d36e6f357472e9c7a3163046deb55678 | [
"Apache-2.0"
] | 12 | 2021-07-24T18:33:22.000Z | 2022-03-12T16:20:49.000Z | extras/general_pipelines/py2_10_20_20/py2_10_20_20.cpp | nvpro-samples/vk_compute_mipmaps | 613b94e4d36e6f357472e9c7a3163046deb55678 | [
"Apache-2.0"
] | null | null | null | extras/general_pipelines/py2_10_20_20/py2_10_20_20.cpp | nvpro-samples/vk_compute_mipmaps | 613b94e4d36e6f357472e9c7a3163046deb55678 | [
"Apache-2.0"
] | 3 | 2021-08-04T02:27:12.000Z | 2022-03-13T08:43:24.000Z | #include "nvpro_pyramid_dispatch_alternative.hpp"
#include "../py2_dispatch_impl.hpp"
NVPRO_PYRAMID_ADD_GENERAL_DISPATCHER(py2_10_20_20,
(py2_dispatch_impl<10, 20, 20>))
| 29.857143 | 69 | 0.679426 | nvpro-samples |
c0d80a3d569a6a3522b2ebc38a601525ece54649 | 518 | hpp | C++ | src/Tools/Display/Dumper/Dumper_reduction.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Tools/Display/Dumper/Dumper_reduction.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | src/Tools/Display/Dumper/Dumper_reduction.hpp | codechecker123/aff3ct | 030af3e990027fa803fb2c68f974c9ec0ee79b5d | [
"MIT"
] | null | null | null | #ifndef DUMPER_REDUCTION_HPP_
#define DUMPER_REDUCTION_HPP_
#include "Dumper.hpp"
namespace aff3ct
{
namespace tools
{
class Dumper_reduction : Dumper
{
protected:
std::vector<Dumper*> dumpers;
public:
explicit Dumper_reduction(std::vector<Dumper*> &dumpers);
virtual ~Dumper_reduction();
virtual void dump (const std::string& base_path);
virtual void add (const int frame_id = 0 );
virtual void clear( );
private:
void checks();
};
}
}
#endif /* DUMPER_REDUCTION_HPP_ */
| 17.266667 | 58 | 0.694981 | codechecker123 |
c0d97772a1c1e4eaf6658cb081639fc2fea493a0 | 10,506 | cpp | C++ | src/maxon_epos_ethercat_sdk/Configuration.cpp | zoenglinghou/maxon_epos_ethercat_sdk | 4127085e33dfdbe08061b30941eaac4f5a5e0686 | [
"BSD-3-Clause"
] | 5 | 2021-04-06T13:42:34.000Z | 2022-02-22T08:37:20.000Z | src/maxon_epos_ethercat_sdk/Configuration.cpp | zoenglinghou/maxon_epos_ethercat_sdk | 4127085e33dfdbe08061b30941eaac4f5a5e0686 | [
"BSD-3-Clause"
] | 2 | 2021-04-29T15:42:38.000Z | 2022-02-23T15:07:31.000Z | src/maxon_epos_ethercat_sdk/Configuration.cpp | zoenglinghou/maxon_epos_ethercat_sdk | 4127085e33dfdbe08061b30941eaac4f5a5e0686 | [
"BSD-3-Clause"
] | 5 | 2021-04-28T15:06:15.000Z | 2022-02-23T09:09:55.000Z | // clang-format off
/*
** Copyright 2021 Robotic Systems Lab - ETH Zurich:
** Linghao Zhang, Jonas Junger, Lennart Nachtigall
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice,
** this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of 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.
*/
// clang-format on
#include "maxon_epos_ethercat_sdk/Configuration.hpp"
#include <iomanip>
#include <vector>
#include <map>
#include <algorithm>
#include <utility>
namespace maxon {
std::string modeOfOperationString(ModeOfOperationEnum modeOfOperation_) {
switch (modeOfOperation_) {
case ModeOfOperationEnum::ProfiledPositionMode:
return "Profiled Position Mode";
case ModeOfOperationEnum::ProfiledVelocityMode:
return "Profiled Velocity Mode";
case ModeOfOperationEnum::HomingMode:
return "Homing Mode";
case ModeOfOperationEnum::CyclicSynchronousPositionMode:
return "Cyclic Synchronous Position Mode";
case ModeOfOperationEnum::CyclicSynchronousVelocityMode:
return "Cyclic Synchronous Velocity Mode";
case ModeOfOperationEnum::CyclicSynchronousTorqueMode:
return "Cyclic Synchronous Torque Mode";
default:
return "Unsupported Mode of Operation";
}
}
std::string rxPdoString(RxPdoTypeEnum rxPdo) {
switch (rxPdo) {
case RxPdoTypeEnum::NA:
return "NA";
case RxPdoTypeEnum::RxPdoStandard:
return "Rx PDO Standard";
case RxPdoTypeEnum::RxPdoCSP:
return "Rx PDO CSP";
case RxPdoTypeEnum::RxPdoCST:
return "Rx PDO CST";
case RxPdoTypeEnum::RxPdoCSV:
return "Rx PDO CSV";
case RxPdoTypeEnum::RxPdoCSTCSP:
return "Rx PDO CST/CSP mixed mode";
case RxPdoTypeEnum::RxPdoCSTCSPCSV:
return "Rx PDO CST/CSP/CSV mixed mode";
case RxPdoTypeEnum::RxPdoPVM:
return "Rx PDO PVM";
default:
return "Unsupported Type";
}
}
std::string txPdoString(TxPdoTypeEnum txPdo) {
switch (txPdo) {
case TxPdoTypeEnum::NA:
return "NA";
case TxPdoTypeEnum::TxPdoCSP:
return "Tx PDO CSP";
case TxPdoTypeEnum::TxPdoCST:
return "Tx PDO CST";
case TxPdoTypeEnum::TxPdoCSV:
return "Tx PDO CSV";
case TxPdoTypeEnum::TxPdoCSTCSP:
return "Tx PDO CST/CSP mixed mode";
case TxPdoTypeEnum::TxPdoCSTCSPCSV:
return "Rx PDO CST/CSP/CSV mixed mode";
case TxPdoTypeEnum::TxPdoPVM:
return "Tx PDO PVM";
case TxPdoTypeEnum::TxPdoStandard:
return "Tx PDO Standard";
default:
return "Unsupported Type";
}
}
std::ostream& operator<<(std::ostream& os, const Configuration& configuration) {
std::string modeOfOperation_ =
modeOfOperationString(configuration.modesOfOperation[0]);
unsigned int tmp3 = modeOfOperation_.size();
unsigned int len2 = tmp3;
len2++;
os << std::boolalpha << std::left << std::setw(43) << std::setfill('-') << "|"
<< std::setw(len2 + 2) << "-"
<< "|\n"
<< std::setfill(' ') << std::setw(43 + len2 + 2) << "| Configuration"
<< "|\n"
<< std::setw(43) << std::setfill('-') << "|" << std::setw(len2 + 2) << "+"
<< "|\n"
<< std::setfill(' ') << std::setw(43) << "| 1st Mode of Operation:"
<< "| " << std::setw(len2) << modeOfOperation_ << "|\n"
<< std::setw(43) << "| Config Run SDO verify timeout:"
<< "| " << std::setw(len2) << configuration.configRunSdoVerifyTimeout
<< "|\n"
<< std::setw(43) << "| Print Debug Messages:"
<< "| " << std::setw(len2) << configuration.printDebugMessages << "|\n"
<< std::setw(43) << "| Drive State Change Min Timeout:"
<< "| " << std::setw(len2) << configuration.driveStateChangeMinTimeout
<< "|\n"
<< std::setw(43) << "| Drive State Change Max Timeout:"
<< "| " << std::setw(len2) << configuration.driveStateChangeMaxTimeout
<< "|\n"
<< std::setw(43) << "| Min Successful Target State Readings:"
<< "| " << std::setw(len2)
<< configuration.minNumberOfSuccessfulTargetStateReadings << "|\n"
<< std::setw(43) << "| Force Append Equal Error:"
<< "| " << std::setw(len2) << configuration.forceAppendEqualError << "|\n"
<< std::setw(43) << "| Force Append Equal Fault:"
<< "| " << std::setw(len2) << configuration.forceAppendEqualFault << "|\n"
<< std::setw(43) << "| Error Storage Capacity"
<< "| " << std::setw(len2) << configuration.errorStorageCapacity << "|\n"
<< std::setw(43) << "| Fault Storage Capacity"
<< "| " << std::setw(len2) << configuration.faultStorageCapacity << "|\n"
<< std::setw(43) << std::setfill('-') << "|" << std::setw(len2 + 2) << "+"
<< "|\n"
<< std::setfill(' ') << std::noboolalpha << std::right;
return os;
}
std::pair<RxPdoTypeEnum, TxPdoTypeEnum> Configuration::getPdoTypeSolution()
const {
// clang-format off
// {ModeOfOperationEnum1, ..., ModeOfOperationEnumN} -> {RxPdoTypeEnum, TxPdoTypeEnum}
const std::map<std::vector<ModeOfOperationEnum>, std::pair<RxPdoTypeEnum, TxPdoTypeEnum>> modes2PdoTypeMap = {
{
{ ModeOfOperationEnum::CyclicSynchronousTorqueMode, ModeOfOperationEnum::CyclicSynchronousPositionMode },
{ RxPdoTypeEnum::RxPdoCSTCSP, TxPdoTypeEnum::TxPdoCSTCSP }
},
{
{ ModeOfOperationEnum::CyclicSynchronousTorqueMode, ModeOfOperationEnum::CyclicSynchronousPositionMode,
ModeOfOperationEnum::CyclicSynchronousVelocityMode },
{ RxPdoTypeEnum::RxPdoCSTCSPCSV, TxPdoTypeEnum::TxPdoCSTCSPCSV }
},
{
{ ModeOfOperationEnum::CyclicSynchronousPositionMode },
{ RxPdoTypeEnum::RxPdoCSP, TxPdoTypeEnum::TxPdoCSP }
},
{
{ ModeOfOperationEnum::CyclicSynchronousTorqueMode },
{ RxPdoTypeEnum::RxPdoCST, TxPdoTypeEnum::TxPdoCST }
},
{
{ ModeOfOperationEnum::CyclicSynchronousVelocityMode },
{ RxPdoTypeEnum::RxPdoCSV, TxPdoTypeEnum::TxPdoCSV }
},
{
{ ModeOfOperationEnum::HomingMode },
{ RxPdoTypeEnum::NA, TxPdoTypeEnum::NA }
},
{
{ ModeOfOperationEnum::ProfiledPositionMode },
{ RxPdoTypeEnum::NA, TxPdoTypeEnum::NA }
},
{
{ ModeOfOperationEnum::ProfiledVelocityMode },
{ RxPdoTypeEnum::RxPdoPVM, TxPdoTypeEnum::TxPdoPVM }
},
{
{ ModeOfOperationEnum::NA },
{ RxPdoTypeEnum::NA, TxPdoTypeEnum::NA }
},
};
// clang-format on
bool setsAreEqual;
for (const auto& modes2PdoTypeEntry : modes2PdoTypeMap) {
setsAreEqual = true;
for (const auto& modeOfOperation : modesOfOperation)
setsAreEqual &=
std::find(modes2PdoTypeEntry.first.begin(),
modes2PdoTypeEntry.first.end(),
modeOfOperation) != modes2PdoTypeEntry.first.end();
for (const auto& modeOfOperation : modes2PdoTypeEntry.first)
setsAreEqual &=
std::find(modesOfOperation.begin(), modesOfOperation.end(),
modeOfOperation) != modesOfOperation.end();
if (setsAreEqual) return modes2PdoTypeEntry.second;
}
return std::pair<RxPdoTypeEnum, TxPdoTypeEnum>{RxPdoTypeEnum::NA,
TxPdoTypeEnum::NA};
}
bool Configuration::sanityCheck(bool silent) const {
bool success = true;
std::string message = "";
auto check_and_inform = [&message,
&success](std::pair<bool, std::string> test) {
if (test.first) {
message += "\033[32m✓\t";
message += test.second;
message += "\033[m\n";
success &= true;
} else {
message += "\033[31m✕\t";
message += test.second;
message += "\033[m\n";
success = false;
}
};
auto pdoTypePair = getPdoTypeSolution();
// clang-format off
const std::vector<std::pair<bool, std::string>> sanity_tests = {
{
(polePairs > 0),
"pole_pairs > 0"
},
{
(motorConstant > 0),
"motor_constant > 0"
},
{
(nominalCurrentA > 0),
"nominal_current > 0"
},
{
(maxCurrentA > 0),
"max_current > 0"
},
{
(torqueConstantNmA > 0),
"torque_constant > 0"
},
{
(maxProfileVelocity > 0),
"max_profile_velocity > 0"
},
{
(quickStopDecel > 0),
"quick_stop_decel > 0"
},
{
(profileDecel > 0),
"profile_decel > 0"
},
{
(profileDecel > 0),
"profile_decel > 0"
},
{
(positionEncoderResolution > 0),
"position_encoder_resolution > 0"
},
{
(gearRatio > 0),
"gear_ratio > 0"
},
{
(pdoTypePair.first != RxPdoTypeEnum::NA && pdoTypePair.second != TxPdoTypeEnum::NA),
"modes of operation combination allowed"
},
{
(driveStateChangeMinTimeout <= driveStateChangeMaxTimeout),
"drive_state_change_min_timeout ≤ drive_state_change_max_timeout"
},
};
// clang-format on
std::for_each(sanity_tests.begin(), sanity_tests.end(), check_and_inform);
if (!silent) {
std::cout << message << std::endl;
}
return success;
}
} // namespace maxon
| 35.137124 | 113 | 0.63202 | zoenglinghou |
c0db91560356c7a14f2665a38bc5f060cfdfe65c | 389 | cpp | C++ | test_Graph/main.cpp | Dieupix/Graph | c57f17808e274f3c0f9d2829ecf58daec8983fd6 | [
"MIT"
] | 4 | 2021-11-30T18:21:06.000Z | 2022-01-05T19:01:57.000Z | test_Graph/main.cpp | Dieupix/Graph | c57f17808e274f3c0f9d2829ecf58daec8983fd6 | [
"MIT"
] | null | null | null | test_Graph/main.cpp | Dieupix/Graph | c57f17808e274f3c0f9d2829ecf58daec8983fd6 | [
"MIT"
] | null | null | null | #define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
int main() {
doctest::Context context;
context.setOption("order-by", "name"); // sort the test cases by their name
//context.setOption("duration", true); // print the duration of each test case
//context.setOption("success", true); // print all tests
return context.run(); // run
}
| 29.923077 | 85 | 0.627249 | Dieupix |
c0de1d6831a09889f4f65cf431903ff4700f369f | 28,755 | cpp | C++ | tests/unit/utils/test_mem.cpp | bruingineer/sACN-1 | aef4a38f025f3800248ac24e377485dba27ed16f | [
"Apache-2.0"
] | null | null | null | tests/unit/utils/test_mem.cpp | bruingineer/sACN-1 | aef4a38f025f3800248ac24e377485dba27ed16f | [
"Apache-2.0"
] | null | null | null | tests/unit/utils/test_mem.cpp | bruingineer/sACN-1 | aef4a38f025f3800248ac24e377485dba27ed16f | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2021 ETC Inc.
*
* 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.
******************************************************************************
* This file is a part of sACN. For more information, go to:
* https://github.com/ETCLabs/sACN
*****************************************************************************/
#include "sacn/private/mem.h"
#include <string>
#include "etcpal/cpp/uuid.h"
#include "etcpal_mock/common.h"
#include "sacn/private/common.h"
#include "sacn/private/opts.h"
#include "sacn_mock/private/common.h"
#include "gtest/gtest.h"
#include "fff.h"
#if SACN_DYNAMIC_MEM
#define TestMem TestMemDynamic
#else
#define TestMem TestMemStatic
#endif
static constexpr sacn_merge_receiver_t kTestMergeReceiverHandle = 1;
static constexpr SacnMergeReceiverConfig kTestMergeReceiverConfig = {
1u,
{[](sacn_merge_receiver_t, uint16_t, const uint8_t*, const sacn_remote_source_t*, void*) {},
[](sacn_merge_receiver_t, uint16_t, const EtcPalSockAddr*, const SacnHeaderData*, const uint8_t*, void*) {}, NULL,
NULL},
SACN_RECEIVER_INFINITE_SOURCES,
true,
kSacnIpV4AndIpV6};
class TestMem : public ::testing::Test
{
protected:
static constexpr unsigned int kTestNumThreads = 1; // TODO: Set back to 4 if/when SACN_RECEIVER_MAX_THREADS increases
static constexpr intptr_t kMagicPointerValue = 0xdeadbeef;
void SetUp() override
{
etcpal_reset_all_fakes();
sacn_common_reset_all_fakes();
ASSERT_EQ(sacn_mem_init(kTestNumThreads), kEtcPalErrOk);
}
void TearDown() override { sacn_mem_deinit(); }
void DoForEachThread(std::function<void(sacn_thread_id_t)>&& fn)
{
for (sacn_thread_id_t thread = 0; thread < kTestNumThreads; ++thread)
{
SCOPED_TRACE("While testing thread ID " + std::to_string(thread));
fn(thread);
}
}
};
TEST_F(TestMem, GetNumThreadsWorks)
{
EXPECT_EQ(sacn_mem_get_num_threads(), kTestNumThreads);
}
TEST_F(TestMem, ValidInitializedStatusLists)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
EXPECT_EQ(status_lists->num_online, 0u);
EXPECT_EQ(status_lists->num_offline, 0u);
EXPECT_EQ(status_lists->num_unknown, 0u);
});
}
TEST_F(TestMem, StatusListsAreReZeroedWithEachGet)
{
SacnSourceStatusLists* status_lists = get_status_lists(0);
ASSERT_NE(status_lists, nullptr);
// Modify some elements
status_lists->num_online = 20;
status_lists->num_offline = 40;
status_lists->num_unknown = 60;
// Now get again and make sure they are re-zeroed
status_lists = get_status_lists(0);
ASSERT_NE(status_lists, nullptr);
EXPECT_EQ(status_lists->num_online, 0u);
EXPECT_EQ(status_lists->num_offline, 0u);
EXPECT_EQ(status_lists->num_unknown, 0u);
}
TEST_F(TestMem, StatusListsAddOfflineWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
sacn_remote_source_t handle_to_add = 0u;
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_offline_source(status_lists, handle_to_add, test_name.c_str(), true));
EXPECT_EQ(status_lists->num_offline, i + 1);
EXPECT_EQ(status_lists->offline[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->offline[i].name, test_name.c_str());
EXPECT_EQ(status_lists->offline[i].terminated, true);
++handle_to_add;
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_offline_source(status_lists, handle_to_add, test_name.c_str(), true));
EXPECT_EQ(status_lists->num_offline, i + 1);
EXPECT_EQ(status_lists->offline[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->offline[i].name, test_name.c_str());
EXPECT_EQ(status_lists->offline[i].terminated, true);
++handle_to_add;
}
// And make sure we can't add another
EXPECT_FALSE(add_offline_source(status_lists, handle_to_add, "test name", true));
#endif
});
}
TEST_F(TestMem, StatusListsAddOnlineWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
sacn_remote_source_t handle_to_add = 0u;
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_online_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_online, i + 1);
EXPECT_EQ(status_lists->online[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->online[i].name, test_name.c_str());
++handle_to_add;
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_online_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_online, i + 1);
EXPECT_EQ(status_lists->online[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->online[i].name, test_name.c_str());
++handle_to_add;
}
// And make sure we can't add another
EXPECT_FALSE(add_online_source(status_lists, handle_to_add, "test name"));
#endif
});
}
TEST_F(TestMem, StatusListsAddUnknownWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnSourceStatusLists* status_lists = get_status_lists(thread);
ASSERT_NE(status_lists, nullptr);
sacn_remote_source_t handle_to_add = 0u;
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_unknown_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_unknown, i + 1);
EXPECT_EQ(status_lists->unknown[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->unknown[i].name, test_name.c_str());
++handle_to_add;
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(add_unknown_source(status_lists, handle_to_add, test_name.c_str()));
EXPECT_EQ(status_lists->num_unknown, i + 1);
EXPECT_EQ(status_lists->unknown[i].handle, handle_to_add);
EXPECT_STREQ(status_lists->unknown[i].name, test_name.c_str());
++handle_to_add;
}
// And make sure we can't add another
EXPECT_FALSE(add_unknown_source(status_lists, handle_to_add, "test name"));
#endif
});
}
TEST_F(TestMem, ValidInitializedToEraseBuffer)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SacnTrackedSource** to_erase_buf = get_to_erase_buffer(thread, 20);
ASSERT_NE(to_erase_buf, nullptr);
for (size_t i = 0; i < 20; ++i)
EXPECT_EQ(to_erase_buf[i], nullptr);
#else
// Just test some arbitrary number for the buffer size
SacnTrackedSource** to_erase_buf = get_to_erase_buffer(thread, SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE);
ASSERT_NE(to_erase_buf, nullptr);
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
EXPECT_EQ(to_erase_buf[i], nullptr);
// Trying to get more than the max capacity should not work
to_erase_buf = get_to_erase_buffer(thread, SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE + 1);
EXPECT_EQ(to_erase_buf, nullptr);
#endif
});
}
TEST_F(TestMem, ToEraseIsReZeroedWithEachGet)
{
SacnTrackedSource** to_erase = get_to_erase_buffer(0, 1);
ASSERT_NE(to_erase, nullptr);
// Modify some elements
to_erase[0] = reinterpret_cast<SacnTrackedSource*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
to_erase = get_to_erase_buffer(0, 1);
ASSERT_NE(to_erase, nullptr);
EXPECT_EQ(to_erase[0], nullptr);
}
TEST_F(TestMem, ValidInitializedRecvThreadContext)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
EXPECT_EQ(recv_thread_context->thread_id, thread);
EXPECT_EQ(recv_thread_context->receivers, nullptr);
EXPECT_EQ(recv_thread_context->num_receivers, 0u);
#if SACN_DYNAMIC_MEM
EXPECT_NE(recv_thread_context->dead_sockets, nullptr);
EXPECT_NE(recv_thread_context->socket_refs, nullptr);
#endif
EXPECT_EQ(recv_thread_context->num_dead_sockets, 0u);
EXPECT_EQ(recv_thread_context->num_socket_refs, 0u);
EXPECT_EQ(recv_thread_context->new_socket_refs, 0u);
});
}
TEST_F(TestMem, AddDeadSocketWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
ASSERT_TRUE(add_dead_socket(recv_thread_context, (etcpal_socket_t)i));
EXPECT_EQ(recv_thread_context->num_dead_sockets, i + 1);
EXPECT_EQ(recv_thread_context->dead_sockets[i], (etcpal_socket_t)i);
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_UNIVERSES * 2; ++i)
{
ASSERT_TRUE(add_dead_socket(recv_thread_context, (etcpal_socket_t)i));
EXPECT_EQ(recv_thread_context->num_dead_sockets, i + 1);
EXPECT_EQ(recv_thread_context->dead_sockets[i], (etcpal_socket_t)i);
}
// And make sure we can't add another
EXPECT_FALSE(add_dead_socket(recv_thread_context, (etcpal_socket_t)SACN_RECEIVER_MAX_UNIVERSES));
#endif
});
}
TEST_F(TestMem, AddSocketRefWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
ASSERT_TRUE(add_socket_ref(recv_thread_context, (etcpal_socket_t)i, kEtcPalIpTypeInvalid, false));
EXPECT_EQ(recv_thread_context->num_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->new_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->socket_refs[i].sock, (etcpal_socket_t)i);
EXPECT_EQ(recv_thread_context->socket_refs[i].refcount, 1u);
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOCKET_REFS; ++i)
{
ASSERT_TRUE(add_socket_ref(recv_thread_context, (etcpal_socket_t)i, kEtcPalIpTypeInvalid, false));
EXPECT_EQ(recv_thread_context->num_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->new_socket_refs, i + 1);
EXPECT_EQ(recv_thread_context->socket_refs[i].sock, (etcpal_socket_t)i);
EXPECT_EQ(recv_thread_context->socket_refs[i].refcount, 1u);
}
// And make sure we can't add another
EXPECT_FALSE(add_socket_ref(recv_thread_context, (etcpal_socket_t)SACN_RECEIVER_MAX_SOCKET_REFS,
kEtcPalIpTypeInvalid, false));
#endif
});
}
TEST_F(TestMem, RemoveSocketRefWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SacnRecvThreadContext* recv_thread_context = get_recv_thread_context(thread);
ASSERT_NE(recv_thread_context, nullptr);
recv_thread_context->socket_refs[0] = SocketRef{(etcpal_socket_t)0, 1};
recv_thread_context->socket_refs[1] = SocketRef{(etcpal_socket_t)1, 20};
recv_thread_context->socket_refs[2] = SocketRef{(etcpal_socket_t)2, 3};
recv_thread_context->num_socket_refs = 3;
recv_thread_context->new_socket_refs = 1;
// Remove a socket ref that has a refcount of 1, the other ones should be shifted
ASSERT_TRUE(remove_socket_ref(recv_thread_context, (etcpal_socket_t)0));
ASSERT_EQ(recv_thread_context->num_socket_refs, 2u);
EXPECT_EQ(recv_thread_context->new_socket_refs, 1u);
EXPECT_EQ(recv_thread_context->socket_refs[0].sock, (etcpal_socket_t)1);
EXPECT_EQ(recv_thread_context->socket_refs[0].refcount, 20u);
EXPECT_EQ(recv_thread_context->socket_refs[1].sock, (etcpal_socket_t)2);
EXPECT_EQ(recv_thread_context->socket_refs[1].refcount, 3u);
// Remove one with multiple references
for (int i = 0; i < 2; ++i)
ASSERT_FALSE(remove_socket_ref(recv_thread_context, (etcpal_socket_t)2));
EXPECT_TRUE(remove_socket_ref(recv_thread_context, (etcpal_socket_t)2));
EXPECT_EQ(recv_thread_context->num_socket_refs, 1u);
});
}
TEST_F(TestMem, ValidInitializedUniverseData)
{
DoForEachThread([](sacn_thread_id_t thread) {
UniverseDataNotification* universe_data = get_universe_data(thread);
ASSERT_NE(universe_data, nullptr);
EXPECT_EQ(universe_data->callback, nullptr);
EXPECT_EQ(universe_data->receiver_handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(universe_data->pdata, nullptr);
EXPECT_EQ(universe_data->context, nullptr);
});
}
TEST_F(TestMem, UniverseDataIsReZeroedWithEachGet)
{
UniverseDataNotification* universe_data = get_universe_data(0);
ASSERT_NE(universe_data, nullptr);
// Modify some elements
universe_data->receiver_handle = 2;
universe_data->callback = reinterpret_cast<SacnUniverseDataCallback>(kMagicPointerValue);
universe_data->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
universe_data = get_universe_data(0);
ASSERT_NE(universe_data, nullptr);
EXPECT_EQ(universe_data->callback, nullptr);
EXPECT_EQ(universe_data->receiver_handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(universe_data->pdata, nullptr);
EXPECT_EQ(universe_data->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSourcesLostBuf)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SourcesLostNotification* sources_lost_buf = get_sources_lost_buffer(thread, 20);
ASSERT_NE(sources_lost_buf, nullptr);
for (int i = 0; i < 20; ++i)
{
auto sources_lost = &sources_lost_buf[i];
EXPECT_EQ(sources_lost->callback, nullptr);
EXPECT_EQ(sources_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sources_lost->num_lost_sources, 0u);
EXPECT_EQ(sources_lost->context, nullptr);
}
#else
SourcesLostNotification* sources_lost_buf = get_sources_lost_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES);
ASSERT_NE(sources_lost_buf, nullptr);
// Test up to the maximum capacity
for (int i = 0; i < SACN_RECEIVER_MAX_THREADS; ++i)
{
auto sources_lost = &sources_lost_buf[i];
EXPECT_EQ(sources_lost->callback, nullptr);
EXPECT_EQ(sources_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sources_lost->num_lost_sources, 0u);
EXPECT_EQ(sources_lost->context, nullptr);
}
// Trying to get more than the max capacity should not work
sources_lost_buf = get_sources_lost_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES + 1);
EXPECT_EQ(sources_lost_buf, nullptr);
#endif
});
}
TEST_F(TestMem, AddLostSourceWorks)
{
DoForEachThread([](sacn_thread_id_t thread) {
SourcesLostNotification* sources_lost = get_sources_lost_buffer(thread, 1);
ASSERT_NE(sources_lost, nullptr);
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number
for (size_t i = 0; i < 20; ++i)
{
auto cid_to_add = etcpal::Uuid::V4();
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(
add_lost_source(sources_lost, SACN_REMOTE_SOURCE_INVALID, &cid_to_add.get(), test_name.c_str(), true));
EXPECT_EQ(sources_lost->num_lost_sources, i + 1);
EXPECT_EQ(sources_lost->lost_sources[i].cid, cid_to_add);
EXPECT_STREQ(sources_lost->lost_sources[i].name, test_name.c_str());
EXPECT_EQ(sources_lost->lost_sources[i].terminated, true);
}
#else
// Test up to the maximum capacity
for (size_t i = 0; i < SACN_RECEIVER_MAX_SOURCES_PER_UNIVERSE; ++i)
{
auto cid_to_add = etcpal::Uuid::V4();
std::string test_name = "test name " + std::to_string(i);
ASSERT_TRUE(
add_lost_source(sources_lost, SACN_REMOTE_SOURCE_INVALID, &cid_to_add.get(), test_name.c_str(), true));
EXPECT_EQ(sources_lost->num_lost_sources, i + 1);
EXPECT_EQ(sources_lost->lost_sources[i].cid, cid_to_add);
EXPECT_STREQ(sources_lost->lost_sources[i].name, test_name.c_str());
EXPECT_EQ(sources_lost->lost_sources[i].terminated, true);
}
// And make sure we can't add another
auto cid_to_add = etcpal::Uuid::V4();
EXPECT_FALSE(add_lost_source(sources_lost, SACN_REMOTE_SOURCE_INVALID, &cid_to_add.get(), "test name", true));
#endif
});
}
TEST_F(TestMem, SourcesLostIsReZeroedWithEachGet)
{
SourcesLostNotification* sources_lost = get_sources_lost_buffer(0, 1);
ASSERT_NE(sources_lost, nullptr);
// Modify some elements
sources_lost->handle = 2;
sources_lost->callback = reinterpret_cast<SacnSourcesLostCallback>(kMagicPointerValue);
sources_lost->num_lost_sources = 10;
sources_lost->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
sources_lost = get_sources_lost_buffer(0, 1);
ASSERT_NE(sources_lost, nullptr);
EXPECT_EQ(sources_lost->callback, nullptr);
EXPECT_EQ(sources_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sources_lost->num_lost_sources, 0u);
EXPECT_EQ(sources_lost->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSourcePapLost)
{
DoForEachThread([](sacn_thread_id_t thread) {
SourcePapLostNotification* source_pap_lost = get_source_pap_lost(thread);
ASSERT_NE(source_pap_lost, nullptr);
EXPECT_EQ(source_pap_lost->callback, nullptr);
EXPECT_EQ(source_pap_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_pap_lost->context, nullptr);
});
}
TEST_F(TestMem, SourcePapLostIsReZeroedWithEachGet)
{
SourcePapLostNotification* source_pap_lost = get_source_pap_lost(0);
ASSERT_NE(source_pap_lost, nullptr);
// Modify some elements
source_pap_lost->handle = 2;
source_pap_lost->callback = reinterpret_cast<SacnSourcePapLostCallback>(kMagicPointerValue);
source_pap_lost->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
source_pap_lost = get_source_pap_lost(0);
ASSERT_NE(source_pap_lost, nullptr);
EXPECT_EQ(source_pap_lost->callback, nullptr);
EXPECT_EQ(source_pap_lost->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_pap_lost->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSamplingStartedBuf)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SamplingStartedNotification* sampling_started_buf = get_sampling_started_buffer(thread, 20);
ASSERT_NE(sampling_started_buf, nullptr);
for (int i = 0; i < 20; ++i)
{
auto sampling_started = &sampling_started_buf[i];
EXPECT_EQ(sampling_started->callback, nullptr);
EXPECT_EQ(sampling_started->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_started->context, nullptr);
}
#else
SamplingStartedNotification* sampling_started_buf =
get_sampling_started_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES);
ASSERT_NE(sampling_started_buf, nullptr);
// Test up to the maximum capacity
for (int i = 0; i < SACN_RECEIVER_MAX_THREADS; ++i)
{
auto sampling_started = &sampling_started_buf[i];
EXPECT_EQ(sampling_started->callback, nullptr);
EXPECT_EQ(sampling_started->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_started->context, nullptr);
}
// Trying to get more than the max capacity should not work
sampling_started_buf = get_sampling_started_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES + 1);
EXPECT_EQ(sampling_started_buf, nullptr);
#endif
});
}
TEST_F(TestMem, SamplingStartedIsReZeroedWithEachGet)
{
SamplingStartedNotification* sampling_started = get_sampling_started_buffer(0, 1);
ASSERT_NE(sampling_started, nullptr);
// Modify some elements
sampling_started->handle = 2;
sampling_started->callback = reinterpret_cast<SacnSamplingPeriodStartedCallback>(kMagicPointerValue);
sampling_started->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
sampling_started = get_sampling_started_buffer(0, 1);
ASSERT_NE(sampling_started, nullptr);
EXPECT_EQ(sampling_started->callback, nullptr);
EXPECT_EQ(sampling_started->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_started->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSamplingEndedBuf)
{
DoForEachThread([](sacn_thread_id_t thread) {
#if SACN_DYNAMIC_MEM
// Just test some arbitrary number for the buffer size
SamplingEndedNotification* sampling_ended_buf = get_sampling_ended_buffer(thread, 20);
ASSERT_NE(sampling_ended_buf, nullptr);
for (int i = 0; i < 20; ++i)
{
auto sampling_ended = &sampling_ended_buf[i];
EXPECT_EQ(sampling_ended->callback, nullptr);
EXPECT_EQ(sampling_ended->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_ended->context, nullptr);
}
#else
SamplingEndedNotification* sampling_ended_buf = get_sampling_ended_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES);
ASSERT_NE(sampling_ended_buf, nullptr);
// Test up to the maximum capacity
for (int i = 0; i < SACN_RECEIVER_MAX_THREADS; ++i)
{
auto sampling_ended = &sampling_ended_buf[i];
EXPECT_EQ(sampling_ended->callback, nullptr);
EXPECT_EQ(sampling_ended->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_ended->context, nullptr);
}
// Trying to get more than the max capacity should not work
sampling_ended_buf = get_sampling_ended_buffer(thread, SACN_RECEIVER_MAX_UNIVERSES + 1);
EXPECT_EQ(sampling_ended_buf, nullptr);
#endif
});
}
TEST_F(TestMem, SamplingEndedIsReZeroedWithEachGet)
{
SamplingEndedNotification* sampling_ended = get_sampling_ended_buffer(0, 1);
ASSERT_NE(sampling_ended, nullptr);
// Modify some elements
sampling_ended->handle = 2;
sampling_ended->callback = reinterpret_cast<SacnSamplingPeriodEndedCallback>(kMagicPointerValue);
sampling_ended->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
sampling_ended = get_sampling_ended_buffer(0, 1);
ASSERT_NE(sampling_ended, nullptr);
EXPECT_EQ(sampling_ended->callback, nullptr);
EXPECT_EQ(sampling_ended->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(sampling_ended->context, nullptr);
}
TEST_F(TestMem, ValidInitializedSourceLimitExceeded)
{
DoForEachThread([](sacn_thread_id_t thread) {
SourceLimitExceededNotification* source_limit_exceeded = get_source_limit_exceeded(thread);
ASSERT_NE(source_limit_exceeded, nullptr);
EXPECT_EQ(source_limit_exceeded->callback, nullptr);
EXPECT_EQ(source_limit_exceeded->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_limit_exceeded->context, nullptr);
});
}
TEST_F(TestMem, SourceLimitExceededIsReZeroedWithEachGet)
{
SourceLimitExceededNotification* source_limit_exceeded = get_source_limit_exceeded(0);
ASSERT_NE(source_limit_exceeded, nullptr);
// Modify some elements
source_limit_exceeded->handle = 2;
source_limit_exceeded->callback = reinterpret_cast<SacnSourceLimitExceededCallback>(kMagicPointerValue);
source_limit_exceeded->context = reinterpret_cast<void*>(kMagicPointerValue);
// Now get again and make sure they are re-zeroed
source_limit_exceeded = get_source_limit_exceeded(0);
ASSERT_NE(source_limit_exceeded, nullptr);
EXPECT_EQ(source_limit_exceeded->callback, nullptr);
EXPECT_EQ(source_limit_exceeded->handle, SACN_RECEIVER_INVALID);
EXPECT_EQ(source_limit_exceeded->context, nullptr);
}
TEST_F(TestMem, AddReceiverToListWorks)
{
SacnRecvThreadContext rtc{};
#if SACN_DYNAMIC_MEM
SacnReceiver receiver{};
#else
SacnReceiver receiver{{}, {}, {}, {}}; // Fixes error C3852
#endif
add_receiver_to_list(&rtc, &receiver);
ASSERT_EQ(rtc.receivers, &receiver);
EXPECT_EQ(rtc.receivers->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 1u);
#if SACN_DYNAMIC_MEM
SacnReceiver receiver2{};
#else
SacnReceiver receiver2{{}, {}, {}, {}}; // Fixes error C3852
#endif
add_receiver_to_list(&rtc, &receiver2);
ASSERT_EQ(rtc.receivers, &receiver);
ASSERT_EQ(rtc.receivers->next, &receiver2);
EXPECT_EQ(rtc.receivers->next->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 2u);
}
TEST_F(TestMem, RemoveReceiverFromListWorks)
{
SacnRecvThreadContext rtc{};
#if SACN_DYNAMIC_MEM
SacnReceiver receiver{};
SacnReceiver receiver2{};
SacnReceiver receiver3{};
#else
SacnReceiver receiver{{}, {}, {}, {}}; // Fixes error C3852
SacnReceiver receiver2{{}, {}, {}, {}};
SacnReceiver receiver3{{}, {}, {}, {}};
#endif
rtc.receivers = &receiver;
receiver.next = &receiver2;
receiver2.next = &receiver3;
rtc.num_receivers = 3;
// Remove from the middle
remove_receiver_from_list(&rtc, &receiver2);
ASSERT_EQ(rtc.receivers, &receiver);
ASSERT_EQ(rtc.receivers->next, &receiver3);
EXPECT_EQ(rtc.receivers->next->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 2u);
EXPECT_EQ(receiver2.next, nullptr);
// Remove from the head
remove_receiver_from_list(&rtc, &receiver);
ASSERT_EQ(rtc.receivers, &receiver3);
EXPECT_EQ(rtc.receivers->next, nullptr);
EXPECT_EQ(rtc.num_receivers, 1u);
EXPECT_EQ(receiver.next, nullptr);
}
TEST_F(TestMem, AddSacnMergeReceiverWorks)
{
SacnMergeReceiver* merge_receiver = nullptr;
EXPECT_EQ(add_sacn_merge_receiver(kTestMergeReceiverHandle, &kTestMergeReceiverConfig, &merge_receiver),
kEtcPalErrOk);
ASSERT_NE(merge_receiver, nullptr);
EXPECT_EQ(merge_receiver->merge_receiver_handle, kTestMergeReceiverHandle);
EXPECT_EQ(merge_receiver->merger_handle, SACN_DMX_MERGER_INVALID);
EXPECT_EQ(merge_receiver->callbacks.universe_data, kTestMergeReceiverConfig.callbacks.universe_data);
EXPECT_EQ(merge_receiver->callbacks.universe_non_dmx, kTestMergeReceiverConfig.callbacks.universe_non_dmx);
EXPECT_EQ(merge_receiver->callbacks.source_limit_exceeded, nullptr);
}
TEST_F(TestMem, AddSacnMergeReceiverSourceWorks)
{
static constexpr size_t kNumSources = 5u;
SacnMergeReceiver* merge_receiver = nullptr;
EXPECT_EQ(add_sacn_merge_receiver(kTestMergeReceiverHandle, &kTestMergeReceiverConfig, &merge_receiver),
kEtcPalErrOk);
etcpal::Uuid last_cid;
for (size_t i = 0u; i < kNumSources; ++i)
{
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), i);
last_cid = etcpal::Uuid::V4();
EXPECT_EQ(add_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(i), false),
kEtcPalErrOk);
}
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), kNumSources);
EXPECT_EQ(add_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(kNumSources - 1u), false),
kEtcPalErrExists);
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), kNumSources);
}
TEST_F(TestMem, RemoveSacnMergeReceiverSourceWorks)
{
static constexpr size_t kNumSources = 5u;
SacnMergeReceiver* merge_receiver = nullptr;
EXPECT_EQ(add_sacn_merge_receiver(kTestMergeReceiverHandle, &kTestMergeReceiverConfig, &merge_receiver),
kEtcPalErrOk);
for (size_t i = 0u; i < kNumSources; ++i)
{
EXPECT_EQ(add_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(i), false),
kEtcPalErrOk);
}
for (size_t i = 0u; i < kNumSources; ++i)
{
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), kNumSources - i);
remove_sacn_merge_receiver_source(merge_receiver, static_cast<sacn_remote_source_t>(i));
}
EXPECT_EQ(etcpal_rbtree_size(&merge_receiver->sources), 0u);
}
| 36.215365 | 120 | 0.738028 | bruingineer |
c0e29d1aa63bcd5ba3fc737bcaeac7f0ab055c62 | 5,929 | cpp | C++ | Acrylic_Backend/BackendAPIs/Plexi2DRenderer/PlexiBackend/PlexiBackend_Vulkan/vulkanMain.cpp | TriHardStudios/TSA-Software-2019 | c64a1462640124f750ee1d33239f4476ace7fcb6 | [
"Apache-2.0"
] | 2 | 2019-09-03T16:48:20.000Z | 2019-09-03T23:00:48.000Z | Acrylic_Backend/BackendAPIs/Plexi2DRenderer/PlexiBackend/PlexiBackend_Vulkan/vulkanMain.cpp | TriHardStudios/TSA-Software-2019 | c64a1462640124f750ee1d33239f4476ace7fcb6 | [
"Apache-2.0"
] | 8 | 2019-11-22T21:34:15.000Z | 2020-02-24T16:25:21.000Z | Acrylic_Backend/BackendAPIs/Plexi2DRenderer/PlexiBackend/PlexiBackend_Vulkan/vulkanMain.cpp | TriHardStudios/TSA-Software-2019 | c64a1462640124f750ee1d33239f4476ace7fcb6 | [
"Apache-2.0"
] | null | null | null | //Dependencies
//#include "./../../plexi_usrStructs.hpp"
#include "../plexi_shaders.hpp"
#include "../plexi_buffer.hpp"
#include "../plexi_helper.hpp"
#include "vulkanMain.hpp"
#include "./VulkanHelpers/validationLayers.hpp"
#include "./VulkanHelpers/queueFamilies.hpp"
#include "./VulkanHelpers/swapChains.hpp"
bool Vulkan::setRequiredInformation(const PlexiGFX_RequiredInformation &requiredInformation) {
if(requiredInformation.vulkan_EXT_SIZE <= 0){
std::cerr << "ERROR: Required Extensions are missing data: Required Extension Length > 0" << std::endl;
return false;
}
requiredExtensions.reserve(requiredInformation.vulkan_EXT_SIZE);
for(size_t i = 0; i < requiredInformation.vulkan_EXT_SIZE; i++){
requiredExtensions.push_back(requiredInformation.vulkan_DEVICE_EXTENSIONS[i]);
}
this->applicationName = requiredInformation.appName.c_str();
requiredExtensionsSet = !requiredExtensions.empty();
return requiredExtensionsSet;
}
void Vulkan::setOptionInformation(const PlexiGFX_OptionalInformation &optionalInformation) {
if(optionalInformation.vulkan_EXT_SIZE < 0){
std::cerr << "ERROR: Optional Extensions are missing data: Optional Extension Length > 0" << std::endl;
}
if(optionalInformation.vulkan_VALID_LAYER_SIZE < 0){
std::cerr << "ERROR: Optional Validation Layers are missing data: Optional Validation Length > 0" << std::endl;
}
//Todo: Warning if length = 0
optionalExtensions.reserve(optionalInformation.vulkan_EXT_SIZE);
optionalValidationLayers.reserve(optionalInformation.vulkan_VALID_LAYER_SIZE);
for(size_t i = 0; i < optionalInformation.vulkan_EXT_SIZE; i++){
optionalExtensions.push_back(optionalInformation.vulkan_DEVICE_EXTENSIONS[i]);
}
for(size_t i = 0; i < optionalInformation.vulkan_VALID_LAYER_SIZE; i++){
optionalValidationLayers.push_back(optionalInformation.vulkan_VALIDATION_LAYERS[i]);
}
validationLayersEnabled = !optionalValidationLayers.empty();
}
std::vector<const char*> Vulkan::getRequiredExtensions() {
uint32_t glfwExtensionsCount = 0;
const char** glfwExtensions;
std::vector<const char*> extensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionsCount);
extensions.reserve(glfwExtensionsCount);
for(size_t i = 0; i < glfwExtensionsCount; i++){
extensions.push_back(glfwExtensions[i]);
}
if(validationLayersEnabled){
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
//Maybe add status message here
return extensions;
}
void Vulkan::initWindow() {
// glfwInit();
// glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
//
// //glfwWindow = glfwCreateWindow(800, 600, applicationName, glfwGetPrimaryMonitor(), nullptr);//Makes full screen w/ res 800x600
// glfwWindow = glfwCreateWindow(800, 600, applicationName, nullptr, nullptr);
//
// //glfwSetWindowUserPointer(glfwWindow, this);
//
//// glfwSetFramebufferSizeCallback(glfwWindow, frameBufferResizeCallBack);//TODO: Implement Later
}
bool Vulkan::createInstance() {
return false;
// if(!requiredExtensionsSet) {
// std::cerr << "ERROR: No Vulkan Extensions have been set: Ensure that required extensions are set in Plexi Config" << std::endl;
// return false;
// }
// auto extensions = getRequiredExtensions();
//
//
// VkApplicationInfo appInfo = {};
// appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
// appInfo.pApplicationName = applicationName;
// appInfo.applicationVersion = VK_MAKE_VERSION(0,1,0);
// appInfo.pEngineName = "No Engine";
// appInfo.engineVersion = VK_MAKE_VERSION(1,0,0);
// appInfo.apiVersion = VK_API_VERSION_1_0;
//
// VkInstanceCreateInfo instanceInfo = {};
// instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
// instanceInfo.pApplicationInfo = &appInfo;
// instanceInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
// instanceInfo.ppEnabledExtensionNames = extensions.data();
// if(validationLayersEnabled){
// instanceInfo.enabledLayerCount = static_cast<uint32_t>(optionalValidationLayers.size());
// instanceInfo.ppEnabledLayerNames = optionalValidationLayers.data();
// } else{
// instanceInfo.enabledLayerCount = 0;
// }
//
// VkResult err = vkCreateInstance(&instanceInfo, nullptr, &vulkanInstance);
//
//
// if(err != VK_SUCCESS){
// std::cerr << "ERROR: Failed to create Vulkan instance: Device or required extensions may not be supported. Check Plexi Config. VK Error Code: " << err << std::endl;
// return false;
// }
//
// return true;
}
bool Vulkan::isSupported() {
return false;
// if(!requiredExtensionsSet) {
// std::cerr << "ERROR: No Vulkan Extensions have been set: Ensure that required extensions are set in Plexi Config" << std::endl;
// return false;
// }
//
// //validation layer support - Extensions are checked in the instance
// if(validationLayersEnabled){
// if(!checkValidationLayerSupport(optionalValidationLayers)) {
// std::cerr << "WARNING: Validation Layers requested but unsupported: Verify device support and check Plexi Config" << std::endl;
// validationLayersEnabled = false;
// }
// }
//
// initWindow();
//
// return createInstance();
}
bool Vulkan::initBackend() {
return false;
}
void Vulkan::createGraphicsPipeline(const Plexi::Shaders::ShaderCreateInfo& shaderCreateInfo, const Plexi::Buffer::BufferCreateInfo& bufferCreateInfo) {
}
void Vulkan::submitScene() {
}
void Vulkan::destroyWindow() {
glfwDestroyWindow(glfwWindow);
glfwTerminate();
}
void Vulkan::cleanup() {
//clean Up all other stuff up here
vkDestroyInstance(vulkanInstance, nullptr);
destroyWindow();
}
GLFWwindow* Vulkan::getWindowRef() {
return glfwWindow;
}
| 31.876344 | 174 | 0.708889 | TriHardStudios |
c0e3aa189fef7d1f17301079c7f7547aed289bec | 458 | cpp | C++ | oj/sp/ACPC10A.cpp | shivanib01/codes | f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3 | [
"MIT"
] | null | null | null | oj/sp/ACPC10A.cpp | shivanib01/codes | f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3 | [
"MIT"
] | null | null | null | oj/sp/ACPC10A.cpp | shivanib01/codes | f0761472a4b4bea3667c0c13b1c9bcfe5b2597a3 | [
"MIT"
] | null | null | null | /*
* Created by
* Shivani Bhardwaj <shivanib134@gmail.com>
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
float a1,a2,a3;
while(1){
cin>>a1>>a2>>a3;
if(a1==0 && a2==0 &&a3==0)
break;
float APExp=(a3+a1)/2;
if(a2==APExp){
cout<<"AP "<<a1+3*(a2-a1)<<"\n";
}
else{
float r=a2/a1;
cout<<"GP "<<a1*r*r*r<<"\n";
}
}
return 0;
}
| 16.962963 | 44 | 0.427948 | shivanib01 |
c0e4eb218634e84afa44387f81e6e2b349175b78 | 317 | hpp | C++ | include/tdc/util/likely.hpp | herlez/tdc | 3b85ae183c21410e65f1e739736287df46c38d1d | [
"MIT"
] | 1 | 2021-05-06T13:39:22.000Z | 2021-05-06T13:39:22.000Z | include/tdc/util/likely.hpp | herlez/tdc | 3b85ae183c21410e65f1e739736287df46c38d1d | [
"MIT"
] | 1 | 2020-03-07T08:05:20.000Z | 2020-03-07T08:05:20.000Z | include/tdc/util/likely.hpp | herlez/tdc | 3b85ae183c21410e65f1e739736287df46c38d1d | [
"MIT"
] | 2 | 2020-05-27T07:54:43.000Z | 2021-11-18T13:29:14.000Z | #pragma once
namespace tdc {
/// \brief Shortcut for \c __builtin_expect for expressions that are likely \c true.
#define tdc_likely(x) __builtin_expect(x, 1)
/// \brief Shortcut for \c __builtin_expect for expressions that are likely \c false.
#define tdc_unlikely(x) __builtin_expect(x, 0)
} // namespace tdc
| 26.416667 | 85 | 0.747634 | herlez |
c0e664b82f99587986a9e57bec939117aa6be51e | 12,806 | cc | C++ | src/tests/numerics/test_fvm_nabla_validation.cc | wdeconinck/atlas | 8949d2b362b9b5431023a967bcf4ca84f6b8ce05 | [
"Apache-2.0"
] | 3 | 2020-04-28T20:07:25.000Z | 2020-05-01T19:07:00.000Z | src/tests/numerics/test_fvm_nabla_validation.cc | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | null | null | null | src/tests/numerics/test_fvm_nabla_validation.cc | pmarguinaud/atlas | 7e0a1251685e07a5dcccc84f4d9251d5a066e2ee | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright 2013 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
#include <cmath>
#include <iomanip>
#include <iostream>
#include "eckit/config/Resource.h"
#include "atlas/array/MakeView.h"
#include "atlas/field/Field.h"
#include "atlas/field/FieldSet.h"
#include "atlas/grid/Distribution.h"
#include "atlas/grid/Grid.h"
#include "atlas/grid/Partitioner.h"
#include "atlas/mesh/Mesh.h"
#include "atlas/mesh/Nodes.h"
#include "atlas/meshgenerator.h"
#include "atlas/numerics/Nabla.h"
#include "atlas/numerics/fvm/Method.h"
#include "atlas/option.h"
#include "atlas/output/Gmsh.h"
#include "atlas/parallel/mpi/mpi.h"
#include "atlas/util/Config.h"
#include "atlas/util/Constants.h"
#include "atlas/util/CoordinateEnums.h"
#include "atlas/util/Earth.h"
#include "tests/AtlasTestEnvironment.h"
using namespace eckit;
using namespace atlas::numerics;
using namespace atlas::meshgenerator;
using namespace atlas::grid;
namespace atlas {
namespace test {
// This test relates to JIRA issues METV-2657 , MIR-459
static std::string griduid() {
//return "O80";
//return "Slat80";
return "Slat720x360";
}
static double radius() {
return util::Earth::radius();
}
static double beta_in_degrees() {
return 90.;
}
static bool output_gmsh() {
return false;
}
static bool mask_polar_values() {
return false;
}
static int metric_approach() {
// Experimental!!!
// approach = 0 ORIGINAL, DEFAULT
// metric_term cos(y) is multiplied with each wind component
// --> cell-interface: avg = 0.5*( cos(y1)*u1 + cos(y2)*u2 )
// approach = 1:
// metric_term cos(0.5*(y1+y2)) is used at cell interface
// --> cell-interface: avg = 0.5*(u1+u2)*cos(0.5*(y1+y2))
// Results seem to indicate that approach=0 is overall better, although approach=1
// seems to handle pole slightly better (error factor 2 to 4 times lower)
return 0;
}
class SolidBodyRotation {
double radius;
double beta;
double sin_beta;
double cos_beta;
public:
SolidBodyRotation( const double _radius, const double _beta ) : radius{_radius}, beta{_beta} {
sin_beta = std::sin( beta );
cos_beta = std::cos( beta );
}
void wind( const double x, const double y, double& u, double& v ) {
double cos_x = std::cos( x );
double cos_y = std::cos( y );
double sin_x = std::sin( x );
double sin_y = std::sin( y );
u = cos_y * cos_beta + cos_x * sin_y * sin_beta;
v = -sin_x * sin_beta;
}
void vordiv( const double x, const double y, double& vor, double& div ) {
double cos_x = std::cos( x );
double cos_y = std::cos( y );
double sin_x = std::sin( x );
double sin_y = std::sin( y );
// Divergence = 1./(R*cos(y)) * ( d/dx( u ) + d/dy( v * cos(y) ) )
// Vorticity = 1./(R*cos(y)) * ( d/dx( v ) - d/dy( u * cos(y) ) )
double ddx_u = -sin_x * sin_y * sin_beta;
double ddy_cosy_v = ( -sin_x * sin_beta ) * ( -sin_y );
double ddx_v = -cos_x * sin_beta;
double ddy_cosy_u = 2 * cos_y * ( -sin_y ) * cos_beta + ( -sin_y ) * cos_x * sin_y * sin_beta +
cos_y * cos_x * cos_y * sin_beta;
double metric = 1. / ( radius * cos_y );
div = metric * ( ddx_u + ddy_cosy_v );
vor = metric * ( ddx_v - ddy_cosy_u );
}
void wind_magnitude_squared( const double x, const double y, double& f ) {
double u, v;
wind( x, y, u, v );
f = u * u + v * v;
}
void wind_magnitude_squared_gradient( const double x, const double y, double& dfdx, double& dfdy ) {
double cos_x = std::cos( x );
double cos_y = std::cos( y );
double sin_x = std::sin( x );
double sin_y = std::sin( y );
double metric_y = 1. / radius;
double metric_x = metric_y / cos_y;
double u = cos_y * cos_beta + cos_x * sin_y * sin_beta;
double v = -sin_x * sin_beta;
double dudx = metric_x * ( -sin_x * sin_y * sin_beta );
double dudy = metric_y * ( -sin_y * cos_beta + cos_x * cos_y * sin_beta );
double dvdx = metric_x * ( -cos_x * sin_beta );
double dvdy = metric_y * ( 0. );
dfdx = 2 * u * dudx + 2 * v * dvdx;
dfdy = 2 * u * dudy + 2 * v * dvdy;
}
};
FieldSet analytical_fields( const fvm::Method& fvm ) {
constexpr double deg2rad = M_PI / 180.;
const double radius = fvm.radius();
auto lonlat_deg = array::make_view<double, 2>( fvm.mesh().nodes().lonlat() );
FieldSet fields;
auto add_scalar_field = [&]( const std::string& name ) {
return array::make_view<double, 1>(
fields.add( fvm.node_columns().createField<double>( option::name( name ) ) ) );
};
auto add_vector_field = [&]( const std::string& name ) {
return array::make_view<double, 2>( fields.add( fvm.node_columns().createField<double>(
option::name( name ) | option::type( "vector" ) | option::variables( 2 ) ) ) );
};
auto f = add_scalar_field( "f" );
auto uv = add_vector_field( "uv" );
auto u = add_scalar_field( "u" );
auto v = add_scalar_field( "v" );
auto grad_f = add_vector_field( "ref_grad_f" );
auto dfdx = add_scalar_field( "ref_dfdx" );
auto dfdy = add_scalar_field( "ref_dfdy" );
auto div = add_scalar_field( "ref_div" );
auto vor = add_scalar_field( "ref_vor" );
auto flow = SolidBodyRotation{radius, beta_in_degrees() * deg2rad};
auto is_ghost = array::make_view<int, 1>( fvm.mesh().nodes().ghost() );
const idx_t nnodes = fvm.mesh().nodes().size();
for ( idx_t jnode = 0; jnode < nnodes; ++jnode ) {
if ( is_ghost( jnode ) ) {
continue;
}
double x = lonlat_deg( jnode, LON ) * deg2rad;
double y = lonlat_deg( jnode, LAT ) * deg2rad;
flow.wind( x, y, u( jnode ), v( jnode ) );
flow.vordiv( x, y, vor( jnode ), div( jnode ) );
flow.wind_magnitude_squared( x, y, f( jnode ) );
flow.wind_magnitude_squared_gradient( x, y, dfdx( jnode ), dfdy( jnode ) );
uv( jnode, XX ) = u( jnode );
uv( jnode, YY ) = v( jnode );
grad_f( jnode, XX ) = dfdx( jnode );
grad_f( jnode, YY ) = dfdy( jnode );
}
fields.set_dirty();
fields.haloExchange();
return fields;
}
//-----------------------------------------------------------------------------
CASE( "test_analytical" ) {
Grid grid( griduid(), GlobalDomain( -180. ) );
Mesh mesh = MeshGenerator{"structured"}.generate( grid );
fvm::Method fvm( mesh, option::radius( radius() ) );
Nabla nabla( fvm, util::Config( "metric_approach", metric_approach() ) );
FieldSet fields = analytical_fields( fvm );
Field div = fields.add( fvm.node_columns().createField<double>( option::name( "div" ) ) );
Field vor = fields.add( fvm.node_columns().createField<double>( option::name( "vor" ) ) );
Field grad_f =
fields.add( fvm.node_columns().createField<double>( option::name( "grad_f" ) | option::variables( 2 ) ) );
Field dfdx = fields.add( fvm.node_columns().createField<double>( option::name( "dfdx" ) ) );
Field dfdy = fields.add( fvm.node_columns().createField<double>( option::name( "dfdy" ) ) );
auto split = []( const Field& vector, Field& component_x, Field& component_y ) {
auto v = array::make_view<double, 2>( vector );
auto x = array::make_view<double, 1>( component_x );
auto y = array::make_view<double, 1>( component_y );
for ( idx_t j = 0; j < v.shape( 0 ); ++j ) {
x( j ) = v( j, XX );
y( j ) = v( j, YY );
}
};
ATLAS_TRACE_SCOPE( "gradient" ) nabla.gradient( fields["f"], grad_f );
split( grad_f, dfdx, dfdy );
ATLAS_TRACE_SCOPE( "divergence" ) nabla.divergence( fields["uv"], div );
ATLAS_TRACE_SCOPE( "vorticity" ) nabla.curl( fields["uv"], vor );
auto do_mask_polar_values = [&]( Field& field, double mask ) {
using Topology = atlas::mesh::Nodes::Topology;
using Range = atlas::array::Range;
auto node_flags = array::make_view<int, 1>( fvm.node_columns().nodes().flags() );
auto is_polar = [&]( idx_t j ) {
return Topology::check( node_flags( j ), Topology::BC | Topology::NORTH ) ||
Topology::check( node_flags( j ), Topology::BC | Topology::SOUTH );
};
auto apply = [&]( array::LocalView<double, 2>&& view ) {
for ( idx_t j = 0; j < view.shape( 0 ); ++j ) {
if ( is_polar( j ) ) {
for ( idx_t v = 0; v < view.shape( 1 ); ++v ) {
view( j, v ) = mask;
}
}
}
};
if ( field.rank() == 1 ) {
apply( array::make_view<double, 1>( field ).slice( Range::all(), Range::dummy() ) );
}
else if ( field.rank() == 2 ) {
apply( array::make_view<double, 2>( field ).slice( Range::all(), Range::all() ) );
}
};
for ( auto fieldname : std::vector<std::string>{"dfdx", "dfdy", "div", "vor"} ) {
auto err_field = fields.add( fvm.node_columns().createField<double>( option::name( "err_" + fieldname ) ) );
auto err2_field = fields.add( fvm.node_columns().createField<double>( option::name( "err2_" + fieldname ) ) );
auto fld = array::make_view<double, 1>( fields[fieldname] );
auto ref = array::make_view<double, 1>( fields["ref_" + fieldname] );
auto err = array::make_view<double, 1>( fields["err_" + fieldname] );
auto err2 = array::make_view<double, 1>( fields["err2_" + fieldname] );
for ( idx_t j = 0; j < fld.shape( 0 ); ++j ) {
err( j ) = fld( j ) - ref( j );
err2( j ) = err( j ) * err( j );
}
if ( mask_polar_values() ) {
do_mask_polar_values( fields["err_" + fieldname], 0. );
do_mask_polar_values( fields["err2_" + fieldname], 0. );
}
}
fields.haloExchange();
// output to gmsh
if ( output_gmsh() ) {
output::Gmsh{"mesh_2d.msh", util::Config( "coordinates", "lonlat" )}.write( mesh );
output::Gmsh{"mesh_3d.msh", util::Config( "coordinates", "xyz" )}.write( mesh );
output::Gmsh{"fields.msh"}.write( fields );
}
auto minmax_within_error = [&]( const std::string& name, double error ) {
Field field = fields["err_" + name];
error = std::abs( error );
double min, max;
fvm.node_columns().minimum( field, min );
fvm.node_columns().maximum( field, max );
bool success = true;
if ( min < -error ) {
Log::warning() << "minumum " << min << " smaller than error " << -error << std::endl;
success = false;
}
if ( max > error ) {
Log::warning() << "maximum " << max << " greater than error " << error << std::endl;
success = false;
}
Log::info() << name << "\t: minmax error between { " << min << " , " << max << " }" << std::endl;
return success;
};
EXPECT( minmax_within_error( "dfdx", 1.e-11 ) );
EXPECT( minmax_within_error( "dfdy", 1.e-11 ) );
EXPECT( minmax_within_error( "div", 1.e-16 ) );
EXPECT( minmax_within_error( "vor", 1.5e-9 ) );
auto rms_within_error = [&]( const std::string& name, double error ) {
Field field = fields["err2_" + name];
double mean;
idx_t N;
fvm.node_columns().mean( field, mean, N );
double rms = std::sqrt( mean / double( N ) );
bool success = true;
if ( rms > error ) {
Log::warning() << "rms " << rms << " greater than error " << error << std::endl;
success = false;
}
Log::info() << name << "\t: rms error = " << rms << std::endl;
return success;
};
EXPECT( rms_within_error( "dfdx", 1.e-14 ) );
EXPECT( rms_within_error( "dfdy", 1.e-14 ) );
EXPECT( rms_within_error( "div", 5.e-20 ) );
EXPECT( rms_within_error( "vor", 5.e-13 ) );
// error for vorticity seems too high ?
}
//-----------------------------------------------------------------------------
} // namespace test
} // namespace atlas
int main( int argc, char** argv ) {
return atlas::test::run( argc, argv );
}
| 37.887574 | 118 | 0.559972 | wdeconinck |
c0e6c3ab3b5ff7369e7cd7df4378d65641c6d183 | 1,522 | hpp | C++ | include/xtd/wrapped_type.hpp | djmott/xtl | cadb963a3d1ad292033f08f4754c545066be75f7 | [
"BSL-1.0"
] | 6 | 2016-06-30T11:23:33.000Z | 2019-10-22T13:09:49.000Z | include/xtd/wrapped_type.hpp | djmott/xtl | cadb963a3d1ad292033f08f4754c545066be75f7 | [
"BSL-1.0"
] | null | null | null | include/xtd/wrapped_type.hpp | djmott/xtl | cadb963a3d1ad292033f08f4754c545066be75f7 | [
"BSL-1.0"
] | 4 | 2016-07-24T10:38:43.000Z | 2021-04-02T11:18:09.000Z | /** @file
* wraps a type in a class for compiler type deductive distinction
* @copyright David Mott (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details.
*/
#pragma once
namespace xtd {
#define WRAPPED(_type) xtd::wrapped<_type, __COUNTER__>
template <typename _ty, size_t> class wrapped {
_ty _inner;
public:
using value_type = _ty;
template <typename ... _arg_ts> wrapped(_arg_ts...oArgs) : _inner(std::forward<_arg_ts>(oArgs)...) {}
wrapped(wrapped&& src) : _inner(std::move(src._inner)) {}
wrapped(const wrapped& src) : _inner(src._inner) {}
template <typename _ArgT> wrapped& operator=(_ArgT&& oArg) {
_inner = std::move(oArg);
return *this;
}
wrapped& operator=(wrapped&& src) {
_inner = std::move(src._inner);
return *this;
}
wrapped& operator=(const wrapped& src) {
_inner = src._inner;
return *this;
}
value_type& operator*() { return _inner; }
const value_type& operator*() const { return _inner; }
value_type* operator->() { return &_inner; }
const value_type* operator->() const { return &_inner; }
operator value_type() const { return _inner; }
operator value_type&() { return _inner; }
operator const value_type&() const { return _inner; }
value_type& operator()() { return _inner; }
const value_type& operator()() const { return _inner; }
};
} | 29.843137 | 156 | 0.630092 | djmott |
c0e6e0334fa6aac68d0279e612e0b81372372162 | 55,314 | cpp | C++ | lld/lib/ReaderWriter/YAML/ReaderWriterYAML.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | lld/lib/ReaderWriter/YAML/ReaderWriterYAML.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | lld/lib/ReaderWriter/YAML/ReaderWriterYAML.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===- lib/ReaderWriter/YAML/ReaderWriterYAML.cpp -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lld/Core/AbsoluteAtom.h"
#include "lld/Core/ArchiveLibraryFile.h"
#include "lld/Core/Atom.h"
#include "lld/Core/DefinedAtom.h"
#include "lld/Core/Error.h"
#include "lld/Core/File.h"
#include "lld/Core/LinkingContext.h"
#include "lld/Core/Reader.h"
#include "lld/Core/Reference.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "lld/Core/Simple.h"
#include "lld/Core/UndefinedAtom.h"
#include "lld/Core/Writer.h"
#include "lld/ReaderWriter/YamlContext.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <system_error>
#include <vector>
using llvm::file_magic;
using llvm::yaml::MappingTraits;
using llvm::yaml::ScalarEnumerationTraits;
using llvm::yaml::ScalarTraits;
using llvm::yaml::IO;
using llvm::yaml::SequenceTraits;
using llvm::yaml::DocumentListTraits;
using namespace lld;
/// The conversion of Atoms to and from YAML uses LLVM's YAML I/O. This
/// file just defines template specializations on the lld types which control
/// how the mapping is done to and from YAML.
namespace {
/// Used when writing yaml files.
/// In most cases, atoms names are unambiguous, so references can just
/// use the atom name as the target (e.g. target: foo). But in a few
/// cases that does not work, so ref-names are added. These are labels
/// used only in yaml. The labels do not exist in the Atom model.
///
/// One need for ref-names are when atoms have no user supplied name
/// (e.g. c-string literal). Another case is when two object files with
/// identically named static functions are merged (ld -r) into one object file.
/// In that case referencing the function by name is ambiguous, so a unique
/// ref-name is added.
class RefNameBuilder {
public:
RefNameBuilder(const lld::File &file)
: _collisionCount(0), _unnamedCounter(0) {
// visit all atoms
for (const lld::DefinedAtom *atom : file.defined()) {
// Build map of atoms names to detect duplicates
if (!atom->name().empty())
buildDuplicateNameMap(*atom);
// Find references to unnamed atoms and create ref-names for them.
for (const lld::Reference *ref : *atom) {
// create refname for any unnamed reference target
const lld::Atom *target = ref->target();
if ((target != nullptr) && target->name().empty()) {
std::string storage;
llvm::raw_string_ostream buffer(storage);
buffer << llvm::format("L%03d", _unnamedCounter++);
StringRef newName = copyString(buffer.str());
_refNames[target] = std::string(newName);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "unnamed atom: creating ref-name: '"
<< newName << "' ("
<< (const void *)newName.data() << ", "
<< newName.size() << ")\n");
}
}
}
for (const lld::UndefinedAtom *undefAtom : file.undefined()) {
buildDuplicateNameMap(*undefAtom);
}
for (const lld::SharedLibraryAtom *shlibAtom : file.sharedLibrary()) {
buildDuplicateNameMap(*shlibAtom);
}
for (const lld::AbsoluteAtom *absAtom : file.absolute()) {
if (!absAtom->name().empty())
buildDuplicateNameMap(*absAtom);
}
}
void buildDuplicateNameMap(const lld::Atom &atom) {
assert(!atom.name().empty());
NameToAtom::iterator pos = _nameMap.find(atom.name());
if (pos != _nameMap.end()) {
// Found name collision, give each a unique ref-name.
std::string Storage;
llvm::raw_string_ostream buffer(Storage);
buffer << atom.name() << llvm::format(".%03d", ++_collisionCount);
StringRef newName = copyString(buffer.str());
_refNames[&atom] = std::string(newName);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "name collision: creating ref-name: '"
<< newName << "' ("
<< (const void *)newName.data()
<< ", " << newName.size() << ")\n");
const lld::Atom *prevAtom = pos->second;
AtomToRefName::iterator pos2 = _refNames.find(prevAtom);
if (pos2 == _refNames.end()) {
// Only create ref-name for previous if none already created.
std::string Storage2;
llvm::raw_string_ostream buffer2(Storage2);
buffer2 << prevAtom->name() << llvm::format(".%03d", ++_collisionCount);
StringRef newName2 = copyString(buffer2.str());
_refNames[prevAtom] = std::string(newName2);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "name collision: creating ref-name: '"
<< newName2 << "' ("
<< (const void *)newName2.data() << ", "
<< newName2.size() << ")\n");
}
} else {
// First time we've seen this name, just add it to map.
_nameMap[atom.name()] = &atom;
DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
<< "atom name seen for first time: '"
<< atom.name() << "' ("
<< (const void *)atom.name().data()
<< ", " << atom.name().size() << ")\n");
}
}
bool hasRefName(const lld::Atom *atom) { return _refNames.count(atom); }
StringRef refName(const lld::Atom *atom) {
return _refNames.find(atom)->second;
}
private:
typedef llvm::StringMap<const lld::Atom *> NameToAtom;
typedef llvm::DenseMap<const lld::Atom *, std::string> AtomToRefName;
// Allocate a new copy of this string in _storage, so the strings
// can be freed when RefNameBuilder is destroyed.
StringRef copyString(StringRef str) {
char *s = _storage.Allocate<char>(str.size());
memcpy(s, str.data(), str.size());
return StringRef(s, str.size());
}
unsigned int _collisionCount;
unsigned int _unnamedCounter;
NameToAtom _nameMap;
AtomToRefName _refNames;
llvm::BumpPtrAllocator _storage;
};
/// Used when reading yaml files to find the target of a reference
/// that could be a name or ref-name.
class RefNameResolver {
public:
RefNameResolver(const lld::File *file, IO &io);
const lld::Atom *lookup(StringRef name) const {
NameToAtom::const_iterator pos = _nameMap.find(name);
if (pos != _nameMap.end())
return pos->second;
_io.setError(Twine("no such atom name: ") + name);
return nullptr;
}
private:
typedef llvm::StringMap<const lld::Atom *> NameToAtom;
void add(StringRef name, const lld::Atom *atom) {
if (_nameMap.count(name)) {
_io.setError(Twine("duplicate atom name: ") + name);
} else {
_nameMap[name] = atom;
}
}
IO &_io;
NameToAtom _nameMap;
};
/// Mapping of Atoms.
template <typename T> class AtomList {
using Ty = std::vector<OwningAtomPtr<T>>;
public:
typename Ty::iterator begin() { return _atoms.begin(); }
typename Ty::iterator end() { return _atoms.end(); }
Ty _atoms;
};
/// Mapping of kind: field in yaml files.
enum FileKinds {
fileKindObjectAtoms, // atom based object file encoded in yaml
fileKindArchive, // static archive library encoded in yaml
fileKindObjectMachO // mach-o object files encoded in yaml
};
struct ArchMember {
FileKinds _kind;
StringRef _name;
const lld::File *_content;
};
// The content bytes in a DefinedAtom are just uint8_t but we want
// special formatting, so define a strong type.
LLVM_YAML_STRONG_TYPEDEF(uint8_t, ImplicitHex8)
// SharedLibraryAtoms have a bool canBeNull() method which we'd like to be
// more readable than just true/false.
LLVM_YAML_STRONG_TYPEDEF(bool, ShlibCanBeNull)
// lld::Reference::Kind is a tuple of <namespace, arch, value>.
// For yaml, we just want one string that encapsulates the tuple.
struct RefKind {
Reference::KindNamespace ns;
Reference::KindArch arch;
Reference::KindValue value;
};
} // end anonymous namespace
LLVM_YAML_IS_SEQUENCE_VECTOR(ArchMember)
LLVM_YAML_IS_SEQUENCE_VECTOR(const lld::Reference *)
// Always write DefinedAtoms content bytes as a flow sequence.
LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(ImplicitHex8)
// for compatibility with gcc-4.7 in C++11 mode, add extra namespace
namespace llvm {
namespace yaml {
// This is a custom formatter for RefKind
template <> struct ScalarTraits<RefKind> {
static void output(const RefKind &kind, void *ctxt, raw_ostream &out) {
assert(ctxt != nullptr);
YamlContext *info = reinterpret_cast<YamlContext *>(ctxt);
assert(info->_registry);
StringRef str;
if (info->_registry->referenceKindToString(kind.ns, kind.arch, kind.value,
str))
out << str;
else
out << (int)(kind.ns) << "-" << (int)(kind.arch) << "-" << kind.value;
}
static StringRef input(StringRef scalar, void *ctxt, RefKind &kind) {
assert(ctxt != nullptr);
YamlContext *info = reinterpret_cast<YamlContext *>(ctxt);
assert(info->_registry);
if (info->_registry->referenceKindFromString(scalar, kind.ns, kind.arch,
kind.value))
return StringRef();
return StringRef("unknown reference kind");
}
static QuotingType mustQuote(StringRef) { return QuotingType::None; }
};
template <> struct ScalarEnumerationTraits<lld::File::Kind> {
static void enumeration(IO &io, lld::File::Kind &value) {
io.enumCase(value, "error-object", lld::File::kindErrorObject);
io.enumCase(value, "object", lld::File::kindMachObject);
io.enumCase(value, "shared-library", lld::File::kindSharedLibrary);
io.enumCase(value, "static-library", lld::File::kindArchiveLibrary);
}
};
template <> struct ScalarEnumerationTraits<lld::Atom::Scope> {
static void enumeration(IO &io, lld::Atom::Scope &value) {
io.enumCase(value, "global", lld::Atom::scopeGlobal);
io.enumCase(value, "hidden", lld::Atom::scopeLinkageUnit);
io.enumCase(value, "static", lld::Atom::scopeTranslationUnit);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::SectionChoice> {
static void enumeration(IO &io, lld::DefinedAtom::SectionChoice &value) {
io.enumCase(value, "content", lld::DefinedAtom::sectionBasedOnContent);
io.enumCase(value, "custom", lld::DefinedAtom::sectionCustomPreferred);
io.enumCase(value, "custom-required",
lld::DefinedAtom::sectionCustomRequired);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::Interposable> {
static void enumeration(IO &io, lld::DefinedAtom::Interposable &value) {
io.enumCase(value, "no", DefinedAtom::interposeNo);
io.enumCase(value, "yes", DefinedAtom::interposeYes);
io.enumCase(value, "yes-and-weak", DefinedAtom::interposeYesAndRuntimeWeak);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::Merge> {
static void enumeration(IO &io, lld::DefinedAtom::Merge &value) {
io.enumCase(value, "no", lld::DefinedAtom::mergeNo);
io.enumCase(value, "as-tentative", lld::DefinedAtom::mergeAsTentative);
io.enumCase(value, "as-weak", lld::DefinedAtom::mergeAsWeak);
io.enumCase(value, "as-addressed-weak",
lld::DefinedAtom::mergeAsWeakAndAddressUsed);
io.enumCase(value, "by-content", lld::DefinedAtom::mergeByContent);
io.enumCase(value, "same-name-and-size",
lld::DefinedAtom::mergeSameNameAndSize);
io.enumCase(value, "largest", lld::DefinedAtom::mergeByLargestSection);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::DeadStripKind> {
static void enumeration(IO &io, lld::DefinedAtom::DeadStripKind &value) {
io.enumCase(value, "normal", lld::DefinedAtom::deadStripNormal);
io.enumCase(value, "never", lld::DefinedAtom::deadStripNever);
io.enumCase(value, "always", lld::DefinedAtom::deadStripAlways);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::DynamicExport> {
static void enumeration(IO &io, lld::DefinedAtom::DynamicExport &value) {
io.enumCase(value, "normal", lld::DefinedAtom::dynamicExportNormal);
io.enumCase(value, "always", lld::DefinedAtom::dynamicExportAlways);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::CodeModel> {
static void enumeration(IO &io, lld::DefinedAtom::CodeModel &value) {
io.enumCase(value, "none", lld::DefinedAtom::codeNA);
io.enumCase(value, "mips-pic", lld::DefinedAtom::codeMipsPIC);
io.enumCase(value, "mips-micro", lld::DefinedAtom::codeMipsMicro);
io.enumCase(value, "mips-micro-pic", lld::DefinedAtom::codeMipsMicroPIC);
io.enumCase(value, "mips-16", lld::DefinedAtom::codeMips16);
io.enumCase(value, "arm-thumb", lld::DefinedAtom::codeARMThumb);
io.enumCase(value, "arm-a", lld::DefinedAtom::codeARM_a);
io.enumCase(value, "arm-d", lld::DefinedAtom::codeARM_d);
io.enumCase(value, "arm-t", lld::DefinedAtom::codeARM_t);
}
};
template <>
struct ScalarEnumerationTraits<lld::DefinedAtom::ContentPermissions> {
static void enumeration(IO &io, lld::DefinedAtom::ContentPermissions &value) {
io.enumCase(value, "---", lld::DefinedAtom::perm___);
io.enumCase(value, "r--", lld::DefinedAtom::permR__);
io.enumCase(value, "r-x", lld::DefinedAtom::permR_X);
io.enumCase(value, "rw-", lld::DefinedAtom::permRW_);
io.enumCase(value, "rwx", lld::DefinedAtom::permRWX);
io.enumCase(value, "rw-l", lld::DefinedAtom::permRW_L);
io.enumCase(value, "unknown", lld::DefinedAtom::permUnknown);
}
};
template <> struct ScalarEnumerationTraits<lld::DefinedAtom::ContentType> {
static void enumeration(IO &io, lld::DefinedAtom::ContentType &value) {
io.enumCase(value, "unknown", DefinedAtom::typeUnknown);
io.enumCase(value, "code", DefinedAtom::typeCode);
io.enumCase(value, "stub", DefinedAtom::typeStub);
io.enumCase(value, "constant", DefinedAtom::typeConstant);
io.enumCase(value, "data", DefinedAtom::typeData);
io.enumCase(value, "quick-data", DefinedAtom::typeDataFast);
io.enumCase(value, "zero-fill", DefinedAtom::typeZeroFill);
io.enumCase(value, "zero-fill-quick", DefinedAtom::typeZeroFillFast);
io.enumCase(value, "const-data", DefinedAtom::typeConstData);
io.enumCase(value, "got", DefinedAtom::typeGOT);
io.enumCase(value, "resolver", DefinedAtom::typeResolver);
io.enumCase(value, "branch-island", DefinedAtom::typeBranchIsland);
io.enumCase(value, "branch-shim", DefinedAtom::typeBranchShim);
io.enumCase(value, "stub-helper", DefinedAtom::typeStubHelper);
io.enumCase(value, "c-string", DefinedAtom::typeCString);
io.enumCase(value, "utf16-string", DefinedAtom::typeUTF16String);
io.enumCase(value, "unwind-cfi", DefinedAtom::typeCFI);
io.enumCase(value, "unwind-lsda", DefinedAtom::typeLSDA);
io.enumCase(value, "const-4-byte", DefinedAtom::typeLiteral4);
io.enumCase(value, "const-8-byte", DefinedAtom::typeLiteral8);
io.enumCase(value, "const-16-byte", DefinedAtom::typeLiteral16);
io.enumCase(value, "lazy-pointer", DefinedAtom::typeLazyPointer);
io.enumCase(value, "lazy-dylib-pointer",
DefinedAtom::typeLazyDylibPointer);
io.enumCase(value, "cfstring", DefinedAtom::typeCFString);
io.enumCase(value, "initializer-pointer",
DefinedAtom::typeInitializerPtr);
io.enumCase(value, "terminator-pointer",
DefinedAtom::typeTerminatorPtr);
io.enumCase(value, "c-string-pointer",DefinedAtom::typeCStringPtr);
io.enumCase(value, "objc-class-pointer",
DefinedAtom::typeObjCClassPtr);
io.enumCase(value, "objc-category-list",
DefinedAtom::typeObjC2CategoryList);
io.enumCase(value, "objc-image-info",
DefinedAtom::typeObjCImageInfo);
io.enumCase(value, "objc-method-list",
DefinedAtom::typeObjCMethodList);
io.enumCase(value, "objc-class1", DefinedAtom::typeObjC1Class);
io.enumCase(value, "dtraceDOF", DefinedAtom::typeDTraceDOF);
io.enumCase(value, "interposing-tuples",
DefinedAtom::typeInterposingTuples);
io.enumCase(value, "lto-temp", DefinedAtom::typeTempLTO);
io.enumCase(value, "compact-unwind", DefinedAtom::typeCompactUnwindInfo);
io.enumCase(value, "unwind-info", DefinedAtom::typeProcessedUnwindInfo);
io.enumCase(value, "tlv-thunk", DefinedAtom::typeThunkTLV);
io.enumCase(value, "tlv-data", DefinedAtom::typeTLVInitialData);
io.enumCase(value, "tlv-zero-fill", DefinedAtom::typeTLVInitialZeroFill);
io.enumCase(value, "tlv-initializer-ptr",
DefinedAtom::typeTLVInitializerPtr);
io.enumCase(value, "mach_header", DefinedAtom::typeMachHeader);
io.enumCase(value, "dso_handle", DefinedAtom::typeDSOHandle);
io.enumCase(value, "sectcreate", DefinedAtom::typeSectCreate);
}
};
template <> struct ScalarEnumerationTraits<lld::UndefinedAtom::CanBeNull> {
static void enumeration(IO &io, lld::UndefinedAtom::CanBeNull &value) {
io.enumCase(value, "never", lld::UndefinedAtom::canBeNullNever);
io.enumCase(value, "at-runtime", lld::UndefinedAtom::canBeNullAtRuntime);
io.enumCase(value, "at-buildtime",lld::UndefinedAtom::canBeNullAtBuildtime);
}
};
template <> struct ScalarEnumerationTraits<ShlibCanBeNull> {
static void enumeration(IO &io, ShlibCanBeNull &value) {
io.enumCase(value, "never", false);
io.enumCase(value, "at-runtime", true);
}
};
template <>
struct ScalarEnumerationTraits<lld::SharedLibraryAtom::Type> {
static void enumeration(IO &io, lld::SharedLibraryAtom::Type &value) {
io.enumCase(value, "code", lld::SharedLibraryAtom::Type::Code);
io.enumCase(value, "data", lld::SharedLibraryAtom::Type::Data);
io.enumCase(value, "unknown", lld::SharedLibraryAtom::Type::Unknown);
}
};
/// This is a custom formatter for lld::DefinedAtom::Alignment. Values look
/// like:
/// 8 # 8-byte aligned
/// 7 mod 16 # 16-byte aligned plus 7 bytes
template <> struct ScalarTraits<lld::DefinedAtom::Alignment> {
static void output(const lld::DefinedAtom::Alignment &value, void *ctxt,
raw_ostream &out) {
if (value.modulus == 0) {
out << llvm::format("%d", value.value);
} else {
out << llvm::format("%d mod %d", value.modulus, value.value);
}
}
static StringRef input(StringRef scalar, void *ctxt,
lld::DefinedAtom::Alignment &value) {
value.modulus = 0;
size_t modStart = scalar.find("mod");
if (modStart != StringRef::npos) {
StringRef modStr = scalar.slice(0, modStart);
modStr = modStr.rtrim();
unsigned int modulus;
if (modStr.getAsInteger(0, modulus)) {
return "malformed alignment modulus";
}
value.modulus = modulus;
scalar = scalar.drop_front(modStart + 3);
scalar = scalar.ltrim();
}
unsigned int power;
if (scalar.getAsInteger(0, power)) {
return "malformed alignment power";
}
value.value = power;
if (value.modulus >= power) {
return "malformed alignment, modulus too large for power";
}
return StringRef(); // returning empty string means success
}
static QuotingType mustQuote(StringRef) { return QuotingType::None; }
};
template <> struct ScalarEnumerationTraits<FileKinds> {
static void enumeration(IO &io, FileKinds &value) {
io.enumCase(value, "object", fileKindObjectAtoms);
io.enumCase(value, "archive", fileKindArchive);
io.enumCase(value, "object-mach-o", fileKindObjectMachO);
}
};
template <> struct MappingTraits<ArchMember> {
static void mapping(IO &io, ArchMember &member) {
io.mapOptional("kind", member._kind, fileKindObjectAtoms);
io.mapOptional("name", member._name);
io.mapRequired("content", member._content);
}
};
// Declare that an AtomList is a yaml sequence.
template <typename T> struct SequenceTraits<AtomList<T> > {
static size_t size(IO &io, AtomList<T> &seq) { return seq._atoms.size(); }
static T *&element(IO &io, AtomList<T> &seq, size_t index) {
if (index >= seq._atoms.size())
seq._atoms.resize(index + 1);
return seq._atoms[index].get();
}
};
// Declare that an AtomRange is a yaml sequence.
template <typename T> struct SequenceTraits<File::AtomRange<T> > {
static size_t size(IO &io, File::AtomRange<T> &seq) { return seq.size(); }
static T *&element(IO &io, File::AtomRange<T> &seq, size_t index) {
assert(io.outputting() && "AtomRange only used when outputting");
assert(index < seq.size() && "Out of range access");
return seq[index].get();
}
};
// Used to allow DefinedAtom content bytes to be a flow sequence of
// two-digit hex numbers without the leading 0x (e.g. FF, 04, 0A)
template <> struct ScalarTraits<ImplicitHex8> {
static void output(const ImplicitHex8 &val, void *, raw_ostream &out) {
uint8_t num = val;
out << llvm::format("%02X", num);
}
static StringRef input(StringRef str, void *, ImplicitHex8 &val) {
unsigned long long n;
if (getAsUnsignedInteger(str, 16, n))
return "invalid two-digit-hex number";
if (n > 0xFF)
return "out of range two-digit-hex number";
val = n;
return StringRef(); // returning empty string means success
}
static QuotingType mustQuote(StringRef) { return QuotingType::None; }
};
// YAML conversion for std::vector<const lld::File*>
template <> struct DocumentListTraits<std::vector<const lld::File *> > {
static size_t size(IO &io, std::vector<const lld::File *> &seq) {
return seq.size();
}
static const lld::File *&element(IO &io, std::vector<const lld::File *> &seq,
size_t index) {
if (index >= seq.size())
seq.resize(index + 1);
return seq[index];
}
};
// YAML conversion for const lld::File*
template <> struct MappingTraits<const lld::File *> {
class NormArchiveFile : public lld::ArchiveLibraryFile {
public:
NormArchiveFile(IO &io) : ArchiveLibraryFile("") {}
NormArchiveFile(IO &io, const lld::File *file)
: ArchiveLibraryFile(file->path()), _path(file->path()) {
// If we want to support writing archives, this constructor would
// need to populate _members.
}
const lld::File *denormalize(IO &io) { return this; }
const AtomRange<lld::DefinedAtom> defined() const override {
return _noDefinedAtoms;
}
const AtomRange<lld::UndefinedAtom> undefined() const override {
return _noUndefinedAtoms;
}
const AtomRange<lld::SharedLibraryAtom> sharedLibrary() const override {
return _noSharedLibraryAtoms;
}
const AtomRange<lld::AbsoluteAtom> absolute() const override {
return _noAbsoluteAtoms;
}
void clearAtoms() override {
_noDefinedAtoms.clear();
_noUndefinedAtoms.clear();
_noSharedLibraryAtoms.clear();
_noAbsoluteAtoms.clear();
}
File *find(StringRef name) override {
for (const ArchMember &member : _members)
for (const lld::DefinedAtom *atom : member._content->defined())
if (name == atom->name())
return const_cast<File *>(member._content);
return nullptr;
}
std::error_code
parseAllMembers(std::vector<std::unique_ptr<File>> &result) override {
return std::error_code();
}
StringRef _path;
std::vector<ArchMember> _members;
};
class NormalizedFile : public lld::File {
public:
NormalizedFile(IO &io)
: File("", kindNormalizedObject), _io(io), _rnb(nullptr),
_definedAtomsRef(_definedAtoms._atoms),
_undefinedAtomsRef(_undefinedAtoms._atoms),
_sharedLibraryAtomsRef(_sharedLibraryAtoms._atoms),
_absoluteAtomsRef(_absoluteAtoms._atoms) {}
NormalizedFile(IO &io, const lld::File *file)
: File(file->path(), kindNormalizedObject), _io(io),
_rnb(new RefNameBuilder(*file)), _path(file->path()),
_definedAtomsRef(file->defined()),
_undefinedAtomsRef(file->undefined()),
_sharedLibraryAtomsRef(file->sharedLibrary()),
_absoluteAtomsRef(file->absolute()) {
}
~NormalizedFile() override {
}
const lld::File *denormalize(IO &io);
const AtomRange<lld::DefinedAtom> defined() const override {
return _definedAtomsRef;
}
const AtomRange<lld::UndefinedAtom> undefined() const override {
return _undefinedAtomsRef;
}
const AtomRange<lld::SharedLibraryAtom> sharedLibrary() const override {
return _sharedLibraryAtomsRef;
}
const AtomRange<lld::AbsoluteAtom> absolute() const override {
return _absoluteAtomsRef;
}
void clearAtoms() override {
_definedAtoms._atoms.clear();
_undefinedAtoms._atoms.clear();
_sharedLibraryAtoms._atoms.clear();
_absoluteAtoms._atoms.clear();
}
// Allocate a new copy of this string in _storage, so the strings
// can be freed when File is destroyed.
StringRef copyString(StringRef str) {
char *s = _storage.Allocate<char>(str.size());
memcpy(s, str.data(), str.size());
return StringRef(s, str.size());
}
IO &_io;
std::unique_ptr<RefNameBuilder> _rnb;
StringRef _path;
AtomList<lld::DefinedAtom> _definedAtoms;
AtomList<lld::UndefinedAtom> _undefinedAtoms;
AtomList<lld::SharedLibraryAtom> _sharedLibraryAtoms;
AtomList<lld::AbsoluteAtom> _absoluteAtoms;
AtomRange<lld::DefinedAtom> _definedAtomsRef;
AtomRange<lld::UndefinedAtom> _undefinedAtomsRef;
AtomRange<lld::SharedLibraryAtom> _sharedLibraryAtomsRef;
AtomRange<lld::AbsoluteAtom> _absoluteAtomsRef;
llvm::BumpPtrAllocator _storage;
};
static void mapping(IO &io, const lld::File *&file) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
// Let any register tag handler process this.
if (info->_registry && info->_registry->handleTaggedDoc(io, file))
return;
// If no registered handler claims this tag and there is no tag,
// grandfather in as "!native".
if (io.mapTag("!native", true) || io.mapTag("tag:yaml.org,2002:map"))
mappingAtoms(io, file);
}
static void mappingAtoms(IO &io, const lld::File *&file) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormalizedFile, const lld::File *>
keys(io, file, nullptr);
assert(info != nullptr);
info->_file = keys.operator->();
io.mapOptional("path", keys->_path);
if (io.outputting()) {
io.mapOptional("defined-atoms", keys->_definedAtomsRef);
io.mapOptional("undefined-atoms", keys->_undefinedAtomsRef);
io.mapOptional("shared-library-atoms", keys->_sharedLibraryAtomsRef);
io.mapOptional("absolute-atoms", keys->_absoluteAtomsRef);
} else {
io.mapOptional("defined-atoms", keys->_definedAtoms);
io.mapOptional("undefined-atoms", keys->_undefinedAtoms);
io.mapOptional("shared-library-atoms", keys->_sharedLibraryAtoms);
io.mapOptional("absolute-atoms", keys->_absoluteAtoms);
}
}
static void mappingArchive(IO &io, const lld::File *&file) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormArchiveFile, const lld::File *>
keys(io, file, &info->_file->allocator());
io.mapOptional("path", keys->_path);
io.mapOptional("members", keys->_members);
}
};
// YAML conversion for const lld::Reference*
template <> struct MappingTraits<const lld::Reference *> {
class NormalizedReference : public lld::Reference {
public:
NormalizedReference(IO &io)
: lld::Reference(lld::Reference::KindNamespace::all,
lld::Reference::KindArch::all, 0),
_target(nullptr), _offset(0), _addend(0), _tag(0) {}
NormalizedReference(IO &io, const lld::Reference *ref)
: lld::Reference(ref->kindNamespace(), ref->kindArch(),
ref->kindValue()),
_target(nullptr), _targetName(targetName(io, ref)),
_offset(ref->offsetInAtom()), _addend(ref->addend()),
_tag(ref->tag()) {
_mappedKind.ns = ref->kindNamespace();
_mappedKind.arch = ref->kindArch();
_mappedKind.value = ref->kindValue();
}
const lld::Reference *denormalize(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
if (!_targetName.empty())
_targetName = f->copyString(_targetName);
DEBUG_WITH_TYPE("WriterYAML", llvm::dbgs()
<< "created Reference to name: '"
<< _targetName << "' ("
<< (const void *)_targetName.data()
<< ", " << _targetName.size() << ")\n");
setKindNamespace(_mappedKind.ns);
setKindArch(_mappedKind.arch);
setKindValue(_mappedKind.value);
return this;
}
void bind(const RefNameResolver &);
static StringRef targetName(IO &io, const lld::Reference *ref);
uint64_t offsetInAtom() const override { return _offset; }
const lld::Atom *target() const override { return _target; }
Addend addend() const override { return _addend; }
void setAddend(Addend a) override { _addend = a; }
void setTarget(const lld::Atom *a) override { _target = a; }
const lld::Atom *_target;
StringRef _targetName;
uint32_t _offset;
Addend _addend;
RefKind _mappedKind;
uint32_t _tag;
};
static void mapping(IO &io, const lld::Reference *&ref) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormalizedReference, const lld::Reference *> keys(
io, ref, &info->_file->allocator());
io.mapRequired("kind", keys->_mappedKind);
io.mapOptional("offset", keys->_offset);
io.mapOptional("target", keys->_targetName);
io.mapOptional("addend", keys->_addend, (lld::Reference::Addend)0);
io.mapOptional("tag", keys->_tag, 0u);
}
};
// YAML conversion for const lld::DefinedAtom*
template <> struct MappingTraits<const lld::DefinedAtom *> {
class NormalizedAtom : public lld::DefinedAtom {
public:
NormalizedAtom(IO &io)
: _file(fileFromContext(io)), _contentType(), _alignment(1) {
static uint32_t ordinalCounter = 1;
_ordinal = ordinalCounter++;
}
NormalizedAtom(IO &io, const lld::DefinedAtom *atom)
: _file(fileFromContext(io)), _name(atom->name()),
_scope(atom->scope()), _interpose(atom->interposable()),
_merge(atom->merge()), _contentType(atom->contentType()),
_alignment(atom->alignment()), _sectionChoice(atom->sectionChoice()),
_deadStrip(atom->deadStrip()), _dynamicExport(atom->dynamicExport()),
_codeModel(atom->codeModel()),
_permissions(atom->permissions()), _size(atom->size()),
_sectionName(atom->customSectionName()),
_sectionSize(atom->sectionSize()) {
for (const lld::Reference *r : *atom)
_references.push_back(r);
if (!atom->occupiesDiskSpace())
return;
ArrayRef<uint8_t> cont = atom->rawContent();
_content.reserve(cont.size());
for (uint8_t x : cont)
_content.push_back(x);
}
~NormalizedAtom() override = default;
const lld::DefinedAtom *denormalize(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
if (!_name.empty())
_name = f->copyString(_name);
if (!_refName.empty())
_refName = f->copyString(_refName);
if (!_sectionName.empty())
_sectionName = f->copyString(_sectionName);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "created DefinedAtom named: '" << _name
<< "' (" << (const void *)_name.data()
<< ", " << _name.size() << ")\n");
return this;
}
void bind(const RefNameResolver &);
// Extract current File object from YAML I/O parsing context
const lld::File &fileFromContext(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
assert(info->_file != nullptr);
return *info->_file;
}
const lld::File &file() const override { return _file; }
StringRef name() const override { return _name; }
uint64_t size() const override { return _size; }
Scope scope() const override { return _scope; }
Interposable interposable() const override { return _interpose; }
Merge merge() const override { return _merge; }
ContentType contentType() const override { return _contentType; }
Alignment alignment() const override { return _alignment; }
SectionChoice sectionChoice() const override { return _sectionChoice; }
StringRef customSectionName() const override { return _sectionName; }
uint64_t sectionSize() const override { return _sectionSize; }
DeadStripKind deadStrip() const override { return _deadStrip; }
DynamicExport dynamicExport() const override { return _dynamicExport; }
CodeModel codeModel() const override { return _codeModel; }
ContentPermissions permissions() const override { return _permissions; }
ArrayRef<uint8_t> rawContent() const override {
if (!occupiesDiskSpace())
return ArrayRef<uint8_t>();
return ArrayRef<uint8_t>(
reinterpret_cast<const uint8_t *>(_content.data()), _content.size());
}
uint64_t ordinal() const override { return _ordinal; }
reference_iterator begin() const override {
uintptr_t index = 0;
const void *it = reinterpret_cast<const void *>(index);
return reference_iterator(*this, it);
}
reference_iterator end() const override {
uintptr_t index = _references.size();
const void *it = reinterpret_cast<const void *>(index);
return reference_iterator(*this, it);
}
const lld::Reference *derefIterator(const void *it) const override {
uintptr_t index = reinterpret_cast<uintptr_t>(it);
assert(index < _references.size());
return _references[index];
}
void incrementIterator(const void *&it) const override {
uintptr_t index = reinterpret_cast<uintptr_t>(it);
++index;
it = reinterpret_cast<const void *>(index);
}
void addReference(Reference::KindNamespace ns,
Reference::KindArch arch,
Reference::KindValue kindValue, uint64_t off,
const Atom *target, Reference::Addend a) override {
assert(target && "trying to create reference to nothing");
auto node = new (file().allocator()) SimpleReference(ns, arch, kindValue,
off, target, a);
_references.push_back(node);
}
const lld::File &_file;
StringRef _name;
StringRef _refName;
Scope _scope;
Interposable _interpose;
Merge _merge;
ContentType _contentType;
Alignment _alignment;
SectionChoice _sectionChoice;
DeadStripKind _deadStrip;
DynamicExport _dynamicExport;
CodeModel _codeModel;
ContentPermissions _permissions;
uint32_t _ordinal;
std::vector<ImplicitHex8> _content;
uint64_t _size;
StringRef _sectionName;
uint64_t _sectionSize;
std::vector<const lld::Reference *> _references;
};
static void mapping(IO &io, const lld::DefinedAtom *&atom) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormalizedAtom, const lld::DefinedAtom *> keys(
io, atom, &info->_file->allocator());
if (io.outputting()) {
// If writing YAML, check if atom needs a ref-name.
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
assert(info != nullptr);
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
assert(f);
assert(f->_rnb);
if (f->_rnb->hasRefName(atom)) {
keys->_refName = f->_rnb->refName(atom);
}
}
io.mapOptional("name", keys->_name, StringRef());
io.mapOptional("ref-name", keys->_refName, StringRef());
io.mapOptional("scope", keys->_scope,
DefinedAtom::scopeTranslationUnit);
io.mapOptional("type", keys->_contentType,
DefinedAtom::typeCode);
io.mapOptional("content", keys->_content);
io.mapOptional("size", keys->_size, (uint64_t)keys->_content.size());
io.mapOptional("interposable", keys->_interpose,
DefinedAtom::interposeNo);
io.mapOptional("merge", keys->_merge, DefinedAtom::mergeNo);
io.mapOptional("alignment", keys->_alignment,
DefinedAtom::Alignment(1));
io.mapOptional("section-choice", keys->_sectionChoice,
DefinedAtom::sectionBasedOnContent);
io.mapOptional("section-name", keys->_sectionName, StringRef());
io.mapOptional("section-size", keys->_sectionSize, (uint64_t)0);
io.mapOptional("dead-strip", keys->_deadStrip,
DefinedAtom::deadStripNormal);
io.mapOptional("dynamic-export", keys->_dynamicExport,
DefinedAtom::dynamicExportNormal);
io.mapOptional("code-model", keys->_codeModel, DefinedAtom::codeNA);
// default permissions based on content type
io.mapOptional("permissions", keys->_permissions,
DefinedAtom::permissions(
keys->_contentType));
io.mapOptional("references", keys->_references);
}
};
template <> struct MappingTraits<lld::DefinedAtom *> {
static void mapping(IO &io, lld::DefinedAtom *&atom) {
const lld::DefinedAtom *atomPtr = atom;
MappingTraits<const lld::DefinedAtom *>::mapping(io, atomPtr);
atom = const_cast<lld::DefinedAtom *>(atomPtr);
}
};
// YAML conversion for const lld::UndefinedAtom*
template <> struct MappingTraits<const lld::UndefinedAtom *> {
class NormalizedAtom : public lld::UndefinedAtom {
public:
NormalizedAtom(IO &io)
: _file(fileFromContext(io)), _canBeNull(canBeNullNever) {}
NormalizedAtom(IO &io, const lld::UndefinedAtom *atom)
: _file(fileFromContext(io)), _name(atom->name()),
_canBeNull(atom->canBeNull()) {}
~NormalizedAtom() override = default;
const lld::UndefinedAtom *denormalize(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
if (!_name.empty())
_name = f->copyString(_name);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "created UndefinedAtom named: '" << _name
<< "' (" << (const void *)_name.data() << ", "
<< _name.size() << ")\n");
return this;
}
// Extract current File object from YAML I/O parsing context
const lld::File &fileFromContext(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
assert(info->_file != nullptr);
return *info->_file;
}
const lld::File &file() const override { return _file; }
StringRef name() const override { return _name; }
CanBeNull canBeNull() const override { return _canBeNull; }
const lld::File &_file;
StringRef _name;
CanBeNull _canBeNull;
};
static void mapping(IO &io, const lld::UndefinedAtom *&atom) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormalizedAtom, const lld::UndefinedAtom *> keys(
io, atom, &info->_file->allocator());
io.mapRequired("name", keys->_name);
io.mapOptional("can-be-null", keys->_canBeNull,
lld::UndefinedAtom::canBeNullNever);
}
};
template <> struct MappingTraits<lld::UndefinedAtom *> {
static void mapping(IO &io, lld::UndefinedAtom *&atom) {
const lld::UndefinedAtom *atomPtr = atom;
MappingTraits<const lld::UndefinedAtom *>::mapping(io, atomPtr);
atom = const_cast<lld::UndefinedAtom *>(atomPtr);
}
};
// YAML conversion for const lld::SharedLibraryAtom*
template <> struct MappingTraits<const lld::SharedLibraryAtom *> {
class NormalizedAtom : public lld::SharedLibraryAtom {
public:
NormalizedAtom(IO &io)
: _file(fileFromContext(io)), _canBeNull(false),
_type(Type::Unknown), _size(0) {}
NormalizedAtom(IO &io, const lld::SharedLibraryAtom *atom)
: _file(fileFromContext(io)), _name(atom->name()),
_loadName(atom->loadName()), _canBeNull(atom->canBeNullAtRuntime()),
_type(atom->type()), _size(atom->size()) {}
~NormalizedAtom() override = default;
const lld::SharedLibraryAtom *denormalize(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
if (!_name.empty())
_name = f->copyString(_name);
if (!_loadName.empty())
_loadName = f->copyString(_loadName);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "created SharedLibraryAtom named: '"
<< _name << "' ("
<< (const void *)_name.data()
<< ", " << _name.size() << ")\n");
return this;
}
// Extract current File object from YAML I/O parsing context
const lld::File &fileFromContext(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
assert(info->_file != nullptr);
return *info->_file;
}
const lld::File &file() const override { return _file; }
StringRef name() const override { return _name; }
StringRef loadName() const override { return _loadName; }
bool canBeNullAtRuntime() const override { return _canBeNull; }
Type type() const override { return _type; }
uint64_t size() const override { return _size; }
const lld::File &_file;
StringRef _name;
StringRef _loadName;
ShlibCanBeNull _canBeNull;
Type _type;
uint64_t _size;
};
static void mapping(IO &io, const lld::SharedLibraryAtom *&atom) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormalizedAtom, const lld::SharedLibraryAtom *>
keys(io, atom, &info->_file->allocator());
io.mapRequired("name", keys->_name);
io.mapOptional("load-name", keys->_loadName);
io.mapOptional("can-be-null", keys->_canBeNull, (ShlibCanBeNull) false);
io.mapOptional("type", keys->_type, SharedLibraryAtom::Type::Code);
io.mapOptional("size", keys->_size, uint64_t(0));
}
};
template <> struct MappingTraits<lld::SharedLibraryAtom *> {
static void mapping(IO &io, lld::SharedLibraryAtom *&atom) {
const lld::SharedLibraryAtom *atomPtr = atom;
MappingTraits<const lld::SharedLibraryAtom *>::mapping(io, atomPtr);
atom = const_cast<lld::SharedLibraryAtom *>(atomPtr);
}
};
// YAML conversion for const lld::AbsoluteAtom*
template <> struct MappingTraits<const lld::AbsoluteAtom *> {
class NormalizedAtom : public lld::AbsoluteAtom {
public:
NormalizedAtom(IO &io)
: _file(fileFromContext(io)), _scope(), _value(0) {}
NormalizedAtom(IO &io, const lld::AbsoluteAtom *atom)
: _file(fileFromContext(io)), _name(atom->name()),
_scope(atom->scope()), _value(atom->value()) {}
~NormalizedAtom() override = default;
const lld::AbsoluteAtom *denormalize(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
if (!_name.empty())
_name = f->copyString(_name);
DEBUG_WITH_TYPE("WriterYAML",
llvm::dbgs() << "created AbsoluteAtom named: '" << _name
<< "' (" << (const void *)_name.data()
<< ", " << _name.size() << ")\n");
return this;
}
// Extract current File object from YAML I/O parsing context
const lld::File &fileFromContext(IO &io) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
assert(info->_file != nullptr);
return *info->_file;
}
const lld::File &file() const override { return _file; }
StringRef name() const override { return _name; }
uint64_t value() const override { return _value; }
Scope scope() const override { return _scope; }
const lld::File &_file;
StringRef _name;
StringRef _refName;
Scope _scope;
Hex64 _value;
};
static void mapping(IO &io, const lld::AbsoluteAtom *&atom) {
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
MappingNormalizationHeap<NormalizedAtom, const lld::AbsoluteAtom *> keys(
io, atom, &info->_file->allocator());
if (io.outputting()) {
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
assert(f);
assert(f->_rnb);
if (f->_rnb->hasRefName(atom)) {
keys->_refName = f->_rnb->refName(atom);
}
}
io.mapRequired("name", keys->_name);
io.mapOptional("ref-name", keys->_refName, StringRef());
io.mapOptional("scope", keys->_scope);
io.mapRequired("value", keys->_value);
}
};
template <> struct MappingTraits<lld::AbsoluteAtom *> {
static void mapping(IO &io, lld::AbsoluteAtom *&atom) {
const lld::AbsoluteAtom *atomPtr = atom;
MappingTraits<const lld::AbsoluteAtom *>::mapping(io, atomPtr);
atom = const_cast<lld::AbsoluteAtom *>(atomPtr);
}
};
} // end namespace llvm
} // end namespace yaml
RefNameResolver::RefNameResolver(const lld::File *file, IO &io) : _io(io) {
typedef MappingTraits<const lld::DefinedAtom *>::NormalizedAtom
NormalizedAtom;
for (const lld::DefinedAtom *a : file->defined()) {
const auto *na = (const NormalizedAtom *)a;
if (!na->_refName.empty())
add(na->_refName, a);
else if (!na->_name.empty())
add(na->_name, a);
}
for (const lld::UndefinedAtom *a : file->undefined())
add(a->name(), a);
for (const lld::SharedLibraryAtom *a : file->sharedLibrary())
add(a->name(), a);
typedef MappingTraits<const lld::AbsoluteAtom *>::NormalizedAtom NormAbsAtom;
for (const lld::AbsoluteAtom *a : file->absolute()) {
const auto *na = (const NormAbsAtom *)a;
if (na->_refName.empty())
add(na->_name, a);
else
add(na->_refName, a);
}
}
inline const lld::File *
MappingTraits<const lld::File *>::NormalizedFile::denormalize(IO &io) {
typedef MappingTraits<const lld::DefinedAtom *>::NormalizedAtom
NormalizedAtom;
RefNameResolver nameResolver(this, io);
// Now that all atoms are parsed, references can be bound.
for (const lld::DefinedAtom *a : this->defined()) {
auto *normAtom = (NormalizedAtom *)const_cast<DefinedAtom *>(a);
normAtom->bind(nameResolver);
}
return this;
}
inline void MappingTraits<const lld::DefinedAtom *>::NormalizedAtom::bind(
const RefNameResolver &resolver) {
typedef MappingTraits<const lld::Reference *>::NormalizedReference
NormalizedReference;
for (const lld::Reference *ref : _references) {
auto *normRef = (NormalizedReference *)const_cast<Reference *>(ref);
normRef->bind(resolver);
}
}
inline void MappingTraits<const lld::Reference *>::NormalizedReference::bind(
const RefNameResolver &resolver) {
_target = resolver.lookup(_targetName);
}
inline StringRef
MappingTraits<const lld::Reference *>::NormalizedReference::targetName(
IO &io, const lld::Reference *ref) {
if (ref->target() == nullptr)
return StringRef();
YamlContext *info = reinterpret_cast<YamlContext *>(io.getContext());
assert(info != nullptr);
typedef MappingTraits<const lld::File *>::NormalizedFile NormalizedFile;
NormalizedFile *f = reinterpret_cast<NormalizedFile *>(info->_file);
RefNameBuilder &rnb = *f->_rnb;
if (rnb.hasRefName(ref->target()))
return rnb.refName(ref->target());
return ref->target()->name();
}
namespace lld {
namespace yaml {
class Writer : public lld::Writer {
public:
Writer(const LinkingContext &context) : _ctx(context) {}
llvm::Error writeFile(const lld::File &file, StringRef outPath) override {
// Create stream to path.
std::error_code ec;
llvm::raw_fd_ostream out(outPath, ec, llvm::sys::fs::OF_TextWithCRLF);
if (ec)
return llvm::errorCodeToError(ec);
// Create yaml Output writer, using yaml options for context.
YamlContext yamlContext;
yamlContext._ctx = &_ctx;
yamlContext._registry = &_ctx.registry();
llvm::yaml::Output yout(out, &yamlContext);
// Write yaml output.
const lld::File *fileRef = &file;
yout << fileRef;
return llvm::Error::success();
}
private:
const LinkingContext &_ctx;
};
} // end namespace yaml
namespace {
/// Handles !native tagged yaml documents.
class NativeYamlIOTaggedDocumentHandler : public YamlIOTaggedDocumentHandler {
bool handledDocTag(llvm::yaml::IO &io, const lld::File *&file) const override {
if (io.mapTag("!native")) {
MappingTraits<const lld::File *>::mappingAtoms(io, file);
return true;
}
return false;
}
};
/// Handles !archive tagged yaml documents.
class ArchiveYamlIOTaggedDocumentHandler : public YamlIOTaggedDocumentHandler {
bool handledDocTag(llvm::yaml::IO &io, const lld::File *&file) const override {
if (io.mapTag("!archive")) {
MappingTraits<const lld::File *>::mappingArchive(io, file);
return true;
}
return false;
}
};
class YAMLReader : public Reader {
public:
YAMLReader(const Registry ®istry) : _registry(registry) {}
bool canParse(file_magic magic, MemoryBufferRef mb) const override {
StringRef name = mb.getBufferIdentifier();
return name.endswith(".objtxt") || name.endswith(".yaml");
}
ErrorOr<std::unique_ptr<File>>
loadFile(std::unique_ptr<MemoryBuffer> mb,
const class Registry &) const override {
// Create YAML Input Reader.
YamlContext yamlContext;
yamlContext._registry = &_registry;
yamlContext._path = mb->getBufferIdentifier();
llvm::yaml::Input yin(mb->getBuffer(), &yamlContext);
// Fill vector with File objects created by parsing yaml.
std::vector<const lld::File *> createdFiles;
yin >> createdFiles;
assert(createdFiles.size() == 1);
// Error out now if there were parsing errors.
if (yin.error())
return make_error_code(lld::YamlReaderError::illegal_value);
std::shared_ptr<MemoryBuffer> smb(mb.release());
const File *file = createdFiles[0];
// Note: loadFile() should return vector of *const* File
File *f = const_cast<File *>(file);
f->setLastError(std::error_code());
f->setSharedMemoryBuffer(smb);
return std::unique_ptr<File>(f);
}
private:
const Registry &_registry;
};
} // end anonymous namespace
void Registry::addSupportYamlFiles() {
add(std::unique_ptr<Reader>(new YAMLReader(*this)));
add(std::unique_ptr<YamlIOTaggedDocumentHandler>(
new NativeYamlIOTaggedDocumentHandler()));
add(std::unique_ptr<YamlIOTaggedDocumentHandler>(
new ArchiveYamlIOTaggedDocumentHandler()));
}
std::unique_ptr<Writer> createWriterYAML(const LinkingContext &context) {
return std::unique_ptr<Writer>(new lld::yaml::Writer(context));
}
} // end namespace lld
| 39.397436 | 85 | 0.634469 | mkinsner |
c0ebf25c626bacc9378ff2cebfc441db711850ee | 633 | cpp | C++ | arch/m68k/m68k_isa.cpp | ismaell/libcpu | 3a82a1ab0b99e439e6fbcafca71e9d3d7fe06b12 | [
"BSD-2-Clause"
] | 277 | 2015-01-04T23:33:37.000Z | 2022-03-24T20:38:51.000Z | arch/m68k/m68k_isa.cpp | farmdve/libcpu | d624f5863f49b059726bce83e4da944ed4b4764c | [
"BSD-2-Clause"
] | 7 | 2015-02-18T12:41:18.000Z | 2021-08-21T14:07:53.000Z | arch/m68k/m68k_isa.cpp | farmdve/libcpu | d624f5863f49b059726bce83e4da944ed4b4764c | [
"BSD-2-Clause"
] | 44 | 2015-02-03T09:08:14.000Z | 2022-03-14T16:35:31.000Z | #include "m68k_isa.h"
const char sizechar[] = { '?', 'b', 'l', 'w' };
const char *condstr[] = {
/*[0]*/ "ra",
/*[1]*/ "sr", // 68030?
/*[2]*/ "hi",
/*[3]*/ "ls",
/*[4]*/ "cc",
/*[5]*/ "cs",
/*[6]*/ "ne",
/*[7]*/ "eq",
/*[8]*/ "vc",
/*[9]*/ "vs",
/*[10]*/ "pl",
/*[11]*/ "mi",
/*[12]*/ "ge",
/*[13]*/ "lt",
/*[14]*/ "gt",
/*[15]*/ "le"
};
const char *condstr_db[] = {
/*[0]*/ "t",
/*[1]*/ "f",
/*[2]*/ "hi",
/*[3]*/ "ls",
/*[4]*/ "cc",
/*[5]*/ "cs",
/*[6]*/ "ne",
/*[7]*/ "eq",
/*[8]*/ "vc",
/*[9]*/ "vs",
/*[10]*/ "pl",
/*[11]*/ "mi",
/*[12]*/ "ge",
/*[13]*/ "lt",
/*[14]*/ "gt",
/*[15]*/ "le"
};
| 14.72093 | 47 | 0.28752 | ismaell |
c0ecdbbab19f7b8861f0406f0fed157d4ae24848 | 2,557 | cpp | C++ | ural/1901.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | 5 | 2015-07-14T10:29:25.000Z | 2016-10-11T12:45:18.000Z | ural/1901.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | null | null | null | ural/1901.cpp | jffifa/algo-solution | af2400d6071ee8f777f9473d6a34698ceef08355 | [
"MIT"
] | 3 | 2016-08-23T01:05:26.000Z | 2017-05-28T02:04:20.000Z | #include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
using namespace std;
typedef long long ll;
multiset<int> S;
int n,m;
int a[120000];
int b[120000];
bool bi[120000];
int main(){
while (~scanf("%d%d",&n,&m)){
S.clear();
for (int i=1;i<=n;i++){
scanf("%d",&a[i]);
S.insert(a[i]);
}
if (n==1){
printf("1\n%d\n",a[1]);
continue;
}
if (n==2){
if (a[1]+a[2]>m)
printf("2\n%d %d\n",a[1],a[2]);
else
printf("1\n%d %d\n",a[1],a[2]);
continue;
}
memset(bi,true,sizeof(bi));
sort(a+1,a+n+1);
b[2]=a[n];
multiset<int>::iterator it;
/*
it=S.lower_bound(b[2]);
S.erase(it);
it=S.upper_bound(m-b[2]);
if (it==S.end()) --it;
b[1]=(*it);
S.erase(it);
for (int i=2;i<n;++i){
it=S.upper_bound(m-b[i]);
if (it==S.end()) --it;
b[i+1]=(*it);
S.erase(it);
}
*/
bool flag=true;
for (int i=1;i<=n;i++)
{
if (flag)
{
if (i<n)
{
it=S.end();it--;
b[i+1]=(*it);
S.erase(it);
it=S.upper_bound(m-b[i+1]);
if (it==S.end()) it=S.begin();
b[i]=(*it);
S.erase(it);
i++;
if (b[i-1]+b[i]<=m)
flag=true;
else flag=false;
}
else
{
it=S.begin();
b[i]=(*it);
S.erase(it);
}
}
else
{
it=S.upper_bound(m-b[i-1]);
if (it==S.end())
{
it=S.begin();
flag=true;
}
else flag=false;
b[i]=(*it);
S.erase(it);
}
}
int ans=0;
b[n+1]=0;
for (int i=1;i<=n;++i){
if (b[i]+b[i+1]<=m) i++;
ans++;
}
printf("%d\n",ans);
for (int i=1;i<=n;++i) printf("%d%c",b[i],i==n?'\n':' ');
}
return 0;
}
| 23.036036 | 65 | 0.332421 | jffifa |
c0ee95d13b958a8311145cd416d1753cf104af42 | 12,504 | cpp | C++ | object_detection/haar_detection.cpp | dustsigns/lecture-demos | 50d5abb252e7e467e9648b61310ce93b85c6c5f0 | [
"BSD-3-Clause"
] | 14 | 2018-03-26T13:43:58.000Z | 2022-03-03T13:04:36.000Z | object_detection/haar_detection.cpp | dustsigns/lecture-demos | 50d5abb252e7e467e9648b61310ce93b85c6c5f0 | [
"BSD-3-Clause"
] | null | null | null | object_detection/haar_detection.cpp | dustsigns/lecture-demos | 50d5abb252e7e467e9648b61310ce93b85c6c5f0 | [
"BSD-3-Clause"
] | 1 | 2019-08-03T23:12:08.000Z | 2019-08-03T23:12:08.000Z | //Illustration of Haar features for object detection
// Andreas Unterweger, 2017-2022
//This code is licensed under the 3-Clause BSD License. See LICENSE file for details.
#include <iostream>
#include <limits>
#include <atomic>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "format.hpp"
#include "colors.hpp"
static constexpr unsigned int block_width = 100;
static constexpr unsigned int block_height = 50;
static_assert(block_width % 2 == 0, "Block width must be even");
static_assert(block_height % 2 == 0, "Block height must be even");
struct haar_data
{
const cv::Mat feature_image;
const cv::Mat original_image;
cv::Mat annotated_image;
cv::Rect current_block;
std::atomic_bool running;
const std::string window_name;
void ResetAnnotatedImage()
{
cv::cvtColor(original_image, annotated_image, cv::COLOR_GRAY2BGRA);
}
haar_data(const cv::Mat &feature_image, const cv::Mat &original_image, const std::string &window_name)
: feature_image(feature_image), original_image(original_image),
current_block(cv::Rect(0, 0, block_width, block_height)), running(false),
window_name(window_name)
{
ResetAnnotatedImage();
}
};
static constexpr unsigned int border_size = 1;
static_assert(border_size < (block_width + 1) / 2, "Border size must be smaller than half the block width");
static_assert(border_size < (block_height + 1) / 2, "Border size must be smaller than half the block height");
static constexpr auto detection_threshold = 80000; //Feature-dependent threshold
static_assert(detection_threshold >= 1, "The detection threshold must be positive and non-zero");
static cv::Rect ExtendRect(const cv::Rect &rect, const unsigned int border)
{
return cv::Rect(rect.x - border, rect.y - border, rect.width + 2 * border, rect.height + 2 * border);
}
static void HighlightBlock(cv::Mat &image, const cv::Rect &block, const cv::Scalar &color)
{
const cv::Rect block_with_border = ExtendRect(block, border_size);
rectangle(image, block_with_border, color, border_size);
}
static void OverlayImages(cv::Mat &original_image, const cv::Rect &image_block, const cv::Mat &overlay, const double alpha)
{
assert(overlay.type() == CV_8UC1);
cv::Mat image_region = original_image(image_block);
cv::Mat converted_overlay;
cv::cvtColor(overlay, converted_overlay, cv::COLOR_GRAY2BGRA);
image_region = image_region * (1 - alpha) + converted_overlay * alpha;
}
static cv::Mat GetAnnotatedImage(haar_data &data, bool persist_changes)
{
constexpr auto overlay_alpha = 0.33;
if (persist_changes)
HighlightBlock(data.annotated_image, data.current_block, imgutils::Green); //Draw detected faces in green and persist changes
cv::Mat temporary_annotated_image = data.annotated_image.clone();
if (!persist_changes)
HighlightBlock(temporary_annotated_image, data.current_block, imgutils::Red); //Draw non-faces in red temporarily
OverlayImages(temporary_annotated_image, data.current_block, data.feature_image, overlay_alpha);
return temporary_annotated_image;
}
static double GetFeatureValue(const cv::Mat &block, const cv::Mat &feature)
{
assert(block.size() == feature.size());
assert(feature.type() == CV_8UC1);
assert(feature.type() == block.type());
cv::Mat block_signed;
block.convertTo(block_signed, CV_16SC1);
cv::Mat feature_signed;
feature.convertTo(feature_signed, CV_16SC1, 1.0 / 127, -1); //Convert [0, 255] range to [0 / 127 - 1, 255 / 127 - 1] = [-1, 1]
const cv::Mat weighted_pixels = block_signed.mul(feature_signed); //Multiply black pixels by (-1) and white pixels by 1
const auto difference = sum(weighted_pixels); //Value is difference between weighted pixels
const auto difference_1d = difference[0];
return difference_1d;
}
static double UpdateImage(haar_data &data, const bool update_GUI = true)
{
const cv::Mat block_pixels = data.original_image(data.current_block);
const double feature_value = GetFeatureValue(block_pixels, data.feature_image);
if (update_GUI)
{
const auto permanent_annotation = feature_value > detection_threshold;
const cv::Mat annotated_image = GetAnnotatedImage(data, permanent_annotation);
const std::string status_text = "Pixel difference (feature value): " + comutils::FormatValue(feature_value, 0);
cv::displayStatusBar(data.window_name, status_text);
cv::imshow(data.window_name, annotated_image);
}
return feature_value;
}
static double SetCurrentPosition(haar_data &data, const cv::Point &top_left, const bool update_GUI = true)
{
data.current_block = cv::Rect(top_left, cv::Size(block_width, block_height));
return UpdateImage(data, update_GUI);
}
static cv::Mat_<double> PerformSearch(haar_data &data, const bool update_GUI = true)
{
constexpr auto search_step_delay = 1; //Animation delay in ms
cv::Mat_<double> score_map(data.original_image.size(), std::numeric_limits<double>::infinity());
for (int y = border_size; y <= data.original_image.cols - static_cast<int>(block_height + border_size); y++)
{
for (int x = border_size; x <= data.original_image.rows - static_cast<int>(block_width + border_size); x++)
{
if (update_GUI && !data.running) //Skip the rest when the user aborts
return score_map;
const cv::Point current_position(x, y);
const double current_score = SetCurrentPosition(data, current_position, update_GUI);
score_map(current_position - cv::Point(border_size, border_size)) = current_score;
if (update_GUI)
cv::waitKey(search_step_delay);
}
}
return score_map;
}
static void ResetImage(haar_data &data)
{
SetCurrentPosition(data, cv::Point(border_size, border_size)); //Set current position to (0, 0) plus border
}
static void SelectPointInImage(const int event, const int x, const int y, const int, void * const userdata)
{
auto &data = *(static_cast<haar_data*>(userdata));
if (!data.running && event == cv::EVENT_LBUTTONUP) //Only react when the left mouse button is being pressed while no motion estimation is running
{
const cv::Point mouse_point(x + border_size, y + border_size); //Assume mouse position is in the top-left of the search block (on the outside border which is border_size pixels in width)
if (mouse_point.x <= data.original_image.cols - static_cast<int>(block_width + border_size) &&
mouse_point.y <= data.original_image.rows - static_cast<int>(block_height + border_size)) //If the mouse is within the image area (minus the positions on the bottom which would lead to the block exceeding the borders)...
SetCurrentPosition(data, mouse_point); //... set the current position according to the mouse position
}
}
static cv::Mat MakeColorMap(const cv::Mat_<double> &diff_map)
{
cv::Mat color_map(diff_map.size(), CV_8UC3);
std::transform(diff_map.begin(), diff_map.end(), color_map.begin<cv::Vec3b>(),
[](const double value) -> cv::Vec3b
{
if (std::isinf(value))
return 0.5 * imgutils::White; //The border is gray
else if (value < detection_threshold) //Values below the threshold are more red the further away they are from the threshold
return ((detection_threshold - value) / (2 * detection_threshold)) * imgutils::Red; //0 is half-way, -threshold and below are full red
else if (value >= detection_threshold) //Values above the threshold are always 25% green and more green the further away they are from the threshold
return 0.25 * imgutils::Green + 0.75 * ((value - detection_threshold) / detection_threshold) * imgutils::Green;
else
return imgutils::Black;
});
return color_map;
}
static void ShowImage(const cv::Mat &feature_image, const cv::Mat &image)
{
constexpr auto window_name = "Image with objects to detect";
cv::namedWindow(window_name);
cv::moveWindow(window_name, 0, 0);
static haar_data data(feature_image, image, window_name); //Make variable global so that it is not destroyed after the function returns (for the variable is needed later)
cv::setMouseCallback(window_name, SelectPointInImage, static_cast<void*>(&data));
constexpr auto clear_button_name = "Clear detections";
cv::createButton(clear_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
data.ResetAnnotatedImage();
ResetImage(data); //Force redraw
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
constexpr auto perform_button_name = "Search whole image";
cv::createButton(perform_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
if (!data.running)
{
data.running = true;
PerformSearch(data);
data.running = false;
}
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
constexpr auto stop_button_name = "Stop search";
cv::createButton(stop_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
data.running = false;
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
constexpr auto map_button_name = "Show map of differences";
cv::createButton(map_button_name, [](const int, void * const user_data)
{
auto &data = *(static_cast<haar_data*>(user_data));
if (data.running) //Abort when the search is already running
return;
auto diff_map = PerformSearch(data, false);
const auto color_map = MakeColorMap(diff_map);
constexpr auto map_window_name = "Difference map";
cv::namedWindow(map_window_name);
cv::moveWindow(map_window_name, data.original_image.cols + 3, 0); //Move difference window right of the main window (image size plus 3 border pixels)
cv::imshow(map_window_name, color_map);
cv::setMouseCallback(map_window_name, SelectPointInImage, static_cast<void*>(&data)); //Perform the same action as in the main window
}, static_cast<void*>(&data), cv::QT_PUSH_BUTTON);
ResetImage(data); //Implies cv::imshow with default position
}
static cv::Mat GetFeatureImage()
{
cv::Mat feature_image(block_height, block_width, CV_8UC1, cv::Scalar(0));
auto lower_half = feature_image(cv::Rect(0, block_height / 2, block_width, block_height / 2));
lower_half = cv::Scalar(255);
return feature_image;
}
int main(const int argc, const char * const argv[])
{
if (argc != 2)
{
std::cout << "Illustrates object detection with Haar features." << std::endl;
std::cout << "Usage: " << argv[0] << " <input image>" << std::endl;
return 1;
}
const auto image_filename = argv[1];
const cv::Mat image = cv::imread(image_filename, cv::IMREAD_GRAYSCALE);
if (image.empty())
{
std::cerr << "Could not read input image '" << image_filename << "'" << std::endl;
return 2;
}
const cv::Mat feature_image = GetFeatureImage();
if (image.rows < feature_image.rows + static_cast<int>(2 * border_size) && image.cols < feature_image.cols + static_cast<int>(2 * border_size))
{
std::cerr << "The input image must be larger than " << (feature_image.rows + 2 * border_size) << "x" << (feature_image.cols + 2 * border_size) << " pixels" << std::endl;
return 3;
}
ShowImage(feature_image, image);
cv::waitKey(0);
return 0;
}
| 48.465116 | 228 | 0.646673 | dustsigns |
c0ef885aa2104d510a2717b2c41affc74db88100 | 734 | cpp | C++ | Example/Source/Main.cpp | eugen-bondarev/AssetSupplier | 90e3d3e5fd7890c945dfc1975e7767d87221e53f | [
"MIT"
] | null | null | null | Example/Source/Main.cpp | eugen-bondarev/AssetSupplier | 90e3d3e5fd7890c945dfc1975e7767d87221e53f | [
"MIT"
] | null | null | null | Example/Source/Main.cpp | eugen-bondarev/AssetSupplier | 90e3d3e5fd7890c945dfc1975e7767d87221e53f | [
"MIT"
] | null | null | null | #include <SRM/SRM.h>
#ifndef EXAMPLE_ROOT_DIR
# define EXAMPLE_ROOT_DIR
#endif
int main(const int argc, const char* argv[])
{
const srm::String root{ EXAMPLE_ROOT_DIR "/Assets" };
srm::ResourceManager resourceManager{
root,
"table.asu",
"data.asu",
srm::ResourceManager::Mode::Create
};
srm::Resource resource;
try
{
//resource = resourceManager.Load("a/b/c/d/e/deep-file.deep");
resource = resourceManager.Load("a/new-file.file");
}
catch (const srm::Exception& exception)
{
SRM_CONSOLE_OUT("[Error] %s", exception.what());
}
if (resource)
{
srm::String str{ "" };
for (size_t i = 0; i < resource.data.size(); ++i)
{
str += resource.data[i];
}
SRM_CONSOLE_INFO(str);
}
return 0;
} | 17.902439 | 64 | 0.651226 | eugen-bondarev |
c0f21a781ccc0dd88313ea39ebb33c5485bd0b6b | 427 | cpp | C++ | legend/legend/App.cpp | Sathorael/legendary-computing-machine | 34273b6e50edb9211f11488d247df74aef56448a | [
"MIT"
] | null | null | null | legend/legend/App.cpp | Sathorael/legendary-computing-machine | 34273b6e50edb9211f11488d247df74aef56448a | [
"MIT"
] | null | null | null | legend/legend/App.cpp | Sathorael/legendary-computing-machine | 34273b6e50edb9211f11488d247df74aef56448a | [
"MIT"
] | 1 | 2019-05-28T18:32:30.000Z | 2019-05-28T18:32:30.000Z | #include "App.h"
#include "SDL\SDL.h"
#include "Window.h"
App::App()
{
}
App::~App()
{
}
void App::run()
{
bool running = true;
SDL_Event e;
Window* window = new Window();
window->init();
while (running)
{
// Handle events in queue
while (SDL_PollEvent(&e) != 0)
{
// Quit if the user requests it.
if (e.type == SDL_QUIT)
{
running = false;
}
}
}
window->destroy();
SDL_Quit();
} | 10.414634 | 36 | 0.559719 | Sathorael |
c0f21db838e35070a41786bf0221e8599672e95f | 3,836 | cc | C++ | src/server/server_unix_socket.cc | kofuk/pixel-terrain | f39e2a0120aab5a11311f57cfd1ab46efa65fddd | [
"MIT"
] | 2 | 2020-10-16T08:46:45.000Z | 2020-11-04T02:19:19.000Z | src/server/server_unix_socket.cc | kofuk/minecraft-image-generator | ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7 | [
"MIT"
] | null | null | null | src/server/server_unix_socket.cc | kofuk/minecraft-image-generator | ef2f7deb2daac7f7c2cfb468ef39e0cdc8b33db7 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: MIT
#include <csignal>
#include <cstring>
#include <iostream>
#include <mutex>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include "server/reader.hh"
#include "server/reader_unix.hh"
#include "server/request.hh"
#include "server/server.hh"
#include "server/server_unix_socket.hh"
#include "server/writer.hh"
#include "server/writer_unix.hh"
#include "utils/threaded_worker.hh"
namespace pixel_terrain::server {
namespace {
threaded_worker<int> *worker;
std::mutex worker_mutex;
void terminate_server() {
::unlink("/tmp/mcmap.sock");
std::exit(0);
}
void handle_signals(sigset_t sigs) {
int sig;
for (;;) {
if (::sigwait(&sigs, &sig) != 0) {
std::exit(1);
}
std::unique_lock<std::mutex> lock(worker_mutex);
if (sig == SIGUSR1) {
if (worker != nullptr) {
worker->finish();
delete worker;
}
terminate_server();
}
}
}
void prepare_signel_handle_thread() {
::sigset_t sigs;
::sigemptyset(&sigs);
::sigaddset(&sigs, SIGPIPE);
::sigaddset(&sigs, SIGUSR1);
::sigaddset(&sigs, SIGINT);
::pthread_sigmask(SIG_BLOCK, &sigs, nullptr);
std::thread t(&handle_signals, sigs);
t.detach();
}
void handle_request_unix(int const fd) {
reader *r = new reader_unix(fd);
auto *req = new request(r);
writer *w = new writer_unix(fd);
handle_request(req, w);
delete w;
delete req;
delete r;
::close(fd);
}
} // namespace
server_unix_socket::server_unix_socket(bool const daemon)
: daemon_mode(daemon) {}
void server_unix_socket::start_server() {
if (daemon_mode) {
if (::daemon(0, 0) == -1) {
std::cerr << "cannot run in daemon mode\n";
std::exit(1);
}
}
prepare_signel_handle_thread();
worker = new threaded_worker<int>(std::thread::hardware_concurrency(),
&handle_request_unix);
worker->start();
int ssock;
::sockaddr_un sa;
std::memset(&sa, 0, sizeof(sa));
::sockaddr_un sa_peer;
std::memset(&sa_peer, 0, sizeof(sa));
::socklen_t addr_len = sizeof(sockaddr_un);
if ((ssock = ::socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
std::perror("server");
std::exit(1);
}
sa.sun_family = AF_UNIX;
std::strcpy(sa.sun_path, "/tmp/mcmap.sock");
if (::bind(ssock, reinterpret_cast<::sockaddr *>(&sa),
sizeof(::sockaddr_un)) == -1) {
goto fail;
}
if (::listen(ssock, 4) == -1) {
goto fail;
}
if (::chmod("/tmp/mcmap.sock", S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH) == -1) {
goto fail;
}
for (;;) {
int fd;
if ((fd = ::accept(ssock, reinterpret_cast<::sockaddr *>(&sa_peer),
&addr_len)) > 0) {
std::unique_lock<std::mutex> lock(worker_mutex);
worker->queue_job(fd);
}
}
fail:
std::perror("server");
::close(ssock);
if (worker != nullptr) {
worker->finish();
}
}
} // namespace pixel_terrain::server
| 26.638889 | 79 | 0.486184 | kofuk |
c0f36aa26b85ca89df0346767a10e37e7b318251 | 10,974 | cpp | C++ | Source/SOrb/UI/Menu/Settings/KeySelector/SoUIInputKeySelectorOverlay.cpp | LaudateCorpus1/WarriOrb | 7c20320484957e1a7fe0c09ab520967849ba65f1 | [
"MIT"
] | 200 | 2021-03-17T11:15:05.000Z | 2022-03-31T23:45:09.000Z | Source/SOrb/UI/Menu/Settings/KeySelector/SoUIInputKeySelectorOverlay.cpp | LaudateCorpus1/WarriOrb | 7c20320484957e1a7fe0c09ab520967849ba65f1 | [
"MIT"
] | null | null | null | Source/SOrb/UI/Menu/Settings/KeySelector/SoUIInputKeySelectorOverlay.cpp | LaudateCorpus1/WarriOrb | 7c20320484957e1a7fe0c09ab520967849ba65f1 | [
"MIT"
] | 38 | 2021-03-17T13:29:18.000Z | 2022-03-04T19:32:52.000Z | // Copyright (c) Csaba Molnar & Daniel Butum. All Rights Reserved.
#include "SoUIInputKeySelectorOverlay.h"
#include "Components/TextBlock.h"
#include "Framework/Application/SlateApplication.h"
#include "SoUIInputKeySelector.h"
#include "UI/General/Buttons/SoUIButtonImageArray.h"
#include "Components/Image.h"
#include "UI/SoUIHelper.h"
#include "Settings/Input/SoInputHelper.h"
#include "Basic/SoGameSingleton.h"
#include "Basic/SoAudioManager.h"
#include "Localization/SoLocalization.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::SynchronizeProperties()
{
Super::SynchronizeProperties();
if (KeySelector)
{
KeySelector->SetAllowModifierKeysInSelection(bAllowModifierKeysInSelection);
KeySelector->SetEscapeKeys(EscapeKeys);
KeySelector->SetAllowedInputType(AllowedInputType);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::NativeConstruct()
{
Super::NativeConstruct();
SetVisibility(ESlateVisibility::Collapsed);
KeySelectorImageRepresentation->SetVisibility(ESlateVisibility::Collapsed);
ErrorMessage->SetVisibility(ESlateVisibility::Collapsed);
if (KeySelector)
{
KeySelector->OnKeySelectedEvent().AddDynamic(this, &ThisClass::HandleKeySelected);
KeySelector->OnIsSelectingKeyChangedEvent().AddDynamic(this, &ThisClass::HandleIsSelectingKeyChanged);
}
if (ButtonImagesTooltipsArray)
{
ButtonImagesTooltipsArray->OnNavigateOnPressedHandleChildEvent().BindLambda([this](int32 SelectedChild, USoUIUserWidget* SoUserWidget)
{
const ESoUICommand PressedCommand = ButtonImagesTooltipsArray->GetButtonIndexCommand(SelectedChild);
OnPressedButtonTooltipsCommand(PressedCommand);
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::NativeDestruct()
{
if (KeySelector)
{
KeySelector->OnKeySelectedEvent().RemoveDynamic(this, &ThisClass::HandleKeySelected);
KeySelector->OnIsSelectingKeyChangedEvent().RemoveDynamic(this, &ThisClass::HandleIsSelectingKeyChanged);
}
Super::NativeDestruct();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::OnUICommand_Implementation(ESoUICommand Command)
{
if (!CanHandleUICommand())
return false;
switch (Command)
{
case ESoUICommand::EUC_Left:
case ESoUICommand::EUC_Right:
return ButtonImagesTooltipsArray->Navigate(Command);
case ESoUICommand::EUC_MainMenuEnter:
{
const ESoUICommand PressedCommand = ButtonImagesTooltipsArray->GetSelectedButtonCommand();
return OnPressedButtonTooltipsCommand(PressedCommand);
}
default:
return OnPressedButtonTooltipsCommand(Command);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::OnPressedButtonTooltipsCommand(ESoUICommand Command)
{
if (!CanHandleUICommand())
return false;
switch (Command)
{
case UICommand_SelectAnother:
return OnCommandSelectAnotherKey();
case UICommand_Apply:
return OnCommandApply();
case UICommand_Cancel:
return OnCommandCancel();
default:
break;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::OnCommandSelectAnotherKey()
{
if (!CanHandleUICommand())
return false;
// Choose another key
SetIsSelectingKey(true);
CurrentlySelectedButtonText->SetVisibility(ESlateVisibility::Visible);
KeySelector->SetTextBlockVisibility(ESlateVisibility::Visible);
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::OnCommandApply()
{
if (!CanHandleUICommand())
return false;
if (!IsSelectedKeyValid())
return false;
// Close overlay
Close();
USoAudioManager::PlaySound2D(this, USoGameSingleton::GetSFX(ESoSFX::SettingsApply));
ApplySelectedKeyEvent.Broadcast(KeySelector->GetSelectedKey());
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::OnCommandCancel()
{
if (IsSelectingKey())
return false;
// Close overlay
Close();
USoAudioManager::PlaySound2D(this, USoGameSingleton::GetSFX(ESoSFX::SettingsRestore));
CancelSelectedKeyEvent.Broadcast();
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::Open_Implementation(bool bOpen)
{
bOpened = bOpen;
ErrorMessage->SetVisibility(ESlateVisibility::Collapsed);
WarningMessage->SetVisibility(ESlateVisibility::Collapsed);
SetVisibility(bOpen ? ESlateVisibility::Visible : ESlateVisibility::Collapsed);
if (bOpen)
{
const ESoInputDeviceType DeviceType = USoInputHelper::GetCurrentGamepadDeviceTypeFromSettings(this);
GamepadDeviceType = (DeviceType == ESoInputDeviceType::Gamepad_PlayStation || DeviceType == ESoInputDeviceType::Gamepad_Switch) ?
DeviceType : ESoInputDeviceType::Gamepad_Xbox;
}
else
{
SetIsSelectingKey(false);
}
OpenChangedEvent.Broadcast(bOpened);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::HandleIsSelectingKeyChanged(bool bIsSelectingKey)
{
// We are trying another key, hide this message
if (bIsSelectingKey)
{
ErrorMessage->SetVisibility(ESlateVisibility::Collapsed);
WarningMessage->SetVisibility(ESlateVisibility::Collapsed);
}
else
{
ButtonImagesTooltipsArray->Highlight();
// Maybe some inputs are still pressed, clear so that we don't go into issues
//if (ASoCharacter* Character = USoStaticHelper::GetPlayerCharacterAsSoCharacter(this))
// Character->ClearInputStates();
}
UpdateKeySelectorImage();
RefreshButtonImagesTooltips();
IsSelectingKeyChangedEvent.Broadcast(bIsSelectingKey);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::HandleKeySelected(const FInputChord& InSelectedKey)
{
CurrentlySelectedButtonText->SetVisibility(ESlateVisibility::Visible);
KeySelector->SetTextBlockVisibility(ESlateVisibility::Visible);
// Display error message
FText Error, Warning;
if (IsSelectedKeyValid(Error, Warning))
{
ErrorMessage->SetVisibility(ESlateVisibility::Collapsed);
WarningMessage->SetVisibility(ESlateVisibility::Collapsed);
}
if (!Error.IsEmpty())
{
// Hide any warnings
ErrorMessage->SetText(Error);
ErrorMessage->SetVisibility(ESlateVisibility::Visible);
WarningMessage->SetVisibility(ESlateVisibility::Collapsed);
CurrentlySelectedButtonText->SetVisibility(ESlateVisibility::Collapsed);
KeySelector->SetTextBlockVisibility(ESlateVisibility::Hidden);
}
else if (!Warning.IsEmpty())
{
WarningMessage->SetVisibility(ESlateVisibility::Visible);
WarningMessage->SetText(Warning);
}
UpdateKeySelectorImage();
RefreshButtonImagesTooltips();
KeySelectedEvent.Broadcast(InSelectedKey);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::IsSelectingKey() const
{
return KeySelector ? KeySelector->IsSelectingKey() : false;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FKey USoUIInputKeySelectorOverlay::GetSelectedKey() const
{
return KeySelector ? KeySelector->GetSelectedKey().Key : FKey();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::SetActionName(const FText& ActionNameText)
{
if (ActionName)
ActionName->SetText(ActionNameText);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::SetIsSelectingKey(bool bInIsSelectingKey)
{
UE_LOG(LogSoInputSelector, Verbose, TEXT("\n\n\nUSoUIInputKeySelectorOverlay::SetIsSelectingKey = %d"), bInIsSelectingKey);
if (KeySelector)
{
// Focus back to us
if (bInIsSelectingKey)
KeySelector->SetPreviousFocusedWidget(FSlateApplication::Get().GetUserFocusedWidget(0));
KeySelector->SetIsSelectingKey(bInIsSelectingKey);
UpdateKeySelectorImage();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::RefreshButtonImagesTooltips()
{
TArray<FSoUITextCommandPair> CommandsToBeDisplayed;
if (!IsSelectingKey())
{
if (IsSelectedKeyValid())
CommandsToBeDisplayed.Add({ UICommand_Apply, FROM_STRING_TABLE_UI("settings_apply") });
CommandsToBeDisplayed.Add({ UICommand_SelectAnother, FROM_STRING_TABLE_UI("settings_select_another") });
CommandsToBeDisplayed.Add({ UICommand_Cancel, FROM_STRING_TABLE_UI("settings_cancel") });
}
ButtonImagesTooltipsArray->UpdateEnsureOnlyTheseCommandsExist(CommandsToBeDisplayed, true);
if (!IsSelectingKey())
ButtonImagesTooltipsArray->SelectFirstValidChild();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool USoUIInputKeySelectorOverlay::IsSelectedKeyValid(FText& OutError, FText& OutWarning, bool bNoOutput) const
{
if (!KeySelector || !IsSelectedKeyValidEvent.IsBound())
return false;
const FInputChord SelectedKey = KeySelector->GetSelectedKey();
return IsSelectedKeyValidEvent.Execute(SelectedKey, OutError, OutWarning, bNoOutput);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void USoUIInputKeySelectorOverlay::UpdateKeySelectorImage()
{
if (!KeySelectorImageRepresentation)
return;
KeySelectorImageRepresentation->SetVisibility(ESlateVisibility::Collapsed);
if (!IsSelectingKey() && IsSelectedKeyValid())
{
const FKey SelectedKey = GetSelectedKey();
switch (KeySelectorImageVisibility)
{
case ESoInputOverlayKeyImageVisibility::All:
// TODO
break;
case ESoInputOverlayKeyImageVisibility::Gamepad:
if (USoInputHelper::IsGamepadKey(SelectedKey))
{
KeySelectorImageRepresentation->SetVisibility(ESlateVisibility::Visible);
KeySelectorImageRepresentation->SetBrushFromTexture(USoGameSingleton::GetIconForInputKey(SelectedKey, GamepadDeviceType, false));
}
break;
case ESoInputOverlayKeyImageVisibility::Keyboard:
// TODO
break;
default:
break;
}
}
}
| 32.856287 | 136 | 0.637507 | LaudateCorpus1 |
c0f39990b5ed10069645da82b03d19168aff19e0 | 5,597 | cc | C++ | src/tests/test_beadstructure_algorithms.cc | BuildJet/csg | c02f06ff316eef38564c8e0160bcaf4a6c7f160d | [
"Apache-2.0"
] | null | null | null | src/tests/test_beadstructure_algorithms.cc | BuildJet/csg | c02f06ff316eef38564c8e0160bcaf4a6c7f160d | [
"Apache-2.0"
] | null | null | null | src/tests/test_beadstructure_algorithms.cc | BuildJet/csg | c02f06ff316eef38564c8e0160bcaf4a6c7f160d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2021 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE beadstructurealgorithms_test
// Third party includes
#include <boost/test/unit_test.hpp>
// Local VOTCA includes
#include "votca/csg/basebead.h"
#include "votca/csg/beadstructure.h"
#include "votca/csg/beadstructurealgorithms.h" // IWYU pragma: keep
using namespace std;
using namespace votca::csg;
class TestBead : public BaseBead {
public:
TestBead() : BaseBead(){};
};
BOOST_AUTO_TEST_SUITE(beadstructurealgorithms_test)
BOOST_AUTO_TEST_CASE(test_beadstructure_breakIntoStructures) {
// Beads for bead structure 1
// Make a methane molecule
//
// H
// |
// H - C - H
// |
// H
//
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Make a Water molecule
//
// H - O - H
//
TestBead testbead6;
testbead6.setName("Hydrogen");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Oxygen");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Hydrogen");
testbead8.setId(8);
// Adding a Helium
//
// He
//
TestBead testbead12;
testbead12.setName("Helium");
testbead12.setId(12);
// Methane
BeadStructure beadstructure_methane;
beadstructure_methane.AddBead(testbead1);
beadstructure_methane.AddBead(testbead2);
beadstructure_methane.AddBead(testbead3);
beadstructure_methane.AddBead(testbead4);
beadstructure_methane.AddBead(testbead5);
// Water
BeadStructure beadstructure_water;
beadstructure_water.AddBead(testbead6);
beadstructure_water.AddBead(testbead7);
beadstructure_water.AddBead(testbead8);
// Helium
BeadStructure beadstructure_helium;
beadstructure_helium.AddBead(testbead12);
// Methane and Water and Helium
BeadStructure beadstructure;
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
beadstructure.AddBead(testbead3);
beadstructure.AddBead(testbead4);
beadstructure.AddBead(testbead5);
beadstructure.AddBead(testbead6);
beadstructure.AddBead(testbead7);
beadstructure.AddBead(testbead8);
// Connect beads
// Methane
beadstructure_methane.ConnectBeads(1, 2);
beadstructure_methane.ConnectBeads(3, 2);
beadstructure_methane.ConnectBeads(4, 2);
beadstructure_methane.ConnectBeads(5, 2);
// Water
beadstructure_water.ConnectBeads(6, 7);
beadstructure_water.ConnectBeads(7, 8);
// Methane and Water
beadstructure.ConnectBeads(1, 2);
beadstructure.ConnectBeads(3, 2);
beadstructure.ConnectBeads(4, 2);
beadstructure.ConnectBeads(5, 2);
beadstructure.ConnectBeads(6, 7);
beadstructure.ConnectBeads(7, 8);
cout << "Calling break into structures " << endl;
vector<BeadStructure> structures = breakIntoStructures(beadstructure);
BOOST_CHECK_EQUAL(structures.size(), 2);
cout << "Bead Count 1 " << structures.at(0).BeadCount() << endl;
cout << "Bead Count 2 " << structures.at(1).BeadCount() << endl;
bool methane_found = false;
bool water_found = false;
for (auto structure : structures) {
if (structure.isStructureEquivalent(beadstructure_methane)) {
methane_found = true;
}
if (structure.isStructureEquivalent(beadstructure_water)) {
water_found = true;
}
}
BOOST_CHECK(methane_found);
BOOST_CHECK(water_found);
// Adding another water
//
// H - O - H
//
TestBead testbead9;
testbead9.setName("Hydrogen");
testbead9.setId(9);
TestBead testbead11;
testbead11.setName("Hydrogen");
testbead11.setId(11);
TestBead testbead10;
testbead10.setName("Oxygen");
testbead10.setId(10);
// Adding the water
beadstructure.AddBead(testbead9);
beadstructure.AddBead(testbead10);
beadstructure.AddBead(testbead11);
beadstructure.ConnectBeads(9, 10);
beadstructure.ConnectBeads(11, 10);
// Adding a Helium
TestBead testbead13;
testbead13.setName("Helium");
testbead13.setId(13);
beadstructure.AddBead(testbead13);
structures = breakIntoStructures(beadstructure);
BOOST_CHECK_EQUAL(structures.size(), 4);
methane_found = false;
water_found = false;
bool structure3_found = false;
votca::Index structure2_count = 0;
for (auto structure : structures) {
if (structure.isStructureEquivalent(beadstructure_methane)) {
methane_found = true;
}
if (structure.isStructureEquivalent(beadstructure_water)) {
water_found = true;
++structure2_count;
}
if (structure.isStructureEquivalent(beadstructure_helium)) {
structure3_found = true;
}
}
BOOST_CHECK(methane_found);
BOOST_CHECK(water_found);
BOOST_CHECK(structure3_found);
BOOST_CHECK_EQUAL(structure2_count, 2);
}
BOOST_AUTO_TEST_SUITE_END()
| 25.211712 | 75 | 0.729141 | BuildJet |
c0f4d5e77c83ae6a7e9d85781c216756d877646c | 4,789 | cpp | C++ | src/rtplugins/SuperSampleAdaptiveRenderer.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | 1 | 2021-11-06T06:13:05.000Z | 2021-11-06T06:13:05.000Z | src/rtplugins/SuperSampleAdaptiveRenderer.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | null | null | null | src/rtplugins/SuperSampleAdaptiveRenderer.cpp | potato3d/rtrt2 | 5c135c1aea0ded2898e16220cec5ed2860dcc9b3 | [
"MIT"
] | null | null | null | #include <rtp/SuperSampleAdaptiveRenderer.h>
#include <rt/Context.h>
#include <rti/ICamera.h>
#include <vr/random.h>
#include <omp.h>
using namespace rtp;
SuperSampleAdaptiveRenderer::SuperSampleAdaptiveRenderer()
{
vr::Random::autoSeed();
_epsilon = 0.01f;
_maxRecursionDepth = 3;
}
void SuperSampleAdaptiveRenderer::render()
{
uint32 width;
uint32 height;
rt::Context* ctx = rt::Context::get();
ctx->getCamera()->getViewport( width, height );
float* frameBuffer = ctx->getFrameBuffer();
int32 w = (int32)width;
int32 h = (int32)height;
vr::vec3f resultColor;
int32 x, y;
int32 chunk = 16;
#pragma omp parallel for shared( frameBuffer, h, w ) private( y ) schedule( dynamic, chunk )
for( y = 0; y < h; ++y )
{
#pragma omp parallel for shared( frameBuffer, h, w, y ) private( x, resultColor ) schedule( dynamic, chunk )
for( x = 0; x < w; ++x )
{
adaptiveSupersample( x, y, resultColor, 1 );
frameBuffer[(x+y*w)*3] = resultColor.r;
frameBuffer[(x+y*w)*3+1] = resultColor.g;
frameBuffer[(x+y*w)*3+2] = resultColor.b;
}
}
}
void SuperSampleAdaptiveRenderer::adaptiveSupersample( float x, float y, vr::vec3f& resultColor, uint32 recursionDepth )
{
rt::Context* ctx = rt::Context::get();
const float deltaRatio = 0.5f / (float)recursionDepth;
float deltaX;
float deltaY;
rt::Sample upperLeftSample;
rt::Sample upperRightSample;
rt::Sample lowerLeftSample;
rt::Sample lowerRightSample;
// Upper left (A)
deltaX = vr::Random::real( -deltaRatio, 0.0f );
deltaY = vr::Random::real( 0.0f, deltaRatio );
upperLeftSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( upperLeftSample );
vr::vec3f upperLeftColor = upperLeftSample.color;
// Upper right (B)
deltaX = vr::Random::real( 0.0f, deltaRatio );
deltaY = vr::Random::real( 0.0f, deltaRatio );
upperRightSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( upperRightSample );
vr::vec3f upperRightColor = upperRightSample.color;
// Lower left (C)
deltaX = vr::Random::real( -deltaRatio, 0.0f );
deltaY = vr::Random::real( -deltaRatio, 0.0f );
lowerLeftSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( lowerLeftSample );
vr::vec3f lowerLeftColor = lowerLeftSample.color;
// Lower right (D)
deltaX = vr::Random::real( 0.0f, deltaRatio );
deltaY = vr::Random::real( -deltaRatio, 0.0f );
lowerRightSample.initPrimaryRay( x + deltaX, y + deltaY );
ctx->traceNearest( lowerRightSample );
vr::vec3f lowerRightColor = lowerRightSample.color;
if( recursionDepth < _maxRecursionDepth )
{
// If too much difference in sample values
vr::vec3f ab = upperLeftColor - upperRightColor;
ab.set( vr::abs( ab.r ), vr::abs( ab.g ), vr::abs( ab.b ) );
vr::vec3f ac = upperLeftColor - lowerLeftColor;
ac.set( vr::abs( ac.r ), vr::abs( ac.g ), vr::abs( ac.b ) );
vr::vec3f ad = upperLeftColor - lowerRightColor;
ad.set( vr::abs( ad.r ), vr::abs( ad.g ), vr::abs( ad.b ) );
vr::vec3f bc = upperRightColor - lowerLeftColor;
bc.set( vr::abs( bc.r ), vr::abs( bc.g ), vr::abs( bc.b ) );
vr::vec3f bd = upperRightColor - lowerRightColor;
bd.set( vr::abs( bd.r ), vr::abs( bd.g ), vr::abs( bd.b ) );
vr::vec3f cd = upperLeftColor - lowerRightColor;
cd.set( vr::abs( cd.r ), vr::abs( cd.g ), vr::abs( cd.b ) );
if( ( ab.r > _epsilon ) || ( ab.g > _epsilon ) || ( ab.b > _epsilon ) ||
( ac.r > _epsilon ) || ( ac.g > _epsilon ) || ( ac.b > _epsilon ) ||
( ad.r > _epsilon ) || ( ad.g > _epsilon ) || ( ad.b > _epsilon ) ||
( bc.r > _epsilon ) || ( bc.g > _epsilon ) || ( bc.b > _epsilon ) ||
( bd.r > _epsilon ) || ( bd.g > _epsilon ) || ( bd.b > _epsilon ) ||
( cd.r > _epsilon ) || ( cd.g > _epsilon ) || ( cd.b > _epsilon ) )
{
// Recursive supersample
const float recDelta = 0.5f / ( (float)recursionDepth + 1.0f );
vr::vec3f recUpperLeft;
vr::vec3f recUpperRight;
vr::vec3f recLowerLeft;
vr::vec3f recLowerRight;
adaptiveSupersample( x - recDelta, y + recDelta, recUpperLeft, recursionDepth + 1 );
adaptiveSupersample( x + recDelta, y + recDelta, recUpperRight, recursionDepth + 1 );
adaptiveSupersample( x - recDelta, y - recDelta, recLowerLeft, recursionDepth + 1 );
adaptiveSupersample( x + recDelta, y - recDelta, recLowerRight, recursionDepth + 1 );
// Average results
resultColor = ( upperLeftColor * 0.125f ) + ( recUpperLeft * 0.125f ) +
( upperRightColor * 0.125f ) + ( recUpperRight * 0.125f ) +
( lowerLeftColor * 0.125f ) + ( recLowerLeft * 0.125f ) +
( lowerRightColor * 0.125f ) + ( recLowerRight * 0.125f );
return;
}
}
// Average results
resultColor = ( upperLeftColor * 0.25f ) + ( upperRightColor * 0.25f ) +
( lowerLeftColor * 0.25f ) + ( lowerRightColor * 0.25f );
}
| 34.207143 | 120 | 0.647108 | potato3d |
c0f5da114371492206f40ca206a102997ae76437 | 32,859 | cc | C++ | src/ufo/filters/TrackCheckShip.cc | NOAA-EMC/ufo | 3bf1407731b79eab16ceff64129552577d9cfcd0 | [
"Apache-2.0"
] | null | null | null | src/ufo/filters/TrackCheckShip.cc | NOAA-EMC/ufo | 3bf1407731b79eab16ceff64129552577d9cfcd0 | [
"Apache-2.0"
] | 10 | 2020-12-10T22:57:51.000Z | 2020-12-17T15:57:04.000Z | src/ufo/filters/TrackCheckShip.cc | NOAA-EMC/ufo | 3bf1407731b79eab16ceff64129552577d9cfcd0 | [
"Apache-2.0"
] | 3 | 2020-12-10T18:38:22.000Z | 2020-12-11T01:36:37.000Z | /*
* (C) Copyright 2021 Met Office UK
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "ufo/filters/TrackCheckShip.h"
#include <Eigen/Core> // for easy array addition/subtraction
#include <algorithm>
#include <cassert>
#include <cmath>
#include <functional>
#include <map>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "ioda/ObsDataVector.h"
#include "ioda/ObsSpace.h"
#include "oops/base/Variables.h"
#include "oops/util/DateTime.h"
#include "oops/util/Duration.h"
#include "oops/util/Logger.h"
#include "ufo/filters/ObsAccessor.h"
#include "ufo/filters/TrackCheckShipDiagnostics.h"
#include "ufo/filters/TrackCheckShipParameters.h"
#include "ufo/utils/Constants.h"
#include "ufo/utils/RecursiveSplitter.h"
namespace ufo {
TrackCheckShip::TrackCheckShip(ioda::ObsSpace &obsdb, const Parameters_ ¶meters,
std::shared_ptr<ioda::ObsDataVector<int> > flags,
std::shared_ptr<ioda::ObsDataVector<float> > obserr)
: FilterBase(obsdb, parameters, flags, obserr), options_(parameters)
{
oops::Log::debug() << "TrackCheckShip: config = " << options_ << std::endl;
assert(options_.core.maxSpeed.value() > 0);
if (options_.testingMode)
diagnostics_.reset(new TrackCheckShipDiagnostics());
}
/// \brief Estimate of speed as calculated in Ops_CheckShipTrack.
///
/// Speed is calculated between \p obs1 and \p obs2, accounting for spatial/temporal
/// uncertainty using the resolution values stored in \p options.
double TrackCheckShip::speedEstimate(
const TrackCheckShip::TrackObservation &obs1,
const TrackCheckShip::TrackObservation &obs2,
const TrackCheckShipParameters& options) {
util::Duration temporalDistance = abs(obs1.getTime() -
obs2.getTime());
util::Duration tempRes = options.core.temporalResolution;
auto dist = distance(obs1, obs2);
auto spatialRes = options.core.spatialResolution;
double speedEst = 0.0;
if (dist > spatialRes) {
speedEst = (dist - 0.5 * spatialRes) /
std::max(temporalDistance.toSeconds(),
(tempRes.toSeconds()));
speedEst *= 1000.0; // convert units from km/s to m/s
}
return speedEst;
}
/// \brief Returns the angle in degrees (rounded to the nearest .1 degree)
/// between displacement vectors going from observations \p a to \p b
/// and \p b to \p c.
float TrackCheckShip::angle(const TrackCheckShip::TrackObservation &a,
const TrackCheckShip::TrackObservation &b,
const TrackCheckShip::TrackObservation &c) {
auto locA = a.getLocation();
auto locB = b.getLocation();
auto locC = c.getLocation();
Eigen::Vector3f disp1{locB[0]-locA[0], locB[1]-locA[1], locB[2]-locA[2]};
Eigen::Vector3f disp2{locC[0]-locB[0], locC[1]-locB[1], locC[2]-locB[2]};
auto retValue = std::acos(disp1.dot(disp2) / (disp1.norm() * disp2.norm()));
retValue *= static_cast<float>(Constants::rad2deg);
return std::round(retValue * 10.0f) * 0.1f;
}
const TrackCheckShipDiagnostics* TrackCheckShip::diagnostics() const
{
return diagnostics_.get();
}
TrackCheckShip::TrackObservation::TrackObservation(
double latitude, double longitude,
const util::DateTime &time,
std::shared_ptr<TrackStatistics> const& ts,
std::shared_ptr<TrackCheckUtils::CheckCounter> const &checkCounter,
size_t observationNumber)
: obsLocationTime_(latitude, longitude, time), fullTrackStatistics_(ts),
observationNumber_(observationNumber), rejected_(false) {}
size_t TrackCheckShip::TrackObservation::getObservationNumber() const
{
return observationNumber_;
}
// Required for the correct destruction of options_.
TrackCheckShip::~TrackCheckShip()
{}
/// Detects whether each observation in a track has been rejected, and marks
/// the corresponding space in \p isRejected as true if so.
/// \param trackObsIndicesBegin the begin iterator of the track
/// \param trackObsIndicesEnd the end iterator
/// \param validObsIds the vector marking all of the observations' global
/// positions
/// \param trackObservations the full vector of observations within
/// the single track
/// \param isRejected the boolean vector whose indices correspond to all of
/// the rejected observations in the full input dataset
void TrackCheckShip::flagRejectedTrackObservations(
std::vector<size_t>::const_iterator trackObsIndicesBegin,
std::vector<size_t>::const_iterator trackObsIndicesEnd,
const std::vector<size_t> &validObsIds,
const std::vector<TrackObservation> &trackObservations,
std::vector<bool> &isRejected) const {
auto trackObsIndexIt = trackObsIndicesBegin;
auto trackObsIt = trackObservations.begin();
for (; trackObsIndexIt != trackObsIndicesEnd; ++trackObsIndexIt, ++trackObsIt)
isRejected[validObsIds[*trackObsIndexIt]] = trackObsIt->rejected();
}
void TrackCheckShip::print(std::ostream & os) const {
os << "TrackCheckShip: config = " << options_ << std::endl;
}
/// The filter begins with separating observations into tracks based on \p Station_Id. Various
/// calculations are then performed between consecutive observations: distances/speeds between
/// observation pairs, and angles between the displacement vectors formed by triplets of
/// consecutive observations. Track-specific counters are incremented for various metrics that
/// indicate an unexpected track path.
///
/// Based on these counter values, the filter may ignore the current track and move on to the next
/// one. Using the described calculations and additional ones if necessary, the observation
/// directly before and/or after the fastest segment is chosen for rejection. This will continue
/// until all remaining segments that link accepted observations are either:
/// 1. slower than a user-defined "max speed (m/s)" where the angles between the fastest accepted
/// segment's displacement vector and its two neighbouring segments' displacement vectors are
/// both less than 90 degrees.
/// 2. slower than 80 percent of this user-defined speed.
///
/// The full track will be rejected if the number of observations removed is more than the
/// user-defined "rejection threshold".
void TrackCheckShip::applyFilter(const std::vector<bool> & apply,
const Variables & filtervars,
std::vector<std::vector<bool>> & flagged) const {
ObsAccessor obsAccessor = TrackCheckUtils::createObsAccessor(options_.stationIdVariable, obsdb_);
const std::vector<size_t> validObsIds
= obsAccessor.getValidObservationIds(apply, *flags_, filtervars);
RecursiveSplitter splitter = obsAccessor.splitObservationsIntoIndependentGroups(validObsIds);
TrackCheckUtils::sortTracksChronologically(validObsIds, obsAccessor, splitter);
TrackCheckUtils::ObsGroupLocationTimes obsLocTime =
TrackCheckUtils::collectObservationsLocations(obsAccessor);
std::vector<bool> isRejected(obsLocTime.latitudes.size(), false);
size_t trackNumber = 0;
for (auto track : splitter.multiElementGroups()) {
trackNumber++;
std::string stationId = std::to_string(trackNumber);
std::vector<TrackObservation> trackObservations = collectTrackObservations(
track.begin(), track.end(), validObsIds, obsLocTime);
std::vector<std::reference_wrapper<TrackObservation>> trackObservationsReferences;
trackObservationsReferences.reserve(trackObservations.size());
std::transform(trackObservations.begin(), trackObservations.end(),
std::back_inserter(trackObservationsReferences),
[](TrackObservation &obs) {
return std::ref<TrackObservation>(obs); });
calculateTrackSegmentProperties(trackObservationsReferences,
CalculationMethod::FIRSTITERATION);
if (!trackObservationsReferences.empty() &&
this->options_.core.earlyBreakCheck &&
TrackCheckShip::earlyBreak(trackObservationsReferences, stationId)) {
continue;
}
bool firstIterativeRemoval = true;
while (trackObservationsReferences.size() >= 3) {
// Initial loop: fastest (as determined by set of comparisons) observation removed
// until all segments show slower speed than max threshold
auto maxSpeedReferenceIterator = std::max_element(
trackObservationsReferences.begin(), trackObservationsReferences.end(),
[](TrackObservation a, TrackObservation b) {
return a.getObservationStatistics().speed <
b.getObservationStatistics().speed;});
auto maxSpeedValue = maxSpeedReferenceIterator->get().getObservationStatistics().speed;
if (maxSpeedValue <= (0.8 * options_.core.maxSpeed.value())) {
break;
} else if (maxSpeedValue < options_.core.maxSpeed.value()) {
auto maxSpeedAngle = std::max(
(maxSpeedReferenceIterator - 1)->get().getObservationStatistics().angle,
maxSpeedReferenceIterator->get().getObservationStatistics().angle);
if (maxSpeedAngle <= 90.0) {
break;
}
}
removeFaultyObservation(
trackObservationsReferences, maxSpeedReferenceIterator, firstIterativeRemoval,
stationId);
firstIterativeRemoval = false;
calculateTrackSegmentProperties(trackObservationsReferences, CalculationMethod::MAINLOOP);
}
auto rejectedCount = std::count_if(trackObservations.begin(), trackObservations.end(),
[](const TrackObservation& a) {return a.rejected();});
if (rejectedCount >= options_.core.rejectionThreshold.value() * trackObservations.size()) {
oops::Log::trace() << "CheckShipTrack: track " << stationId << " NumRej " <<
rejectedCount << " out of " << trackObservations.size() <<
" reports rejected. *** Reject whole track ***\n";
for (TrackObservation &obs : trackObservations)
obs.setRejected(true);
}
flagRejectedTrackObservations(track.begin(), track.end(),
validObsIds, trackObservations, isRejected);
}
obsAccessor.flagRejectedObservations(isRejected, flagged);
}
/// \returns a \p vector of \p TrackObservations that all hold a \p shared_ptr to an instance
/// of \p TrackStatistics, which holds all of the track-specific counters.
std::vector<TrackCheckShip::TrackObservation> TrackCheckShip::collectTrackObservations(
std::vector<size_t>::const_iterator trackObsIndicesBegin,
std::vector<size_t>::const_iterator trackObsIndicesEnd,
const std::vector<size_t> &validObsIds,
const TrackCheckUtils::ObsGroupLocationTimes &obsLocTime) const {
std::vector<TrackObservation> trackObservations;
trackObservations.reserve(trackObsIndicesEnd - trackObsIndicesBegin);
std::shared_ptr<TrackStatistics> trackStatistics(new TrackStatistics());
std::shared_ptr<TrackCheckUtils::CheckCounter> checkCounter(new TrackCheckUtils::CheckCounter);
size_t observationNumber = 0;
for (std::vector<size_t>::const_iterator it = trackObsIndicesBegin;
it != trackObsIndicesEnd; ++it) {
const size_t obsId = validObsIds[*it];
trackObservations.push_back(TrackObservation(obsLocTime.latitudes[obsId],
obsLocTime.longitudes[obsId],
obsLocTime.datetimes[obsId], trackStatistics,
checkCounter,
observationNumber));
observationNumber++;
}
return trackObservations;
}
/// \brief \returns true if at least half of the track segments have
/// incremented the relevant rejection counters
///
/// This filter is best for mostly-accurate observation tracks. If the track has
/// many "errors" (as indicated by the counters that are incremented before
/// any observations are removed), it will stop early by default.
///
/// Sometimes caused by two ships with same callsign or various reports with wrong time,
/// the check gives up. This is particularly a problem with WOD01 data - case studies
/// suggest that most suspect data is reasonable.
bool TrackCheckShip::earlyBreak(const std::vector<std::reference_wrapper<TrackObservation>>
&trackObs, const std::string trackId) const {
bool breakResult = false;
const auto& trackStats = *(trackObs[0].get().getFullTrackStatistics());
// if at least half of the track segments have a time difference of less than an hour
// (if non-buoy), are faster than a configured maximum speed, or exhibit at least a 90
// degree bend
if ((2 * ((options_.inputCategory.value() != SurfaceObservationSubtype::BUOY &&
options_.inputCategory.value() != SurfaceObservationSubtype::BUOYPROF)
* trackStats.numShort_ + trackStats.numFast_) + trackStats.numBends_)
>= (trackObs.size() - 1)) {
oops::Log::trace() << "ShipTrackCheck: " << trackId << "\n" <<
"Time difference < 1 hour: " << trackStats.numShort_ << "\n" <<
"Fast: " << trackStats.numFast_ << "\n" <<
"Bends: " << trackStats.numBends_ << "\n" <<
"Total observations: " << trackObs.size() << "\n" <<
"Track was not checked." << std::endl;
breakResult = true;
}
if (options_.testingMode)
diagnostics_->storeEarlyBreakResult(breakResult);
return breakResult;
}
/// \brief Chooses which of the observations surrounding the speediest segment to remove,
/// flagging it accordingly.
void TrackCheckShip::removeFaultyObservation(
std::vector<std::reference_wrapper<TrackObservation>> &track,
const std::vector<std::reference_wrapper<TrackObservation>>::iterator
&observationAfterFastestSegment,
bool firstIterativeRemoval, const std::string trackId) const {
int errorCategory = 0;
util::Duration four_days{"P4D"};
auto rejectedObservation = observationAfterFastestSegment;
// lambda function to "fail" an observation that should be rejected
auto fail = [&rejectedObservation](
const std::vector<std::reference_wrapper<TrackObservation>>::iterator &iter) {
iter->get().setRejected(true);
rejectedObservation = iter;
};
auto neighborObservationStatistics = [&observationAfterFastestSegment](int index) ->
const ObservationStatistics & {
return (observationAfterFastestSegment + index)->get().getObservationStatistics();
};
auto meanSpeed = observationAfterFastestSegment->get().getFullTrackStatistics()->meanSpeed_;
if (observationAfterFastestSegment == track.begin() + 1) {
// Decide whether ob 0 or 1 agrees best with ob 2
if (neighborObservationStatistics(0).speedAveraged <=
options_.core.maxSpeed &&
(neighborObservationStatistics(1).speed >
options_.core.maxSpeed ||
neighborObservationStatistics(1).angle > 45.0)) {
fail(observationAfterFastestSegment);
errorCategory = 2;
} else {
fail(observationAfterFastestSegment - 1);
errorCategory = 1;
}
} else if (observationAfterFastestSegment == track.end() - 1) {
if (neighborObservationStatistics(-1).speedAveraged <=
options_.core.maxSpeed &&
(neighborObservationStatistics(-1).speed >
options_.core.maxSpeed ||
neighborObservationStatistics(-2).angle > 45.0)) {
fail(observationAfterFastestSegment - 1);
errorCategory = 2;
} else {
fail(observationAfterFastestSegment);
errorCategory = 1;
}
} else if (neighborObservationStatistics(-1).speed >
options_.core.maxSpeed) {
fail(observationAfterFastestSegment - 1);
errorCategory = 4;
// Category 4: both segments surrounding observation have excessive speed
} else if (neighborObservationStatistics(1).speed >
options_.core.maxSpeed) {
fail(observationAfterFastestSegment);
errorCategory = 4;
} else if (neighborObservationStatistics(0).speedAveraged >
options_.core.maxSpeed) {
fail(observationAfterFastestSegment - 1);
errorCategory = 5;
// Category 5: observation before fastest segment would still begin a fast segment
// if observation after fastest segment were removed
} else if (neighborObservationStatistics(-1).speedAveraged >
options_.core.maxSpeed) {
fail(observationAfterFastestSegment);
errorCategory = 5;
// Category 5: observation after fastest segment would still end a fast segment if
// observation before fastest segment were removed
} else if (neighborObservationStatistics(-1).angle >
(45.0 + neighborObservationStatistics(0).angle)) {
fail(observationAfterFastestSegment - 1);
errorCategory = 6;
} else if (neighborObservationStatistics(0).angle >
45.0 + neighborObservationStatistics(-1).angle) {
fail(observationAfterFastestSegment);
errorCategory = 6;
} else if (neighborObservationStatistics(-2).angle > 45.0 &&
neighborObservationStatistics(-2).angle >
neighborObservationStatistics(1).angle) {
fail(observationAfterFastestSegment - 1);
errorCategory = 7;
} else if (neighborObservationStatistics(1).angle > 45.0) {
fail(observationAfterFastestSegment);
errorCategory = 7;
} else if (neighborObservationStatistics(-1).speed <
0.5 * std::min(
neighborObservationStatistics(1).speed,
meanSpeed)) {
fail(observationAfterFastestSegment - 1);
errorCategory = 8;
} else if (neighborObservationStatistics(1).speed <
0.5 * std::min(neighborObservationStatistics(-1).speed, meanSpeed)) {
fail(observationAfterFastestSegment);
errorCategory = 8;
} else {
double distanceSum = 0.0;
distanceSum = std::accumulate(observationAfterFastestSegment - 1,
observationAfterFastestSegment + 2, distanceSum,
[](double summed, TrackObservation& obs) {
return summed + obs.getObservationStatistics().distance;
});
double distancePrevObsOmitted =
neighborObservationStatistics(-1).distanceAveraged +
neighborObservationStatistics(1).distance;
double distanceCurrentObsOmitted =
neighborObservationStatistics(-1).distance +
neighborObservationStatistics(0).distanceAveraged;
util::Duration timeSum = (observationAfterFastestSegment + 1)->get().getTime() - (
observationAfterFastestSegment - 2)->get().getTime();
if (options_.testingMode.value()) {
diagnostics_->storeDistanceSum(distanceSum);
diagnostics_->storeDistancePrevObsOmitted(distancePrevObsOmitted);
diagnostics_->storeDistanceCurrentObsOmitted(distanceCurrentObsOmitted);
double timeDouble = timeSum.toSeconds();
diagnostics_->storeTimeSum(timeDouble);
}
if (distancePrevObsOmitted < distanceCurrentObsOmitted - std::max(
options_.core.spatialResolution.value(), 0.1 * distanceSum)) {
fail(observationAfterFastestSegment - 1);
errorCategory = 9;
} else if (distanceCurrentObsOmitted < (
distancePrevObsOmitted - std::max(
options_.core.spatialResolution.value(), 0.1 * distanceSum))) {
fail(observationAfterFastestSegment);
errorCategory = 9;
} else if (timeSum <= four_days && timeSum.toSeconds() > 0 &&
std::min(distancePrevObsOmitted, distanceCurrentObsOmitted) > 0.0) {
double previousSegmentDistanceProportion =
// Prev segment dist/(prev segment distance + distAveragedCurrentObservation)
neighborObservationStatistics(-1).distance /
distanceCurrentObsOmitted;
double previousObservationDistanceAveragedProportion =
// Previous observation distAveraged / (prev obs distAveraged + next segment distance)
neighborObservationStatistics(-1).
distanceAveraged / distancePrevObsOmitted;
double previousSegmentTimeProportion =
static_cast<double>(((observationAfterFastestSegment - 1)->get().getTime() -
(observationAfterFastestSegment - 2)->get().getTime()).toSeconds()) /
timeSum.toSeconds();
double previousAndFastestSegmentTimeProportion =
static_cast<double>(((observationAfterFastestSegment->get().getTime()) -
(observationAfterFastestSegment - 2)->get().getTime()).toSeconds()) /
timeSum.toSeconds();
if (options_.testingMode.value()) {
diagnostics_->storePreviousSegmentDistanceProportion(previousSegmentDistanceProportion);
diagnostics_->storePreviousObservationDistanceAveragedProportion(
previousObservationDistanceAveragedProportion);
diagnostics_->storePreviousSegmentTimeProportion(previousSegmentTimeProportion);
diagnostics_->storePreviousAndFastestSegmentTimeProportion(
previousAndFastestSegmentTimeProportion);
}
if (std::abs(previousSegmentDistanceProportion - previousSegmentTimeProportion) >
0.1 + std::abs(previousObservationDistanceAveragedProportion -
previousAndFastestSegmentTimeProportion)) {
// previous segment's spatial and temporal lengths are significantly more disproportionate
// when compared to a larger portion of track
// than the equivalents for the post-fastest segment
fail(observationAfterFastestSegment - 1);
errorCategory = 10;
} else if (std::abs(previousObservationDistanceAveragedProportion -
previousAndFastestSegmentTimeProportion) > 0.1 +
std::abs(previousSegmentDistanceProportion - previousSegmentTimeProportion)) {
// next segment after fastest has spatial and temporal lengths that are significantly more
// disproportionate than the segment before the fastest
fail(observationAfterFastestSegment);
errorCategory = 10;
} else {
fail(observationAfterFastestSegment);
}
oops::Log::trace() << "CheckShipTrack: proportions " << previousSegmentDistanceProportion <<
" " << previousSegmentTimeProportion <<
" " << previousObservationDistanceAveragedProportion << " "
<< previousAndFastestSegmentTimeProportion << " speeds: " << meanSpeed
<< " " << neighborObservationStatistics(-1).speed << " " <<
neighborObservationStatistics(0).speed << " " <<
neighborObservationStatistics(1).speed << " [m/s]" << std::endl;
}
if (errorCategory == 9 || std::min(distancePrevObsOmitted, distanceCurrentObsOmitted) == 0.0) {
oops::Log::trace() << "CheckShipTrack: Dist check, station id: " <<
trackId << std::endl <<
" error category: " << errorCategory << std::endl <<
" distances: " << distanceSum * 0.001 << " " <<
distancePrevObsOmitted * 0.001 << " " <<
distanceCurrentObsOmitted * 0.001 << " " <<
(distancePrevObsOmitted - distanceCurrentObsOmitted) * 0.001 <<
" " << std::max(options_.core.spatialResolution.value(),
0.1 * distanceSum) *
0.001 << "[km]" << std::endl;
}
}
if (errorCategory == 0 || ((rejectedObservation->get().getObservationStatistics().
speedAveraged) >
options_.core.maxSpeed.value())) {
oops::Log::trace() << "CheckShipTrack: cannot decide between station id " <<
trackId << " observations " <<
(observationAfterFastestSegment - 1)->get().getObservationNumber() <<
" " << observationAfterFastestSegment->get().getObservationNumber() <<
" rejecting both." << std::endl;
errorCategory += 100;
if (options_.testingMode.value() && firstIterativeRemoval) {
std::vector<size_t> observationNumbersAroundFastest{
(observationAfterFastestSegment - 1)->get().getObservationNumber(),
observationAfterFastestSegment->get().getObservationNumber()};
diagnostics_->storeFirstIterativeRemovalInfo(
std::make_pair(observationNumbersAroundFastest, errorCategory));
}
if (rejectedObservation == observationAfterFastestSegment) {
fail(observationAfterFastestSegment - 1);
} else {
fail(observationAfterFastestSegment);
}
track.erase(observationAfterFastestSegment - 1, observationAfterFastestSegment);
} else {
if (options_.testingMode.value() && firstIterativeRemoval) {
std::vector<size_t> rejectedObservationNumber{rejectedObservation->get().
getObservationNumber()};
diagnostics_->storeFirstIterativeRemovalInfo(
std::make_pair(rejectedObservationNumber,
errorCategory));
}
oops::Log::trace() << "CheckShipTrack: rejecting station " << trackId << " observation " <<
rejectedObservation->get().getObservationNumber() << "\n" <<
"Error category: " << errorCategory << "\n" <<
"rejection candidates: " <<
(observationAfterFastestSegment - 1)->get().getObservationNumber() <<
" " << observationAfterFastestSegment->get().getObservationNumber() <<
"\n" << "speeds: " << (observationAfterFastestSegment - 1)->get().
getObservationStatistics().speed << " " <<
observationAfterFastestSegment->get().getObservationStatistics().speed <<
"\n" << (observationAfterFastestSegment - 1)->get().
getObservationStatistics().angle << " " <<
observationAfterFastestSegment->get().
getObservationStatistics().angle << "\n";
track.erase(rejectedObservation);
}
}
/// \todo Trace output will need to be changed to match that of OPS (indices, LWin)
/// \brief Calculates all of the statistics that require only two
/// adjacent \p TrackObservations, storing within the righthand observation.
///
/// This includes
/// distance between the two observations,
/// time difference between the observations, speed between the
/// observations, and if the
/// observations are recorded for the same time. Calls function to
/// increment track-wise counters based on
/// results.
void TrackCheckShip::TrackObservation::calculateTwoObservationValues(
TrackObservation& prevObs, bool firstIteration,
const TrackCheckShipParameters &options) {
this->setDistance(TrackCheckShip::distance(prevObs, *this));
(this->observationStatistics_.distance > options.core.spatialResolution) ?
this->setSpeed(TrackCheckShip::speedEstimate(*this, prevObs, options)) :
this->setSpeed(0.0);
this->setTimeDifference(getTime() - prevObs.getTime());
if (firstIteration) {
adjustTwoObservationStatistics(options);
}
}
void TrackCheckShip::TrackObservation::resetObservationCalculations() {
this->setDistance(0.0);
this->setSpeed(0.0);
this->setDistanceAveraged(0.0);
this->setSpeedAveraged(0.0);
this->setAngle(0.0);
}
/// Calculates all of the statistics that require three
/// consecutive \p TrackObservations,
/// storing within the middle observation. This includes
/// distance between two alternating observations,
/// speed between these alternating observations (if the middle
/// observation was not recorded), and the
/// angle formed by the three-observation track segment.
/// Calls function to increment track-wise counters based on results.
void TrackCheckShip::TrackObservation::calculateThreeObservationValues(
const TrackObservation& prevObs, const TrackObservation& nextObs,
bool firstIteration, const TrackCheckShipParameters &options) {
this->setDistanceAveraged(TrackCheckShip::distance(prevObs, nextObs));
this->setSpeedAveraged(speedEstimate(prevObs, nextObs, options));
if (std::min(this->observationStatistics_.distance,
nextObs.observationStatistics_.distance) >
options.core.spatialResolution) {
this->observationStatistics_.angle = angle(prevObs, *this, nextObs);
}
if (firstIteration) {
adjustThreeObservationStatistics();
}
}
/// This performs all of the necessary calculations based on the
/// observations' locations and timestamps by calling
/// \p calculateTwoObservationValues and \p calculateThreeObservationValues for the
/// non-edge-case observations.
void TrackCheckShip::calculateTrackSegmentProperties(
const std::vector<std::reference_wrapper<TrackObservation>> &trackObservations,
CalculationMethod calculationMethod) const {
if (trackObservations.size()) {
if (calculationMethod == MAINLOOP)
trackObservations[0].get().resetObservationCalculations();
for (size_t obsIdx = 1; obsIdx < trackObservations.size(); obsIdx++) {
TrackObservation &obs = trackObservations[obsIdx].get();
TrackObservation &prevObs = trackObservations[obsIdx - 1].get();
obs.calculateTwoObservationValues(prevObs, calculationMethod == FIRSTITERATION, options_);
if (obsIdx > 1) {
const TrackObservation &prevPrevObs = trackObservations[obsIdx - 2].get();
prevObs.calculateThreeObservationValues(prevPrevObs, obs,
calculationMethod == FIRSTITERATION, options_);
}
if (calculationMethod == FIRSTITERATION && (obsIdx == trackObservations.size() - 1)) {
int potentialDenominator = trackObservations.size() - 1 -
obs.getFullTrackStatistics()->numShort_ - obs.getFullTrackStatistics()->numFast_;
(obs.getFullTrackStatistics()->meanSpeed_) = (obs.getFullTrackStatistics()->sumSpeed_) /
std::max(1, potentialDenominator);
}
}
if (options_.testingMode.value() && calculationMethod != MAINLOOP) {
std::vector<TrackCheckShip::ObservationStatistics> obsStats;
for (size_t obsIdx = 0; obsIdx < trackObservations.size(); ++obsIdx) {
obsStats.push_back(trackObservations[obsIdx].get().getObservationStatistics());
}
auto trackStats = *(trackObservations[0].get().getFullTrackStatistics());
if (calculationMethod == FIRSTITERATION)
diagnostics_->storeInitialCalculationResults(std::make_pair(obsStats, trackStats));
}
}
}
/// \brief Keeps track of 0-distanced, short, and fast track segments,
/// as well as incrementing \p sumSpeed_ for normal track segments.
void TrackCheckShip::TrackObservation::adjustTwoObservationStatistics
(const TrackCheckShipParameters &options) const {
util::Duration hour{"PT1H"};
if (getObservationStatistics().timeDifference < hour) {
getFullTrackStatistics()->numShort_++;
} else if (getObservationStatistics().speed >= options.core.maxSpeed) {
getFullTrackStatistics()->numFast_++;
} else {
getFullTrackStatistics()->sumSpeed_ += getObservationStatistics().speed;
}
}
/// \brief Increments number of bends if angle is greater than or equal to 90 degrees
void TrackCheckShip::TrackObservation::adjustThreeObservationStatistics() const {
if (getObservationStatistics().angle >= 90.0)
getFullTrackStatistics()->numBends_++;
}
const TrackCheckShip::ObservationStatistics &
TrackCheckShip::TrackObservation::getObservationStatistics() const
{
return observationStatistics_;
}
const std::shared_ptr<TrackCheckShip::TrackStatistics>
TrackCheckShip::TrackObservation::getFullTrackStatistics() const
{
return fullTrackStatistics_;
}
void TrackCheckShip::TrackObservation::setDistance(double dist) {
this->observationStatistics_.distance = dist;
}
void TrackCheckShip::TrackObservation::setTimeDifference(util::Duration tDiff) {
this->observationStatistics_.timeDifference = tDiff;
}
void TrackCheckShip::TrackObservation::setSpeed(double speed) {
this->observationStatistics_.speed = speed;
}
void TrackCheckShip::TrackObservation::setAngle(double angle) {
this->observationStatistics_.angle = angle;
}
void TrackCheckShip::TrackObservation::setDistanceAveraged(double distAvg) {
this->observationStatistics_.distanceAveraged = distAvg;
}
void TrackCheckShip::TrackObservation::setSpeedAveraged(double speedAvg) {
this->observationStatistics_.speedAveraged = speedAvg;
}
} // namespace ufo
| 49.043284 | 100 | 0.686205 | NOAA-EMC |
c0f841ff3bfcf22e1244e3fc2bfd9b3193a62b29 | 367 | cpp | C++ | src/jitcat/TypeInfoDeleter.cpp | Zueuk/JitCat | 04eb77a9acf6f8b36689c0aabcb6d68edd28f0fc | [
"MIT"
] | 14 | 2019-03-16T07:00:44.000Z | 2021-10-20T23:36:51.000Z | src/jitcat/TypeInfoDeleter.cpp | Zueuk/JitCat | 04eb77a9acf6f8b36689c0aabcb6d68edd28f0fc | [
"MIT"
] | 13 | 2019-11-22T12:43:55.000Z | 2020-05-25T13:09:08.000Z | src/jitcat/TypeInfoDeleter.cpp | Zueuk/JitCat | 04eb77a9acf6f8b36689c0aabcb6d68edd28f0fc | [
"MIT"
] | 1 | 2019-11-23T17:59:58.000Z | 2019-11-23T17:59:58.000Z | /*
This file is part of the JitCat library.
Copyright (C) Machiel van Hooren 2020
Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
#include "jitcat/TypeInfoDeleter.h"
#include "jitcat/TypeInfo.h"
void jitcat::Reflection::TypeInfoDeleter::operator()(TypeInfo* typeInfo) const
{
TypeInfo::destroy(typeInfo);
}
| 22.9375 | 94 | 0.746594 | Zueuk |
c0f94c1d95812e041af5802cf0bc130c2bb8c249 | 1,635 | cpp | C++ | Chapter_03/sample6.cpp | expoli/Learn-OpenCV-4-By-Building-Projects-Second-Edition | f0288b6a303923da100393b60b79f8eaf3a03165 | [
"MIT"
] | 1 | 2020-07-30T10:30:29.000Z | 2020-07-30T10:30:29.000Z | Chapter_03/sample6.cpp | expoli/Learn-OpenCV-4-By-Building-Projects-Second-Edition | f0288b6a303923da100393b60b79f8eaf3a03165 | [
"MIT"
] | null | null | null | Chapter_03/sample6.cpp | expoli/Learn-OpenCV-4-By-Building-Projects-Second-Edition | f0288b6a303923da100393b60b79f8eaf3a03165 | [
"MIT"
] | null | null | null | #include <opencv2/viz.hpp>
#include <opencv2/calib3d.hpp>
#include <iostream>
using namespace cv;
using namespace std;
/*
* @function main
*/
int main() {
/// Create a window
viz::Viz3d myWindow("Coordinate Frame");
/// Add coordinate axes
myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
/// Add line to represent (1,1,1) axis
viz::WLine axis(Point3f(-1.0f, -1.0f, -1.0f), Point3f(1.0f, 1.0f, 1.0f));
axis.setRenderingProperty(viz::LINE_WIDTH, 4.0);
myWindow.showWidget("Line Widget", axis);
/// Construct a cube widget
viz::WCube cube_widget(Point3f(0.5, 0.5, 0.0), Point3f(0.0, 0.0, -0.5), true, viz::Color::blue());
cube_widget.setRenderingProperty(viz::LINE_WIDTH, 4.0);
/// Display widget (update if already displayed)
myWindow.showWidget("Cube Widget", cube_widget);
/// Rodrigues vector
Mat rot_vec = Mat::zeros(1, 3, CV_32F);
float translation_phase = 0.0, translation = 0.0;
while (!myWindow.wasStopped()) {
/* Rotation using rodrigues */
/// Rotate around (1,1,1)
rot_vec.at<float>(0, 0) += CV_PI * 0.01f;
rot_vec.at<float>(0, 1) += CV_PI * 0.01f;
rot_vec.at<float>(0, 2) += CV_PI * 0.01f;
/// Shift on (1,1,1)
translation_phase += CV_PI * 0.01f;
translation = sin(translation_phase);
Mat rot_mat;
Rodrigues(rot_vec, rot_mat);
/// Construct pose
Affine3f pose(rot_mat, Vec3f(translation, translation, translation));
myWindow.setWidgetPose("Cube Widget", pose);
myWindow.spinOnce(1, true);
}
return 0;
} | 29.196429 | 102 | 0.620795 | expoli |
c0fad15e9df31d2ee09c0e977e287c7c3f61ae14 | 9,041 | cpp | C++ | assets/API/api.cpp | KingsleyXie/SupermarketManagement | 9fea4a13792d0b44ed871da9f2af5240c6931fec | [
"MIT"
] | null | null | null | assets/API/api.cpp | KingsleyXie/SupermarketManagement | 9fea4a13792d0b44ed871da9f2af5240c6931fec | [
"MIT"
] | null | null | null | assets/API/api.cpp | KingsleyXie/SupermarketManagement | 9fea4a13792d0b44ed871da9f2af5240c6931fec | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
fstream data; // File with all the data of this system
json request, response, record; // JSON for request, response and existed data record
double rate = 1.5; // Rate from payment to points
int destination, operation, data_index; // Request Judgement, Shunt and JSON data array index
class DATA
// Base class of the whole program
{
public:
DATA(json req)
{
request = req;
data.open("data.json", ios::in);
data >> record;
data.close();
}
~DATA()
{
data.open("data.json", ios::out);
data << record;
data.close();
}
};
class Sales: public DATA
// Sales class with Sell and Return function
{
public:
Sales(json req): DATA(req)
{
switch(operation)
{
case 1: sell_item(); break;
case 2: return_item(); break;
case 3: input_limit(); break;
}
}
private:
int sell_item()
{
data_index = request["itemID"];
int inventoryQuantity = record["items"][data_index]["inventoryQuantity"];
record["items"][data_index]["inventoryQuantity"] = inventoryQuantity - 1;
record["finance"].push_back(
{
{"name", "Sell Record"},
{"income", record["items"][data_index]["salePrice"]},
{"expenditure", 0},
{"date",
{
{"year", request["year"]},
{"month", request["month"]},
{"day", request["day"]}
}
}
});
double points = record["items"][data_index]["salePrice"];
data_index = request["customerID"];
double totalPoints = record["customers"][data_index]["totalPoints"];
record["customers"][data_index]["purchases"].push_back(
{
{"purchaseTime", request["time"]},
{"payment", points},
{"points", points * rate}
});
record["customers"][data_index]["totalPoints"] = totalPoints + points * rate;
response ={{"code", 0}};
cout << response;
return 0;
}
int return_item()
{
data_index = request["itemID"];
int inventoryQuantity = record["items"][data_index]["inventoryQuantity"];
record["items"][data_index]["inventoryQuantity"] = inventoryQuantity + 1;
record["finance"].push_back(
{
{"name", "Return Record"},
{"income", 0},
{"expenditure", record["items"][data_index]["salePrice"]},
{"date",
{
{"year", request["year"]},
{"month", request["month"]},
{"day", request["day"]}
}
}
});
double points = record["items"][data_index]["salePrice"];
data_index = request["customerID"];
double totalPoints = record["customers"][data_index]["totalPoints"];
points = - points;
record["customers"][data_index]["purchases"].push_back(
{
{"purchaseTime", request["time"]},
{"payment", points},
{"points", points * rate}
});
record["customers"][data_index]["totalPoints"] = totalPoints + points * rate;
response ={{"code", 0}};
cout << response;
return 0;
}
int input_limit()
{
response =
{
{"items", record["items"].size()},
{"suppliers", record["suppliers"].size()},
{"customers", record["customers"].size()}
};
cout << response;
return 0;
}
};
class Inventory: public DATA
// Inventory class with Add, Update function
{
public:
Inventory(json req): DATA(req)
{
switch(operation)
{
case 1: display(); break;
case 2: add(); break;
case 3: update(); break;
}
}
private:
int display()
{
response = record["items"];
cout << response;
return 0;
}
int add()
{
record["items"].push_back(
{
{"barcode", request["barcode"]},
{"brand", request["brand"]},
{"name", request["name"]},
{"type", request["type"]},
{"unspsc", request["unspsc"]},
{"price", request["price"]},
{"salePrice", request["salePrice"]},
{"inventoryQuantity", request["inventoryQuantity"]},
{"threshold", request["threshold"]},
{"expiredTime", request["expiredTime"]},
{"importTime", request["time"]},
{"updateTime", request["time"]}
});
double amount = request["inventoryQuantity"], price = request["price"];
record["finance"].push_back(
{
{"name", "Inventory Add Record"},
{"income", 0},
{"expenditure", amount * price},
{"date",
{
{"year", request["year"]},
{"month", request["month"]},
{"day", request["day"]}
}
}
});
data_index = request["supplierID"];
int itemID = record["items"].size();
record["suppliers"][data_index]["transactions"].push_back(
{
{"transactionTime", request["time"]},
{"itemID", itemID},
{"itemName", request["name"]},
{"itemAmount", request["inventoryQuantity"]},
{"itemPrice", request["price"]}
});
response ={{"code", 0}};
cout << response;
return 0;
}
int update()
{
data_index = request["itemID"];
record["items"][data_index] =
{
{"barcode", record["items"][data_index]["barcode"]},
{"brand", request["brand"]},
{"name", request["name"]},
{"type", request["type"]},
{"unspsc", request["unspsc"]},
{"price", request["price"]},
{"salePrice", request["salePrice"]},
{"inventoryQuantity", request["inventoryQuantity"]},
{"threshold", request["threshold"]},
{"expiredTime", request["expiredTime"]},
{"importTime", record["items"][data_index]["importTime"]},
{"updateTime", request["time"]}
};
double amount = request["inventoryQuantity"], price = request["price"];
record["finance"].push_back(
{
{"name", "Inventory Update Record"},
{"income", 0},
{"expenditure", amount * price},
{"date",
{
{"year", request["year"]},
{"month", request["month"]},
{"day", request["day"]}
}
}
});
data_index = request["supplierID"];
record["suppliers"][data_index]["transactions"].push_back(
{
{"transactionTime", request["time"]},
{"itemID", request["itemID"]},
{"itemName", request["name"]},
{"itemAmount", request["inventoryQuantity"]},
{"itemPrice", request["price"]}
});
response ={{"code", 0}};
cout << response;
return 0;
}
};
class Staff: public DATA
// Staff class with Add, Update function
{
public:
Staff(json req): DATA(req)
{
switch(operation)
{
case 1: display(); break;
case 2: add(); break;
case 3: update(); break;
}
}
private:
int display()
{
response = record["staffs"];
cout << response;
return 0;
}
int add()
{
record["staffs"].push_back(
{
{"jobNo", request["jobNo"]},
{"name", request["name"]},
{"gender", request["gender"]},
{"nation", request["nation"]},
{"nativePlace", request["nativePlace"]},
{"department", request["department"]},
{"postion", request["postion"]},
{"birthday", request["birthday"]},
{"contact", request["contact"]},
{"address", request["address"]},
{"salary", request["salary"]},
{"entryTime", request["entryTime"]},
{"status", request["status"]}
});
response ={{"code", 0}};
cout << response;
return 0;
}
int update()
{
data_index = request["staffID"];
record["staffs"][data_index] =
{
{"jobNo", request["jobNo"]},
{"name", request["name"]},
{"gender", request["gender"]},
{"nation", request["nation"]},
{"nativePlace", request["nativePlace"]},
{"department", request["department"]},
{"postion", request["postion"]},
{"birthday", request["birthday"]},
{"contact", request["contact"]},
{"address", request["address"]},
{"salary", request["salary"]},
{"entryTime", request["entryTime"]},
{"status", request["status"]}
};
response ={{"code", 0}};
cout << response;
return 0;
}
};
class Finance: public DATA
// Finance class with Display function
{
public:
Finance(json req): DATA(req)
{
switch(operation)
{
case 1: display(); break;
case 2: add(); break;
}
}
private:
int display()
{
response = record["finance"];
cout << response;
return 0;
}
int add()
{
record["finance"].push_back(
{
{"name", request["financeName"]},
{"income", request["income"]},
{"expenditure", request["expenditure"]},
{"date",
{
{"year", request["year"]},
{"month", request["month"]},
{"day", request["day"]}
}
}
});
response ={{"code", 0}};
cout << response;
return 0;
}
};
class Report: public DATA
// Report class with Display function
{
public:
Report(json req): DATA(req)
{
switch(operation)
{
case 1: finance_data(); break;
case 2: suppliers_data(); break;
case 3: customers_data(); break;
}
}
private:
int finance_data()
{
response = record["finance"];
cout << response;
return 0;
}
int suppliers_data()
{
response = record["suppliers"];
cout << response;
return 0;
}
int customers_data()
{
response = record["customers"];
cout << response;
return 0;
}
};
int main(int argc, char const *argv[])
{
cin >> request;
cout<<"Content-type: application/json\n\n";
destination = request["destination"];
operation = request["operation"];
switch (destination)
{
case 1: { Sales obj(request); } break;
case 2: { Inventory obj(request); } break;
case 3: { Staff obj(request); } break;
case 4: { Finance obj(request); } break;
case 5: { Report obj(request); } break;
}
return 0;
}
| 21.074592 | 93 | 0.603473 | KingsleyXie |
c0fb9efba1193e769ef84210ae216e8c50113513 | 844 | hpp | C++ | src/main/include/StarDust/file/ConfigParser.hpp | 4H-Botsmiths/InfiniteRecharge2020 | 811d71a49a50f38f44dcc7139786caaeaa99f739 | [
"BSD-3-Clause"
] | null | null | null | src/main/include/StarDust/file/ConfigParser.hpp | 4H-Botsmiths/InfiniteRecharge2020 | 811d71a49a50f38f44dcc7139786caaeaa99f739 | [
"BSD-3-Clause"
] | 1 | 2021-12-27T04:40:42.000Z | 2021-12-27T04:40:42.000Z | src/main/include/StarDust/file/ConfigParser.hpp | 4H-Botsmiths/InfiniteRecharge2020 | 811d71a49a50f38f44dcc7139786caaeaa99f739 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include "StarDust\core\StarDustComponent.hpp"
#include "StarDust\file\ParserParamBase.hpp"
#include "StarDust\file\ParserParam.hpp"
#define CONFIG_FILE_PATH "/home/lvuser/config.dat"
class ConfigParser : public StarDustComponent {
public:
//takes in a vector of ParserParams to be parsed
ConfigParser(std::vector<ParserParamBase*> parameters);
//same as above but overrides default filename with a diffent one
ConfigParser(std::vector<ParserParamBase*> parameters, std::string filename);
void __RobotInit__() override;
void __AutonomousInit__() override;
void __TeleopInit__() override;
private:
void autorun();
std::vector<ParserParamBase*> parameters;
std::string filename;
}; | 27.225806 | 82 | 0.722749 | 4H-Botsmiths |
8d0634b3b1f3d755352f283a3da9cd691f7b4425 | 2,011 | hpp | C++ | include/psinc/handlers/helpers/Filter.hpp | emergent-design/libpsinc | 8a30ebc2838d205b214e5f2e523b6bf558b0a41e | [
"MIT"
] | 2 | 2017-02-28T11:27:38.000Z | 2019-01-23T06:10:49.000Z | include/psinc/handlers/helpers/Filter.hpp | emergent-design/libpsinc | 8a30ebc2838d205b214e5f2e523b6bf558b0a41e | [
"MIT"
] | 6 | 2015-06-26T13:01:49.000Z | 2020-07-31T15:08:55.000Z | include/psinc/handlers/helpers/Filter.hpp | emergent-design/libpsinc | 8a30ebc2838d205b214e5f2e523b6bf558b0a41e | [
"MIT"
] | 1 | 2017-02-28T10:55:30.000Z | 2017-02-28T10:55:30.000Z | #pragma once
#include <emergent/Maths.hpp>
#include <emergent/image/Image.hpp>
namespace psinc
{
class Filter
{
public:
enum Mode
{
Disabled,
RowOffset, // Adjust brightness of specific rows by a fixed offset
RowGain // Adjust brightness of specific rows by a gain multiplier
};
struct Configuration
{
Mode mode = Mode::Disabled;
int start = 0; // Starting row of the mark-space pattern
int mark = 2; // Number of rows to apply the offset/gain to
int space = 5; // Number of rows to then skip
int offset = 0; // Offset to be applied to pixel values in mark rows
double gain = 1.0; // Gain multiplier to be applied to pixel values in mark rows
};
template <typename T> static void Process(const Configuration &configuration, emg::ImageBase<T> &image)
{
switch (configuration.mode)
{
case Mode::Disabled: break;
case Mode::RowOffset: Apply(configuration, image, [=](const T s) { return s + configuration.offset; }); break;
case Mode::RowGain: Apply(configuration, image, [=](const T s) { return std::lrint(configuration.gain * s); }); break;
}
}
private:
template <typename T, typename Operation> static void Apply(const Configuration &configuration, emg::ImageBase<T> &image, Operation operation)
{
int x, y;
const int width = image.Width();
const int height = image.Height();
const int depth = image.Depth();
const int row = width * depth;
const int mark = configuration.mark * row;
const int space = configuration.space * row;
const int limit = height - configuration.mark;
const int window = configuration.mark + configuration.space;
T *src = image + configuration.start * row;
for (y=configuration.start; y<height; y+=window, src+=space)
{
const int end = y < limit ? mark : (height - y) * row;
for (x=0; x<end; x++, src++)
{
*src = emg::Maths::clamp<T>(operation(*src));
}
}
}
};
}
| 28.728571 | 145 | 0.637991 | emergent-design |
8d0b5e39b44128a906a78b45bce4c9f8933b89f4 | 830 | cpp | C++ | platform/OSP/JS/Web/src/JSServletExecutorCache.cpp | gboyraz/macchina.io | 3e26fea95e87512459693831242b297f0780cc21 | [
"Apache-2.0"
] | 2 | 2020-11-23T23:37:00.000Z | 2020-12-22T04:02:41.000Z | platform/OSP/JS/Web/src/JSServletExecutorCache.cpp | bas524/cmake.macchina.io | 22a21d78f8075fd145b788b41a23603591e91c9f | [
"Apache-2.0"
] | null | null | null | platform/OSP/JS/Web/src/JSServletExecutorCache.cpp | bas524/cmake.macchina.io | 22a21d78f8075fd145b788b41a23603591e91c9f | [
"Apache-2.0"
] | 1 | 2020-11-23T23:37:09.000Z | 2020-11-23T23:37:09.000Z | //
// JSServletExecutorCache.cpp
//
// Copyright (c) 2016, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: Apache-2.0
//
#include "JSServletExecutorCache.h"
#include "Poco/SingletonHolder.h"
namespace Poco {
namespace OSP {
namespace JS {
namespace Web {
//
// JSServletExecutorHolder
//
JSServletExecutorHolder::JSServletExecutorHolder(JSServletExecutor::Ptr pExecutor):
_pExecutor(pExecutor)
{
}
//
// JSServletExecutorCache
//
JSServletExecutorCache::JSServletExecutorCache(long size):
Poco::LRUCache<std::string, JSServletExecutorHolder, Poco::Mutex>(size)
{
}
namespace
{
static Poco::SingletonHolder<JSServletExecutorCache> sh;
}
JSServletExecutorCache& JSServletExecutorCache::instance()
{
return *sh.get();
}
} } } } // namespace Poco::OSP::JS::Web
| 14.821429 | 83 | 0.745783 | gboyraz |
8d0b96f3958c3e97495049259b1da3186b50642a | 7,013 | cpp | C++ | abcg/abcg_image.cpp | guiarqueiro/entrega3 | 48d7d9828b44f232b51044269a4164056fbe95b8 | [
"MIT"
] | 11 | 2021-03-23T00:06:20.000Z | 2021-10-02T22:13:37.000Z | abcg/abcg_image.cpp | guiarqueiro/entrega3 | 48d7d9828b44f232b51044269a4164056fbe95b8 | [
"MIT"
] | 2 | 2021-03-11T23:31:39.000Z | 2021-10-04T22:21:57.000Z | abcg/abcg_image.cpp | guiarqueiro/entrega3 | 48d7d9828b44f232b51044269a4164056fbe95b8 | [
"MIT"
] | 101 | 2021-02-08T18:48:02.000Z | 2022-03-16T03:51:09.000Z | /**
* @file abcg_image.cpp
* @brief Definition of texture loading helper functions.
*
* This project is released under the MIT License.
*/
#include "abcg_image.hpp"
#include <fmt/core.h>
#include <cppitertools/itertools.hpp>
#include <fstream>
#include <gsl/gsl>
#include <span>
#include <vector>
#include "SDL_image.h"
#include "abcg_exception.hpp"
#include "abcg_external.hpp"
void flipHorizontally(gsl::not_null<SDL_Surface*> surface) {
auto width{static_cast<size_t>(surface->w * surface->format->BytesPerPixel)};
auto height{static_cast<size_t>(surface->h)};
std::span pixels{static_cast<std::byte*>(surface->pixels), width * height};
// Row of pixels for the swap
std::vector<std::byte> pixelRow(width, std::byte{});
// For each row
for (auto rowIndex : iter::range(height)) {
auto rowStart{width * rowIndex};
auto rowEnd{rowStart + width - 1};
// For each RGB triplet of this row
// C++23: for (auto tripletStart : iter::range(0uz, width, 3uz)) {
for (auto tripletStart : iter::range<std::size_t>(0, width, 3)) {
pixelRow.at(tripletStart + 0) = pixels[rowEnd - tripletStart - 2];
pixelRow.at(tripletStart + 1) = pixels[rowEnd - tripletStart - 1];
pixelRow.at(tripletStart + 2) = pixels[rowEnd - tripletStart - 0];
}
memcpy(pixels.subspan(rowStart).data(), pixelRow.data(), width);
}
}
void flipVertically(gsl::not_null<SDL_Surface*> surface) {
auto width{static_cast<size_t>(surface->w * surface->format->BytesPerPixel)};
auto height{static_cast<size_t>(surface->h)};
std::span pixels{static_cast<std::byte*>(surface->pixels), width * height};
// Row of pixels for the swap
std::vector<std::byte> pixelRow(width, std::byte{});
// If height is odd, don't need to swap middle row
size_t halfHeight{height / 2};
for (auto rowIndex : iter::range(halfHeight)) {
auto rowStartFromTop{width * rowIndex};
auto rowStartFromBottom{width * (height - rowIndex - 1)};
memcpy(pixelRow.data(), pixels.subspan(rowStartFromTop).data(), width);
memcpy(pixels.subspan(rowStartFromTop).data(),
pixels.subspan(rowStartFromBottom).data(), width);
memcpy(pixels.subspan(rowStartFromBottom).data(), pixelRow.data(), width);
}
}
GLuint abcg::opengl::loadTexture(std::string_view path, bool generateMipmaps) {
GLuint textureID{};
// Copy file data into buffer
std::ifstream input(path.data(), std::ios::binary);
if (!input) {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to open texture file {}", path))};
}
std::vector<char> buffer((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
// Load the bitmap
if (SDL_Surface * surface{IMG_Load(path.data())}) {
// Enforce RGB/RGBA
GLenum format{0};
SDL_Surface* formattedSurface{nullptr};
if (surface->format->BytesPerPixel == 3) {
formattedSurface =
SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGB24, 0);
format = GL_RGB;
} else {
formattedSurface =
SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGBA32, 0);
format = GL_RGBA;
}
SDL_FreeSurface(surface);
// Flip upside down
flipVertically(formattedSurface);
// Generate the texture
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(format),
formattedSurface->w, formattedSurface->h, 0, format,
GL_UNSIGNED_BYTE, formattedSurface->pixels);
SDL_FreeSurface(formattedSurface);
// Set texture filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Generate the mipmap levels
if (generateMipmaps) {
glGenerateMipmap(GL_TEXTURE_2D);
// Override minifying filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
}
// Set texture wrapping
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
} else {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to load texture file {}", path))};
}
glBindTexture(GL_TEXTURE_2D, 0);
return textureID;
}
GLuint abcg::opengl::loadCubemap(std::array<std::string_view, 6> paths,
bool generateMipmaps, bool rightHandedSystem) {
GLuint textureID{};
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
for (auto&& [index, path] : iter::enumerate(paths)) {
// Copy file data into buffer
std::ifstream input(path.data(), std::ios::binary);
if (!input) {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to open texture file {}", path))};
}
std::vector<char> buffer((std::istreambuf_iterator<char>(input)),
std::istreambuf_iterator<char>());
// Load the bitmap
if (SDL_Surface * surface{IMG_Load(path.data())}) {
// Enforce RGB
SDL_Surface* formattedSurface{
SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_RGB24, 0)};
SDL_FreeSurface(surface);
auto target{GL_TEXTURE_CUBE_MAP_POSITIVE_X + static_cast<GLenum>(index)};
// LHS to RHS
if (rightHandedSystem) {
if (target == GL_TEXTURE_CUBE_MAP_POSITIVE_Y ||
target == GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) {
// Flip upside down
flipVertically(formattedSurface);
} else {
flipHorizontally(formattedSurface);
}
// Swap -z with +z
if (target == GL_TEXTURE_CUBE_MAP_POSITIVE_Z)
target = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
else if (target == GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)
target = GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
}
// Create texture
glTexImage2D(target, 0, GL_RGB, formattedSurface->w, formattedSurface->h,
0, GL_RGB, GL_UNSIGNED_BYTE, formattedSurface->pixels);
SDL_FreeSurface(formattedSurface);
} else {
throw abcg::Exception{abcg::Exception::Runtime(
fmt::format("Failed to load texture file {}", path))};
}
}
// Set texture wrapping
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
// Set texture filtering
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// Generate the mipmap levels
if (generateMipmaps) {
glGenerateMipmap(GL_TEXTURE_CUBE_MAP);
// Override minifying filtering
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
}
return textureID;
}
| 34.377451 | 80 | 0.67988 | guiarqueiro |
8d0c7e11eac68d010789d67227ae3efd8dc487f1 | 6,758 | cpp | C++ | module-bluetooth/Bluetooth/WorkerController.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 1 | 2021-11-11T22:56:43.000Z | 2021-11-11T22:56:43.000Z | module-bluetooth/Bluetooth/WorkerController.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | null | null | null | module-bluetooth/Bluetooth/WorkerController.cpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include "WorkerController.hpp"
#include "Device.hpp"
#include "interface/profiles/ProfileManager.hpp"
#include <log/log.hpp>
#define BOOST_SML_CFG_DISABLE_MIN_SIZE // GCC10 fix
#include <boost/sml.hpp>
#include <magic_enum.hpp>
#include <stdexcept>
namespace bluetooth
{
namespace sml = boost::sml;
namespace
{
struct TurnOn
{};
struct TurnOff
{};
struct ShutDown
{};
struct ProcessCommand
{
Command command;
};
class InitializationError : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
class ProcessingError : public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
};
struct InitializationState
{
bool isInitDone = false;
};
struct Setup
{
public:
auto operator()() const
{
auto isInit = [](InitializationState &data) { return data.isInitDone; };
auto init = [](std::shared_ptr<AbstractDriver> &driver) {
if (const auto status = driver->init(); status != Error::Success) {
throw InitializationError{"Unable to initialize a bluetooth driver."};
}
};
auto setup = [](DeviceRegistrationFunction ®isterDevice, InitializationState &data) {
if (const auto status = registerDevice(); status != Error::Success) {
throw InitializationError{"Unable to initialize bluetooth"};
}
data.isInitDone = true;
};
auto startDriver = [](std::shared_ptr<AbstractDriver> &driver) {
if (const auto status = driver->run(); status != Error::Success) {
throw InitializationError{"Unable to run the bluetooth driver"};
}
};
using namespace sml;
// clang-format off
return make_transition_table(*"Setup"_s / startDriver = "StartingDriver"_s,
"Setup"_s + on_entry<_> [ !isInit ] / ( init, setup ),
"StartingDriver"_s = X);
// clang-format on
}
};
struct On
{
auto operator()() const
{
auto isInit = [](InitializationState &data) { return data.isInitDone; };
auto handleCommand = [](std::shared_ptr<AbstractCommandHandler> &processor,
const ProcessCommand &processCommand) {
if (const auto status = processor->handle(processCommand.command); status != Error::Success) {
throw ProcessingError{"Failed to process command"};
}
};
using namespace sml;
// clang-format off
return make_transition_table(*"Idle"_s + event<ProcessCommand> [ isInit ] / handleCommand = "Processing"_s,
"Processing"_s = "Idle"_s);
// clang-format on
}
};
class StateMachine
{
public:
auto operator()() const
{
auto turnOff = [](std::shared_ptr<AbstractDriver> &driver) { driver->stop(); };
auto printInitError = [](const InitializationError &error) { LOG_ERROR("%s", error.what()); };
auto printProcessingError = [](const ProcessingError &error) { LOG_ERROR("%s", error.what()); };
using namespace sml;
// clang-format off
return make_transition_table(*"Off"_s + event<TurnOn> = state<Setup>,
state<Setup> = state<On>,
state<Setup> + exception<InitializationError> / printInitError = "Off"_s,
state<On> + event<TurnOff> / turnOff = "Off"_s,
state<On> + exception<ProcessingError> / ( printProcessingError, turnOff ) = "Restart"_s,
"Restart"_s = state<Setup>,
"Off"_s + event<ShutDown> = X);
// clang-format on
}
};
} // namespace
class StatefulController::Impl
{
public:
Impl(std::shared_ptr<AbstractDriver> &&driver,
std::shared_ptr<AbstractCommandHandler> &&handler,
DeviceRegistrationFunction &®isterDevice);
using SM = sml::sm<StateMachine>;
SM sm;
};
StatefulController::Impl::Impl(std::shared_ptr<AbstractDriver> &&driver,
std::shared_ptr<AbstractCommandHandler> &&handler,
DeviceRegistrationFunction &®isterDevice)
: sm{std::move(driver), std::move(handler), std::move(registerDevice), InitializationState{}}
{}
StatefulController::StatefulController(std::shared_ptr<AbstractDriver> &&driver,
std::shared_ptr<AbstractCommandHandler> &&handler,
DeviceRegistrationFunction &®isterDevice)
: pimpl(std::make_unique<Impl>(std::move(driver), std::move(handler), std::move(registerDevice)))
{}
StatefulController::~StatefulController() noexcept = default;
void StatefulController::turnOn()
{
pimpl->sm.process_event(TurnOn{});
}
void StatefulController::turnOff()
{
pimpl->sm.process_event(TurnOff{});
}
void StatefulController::shutdown()
{
if (isOn()) {
turnOff();
}
pimpl->sm.process_event(ShutDown{});
}
auto StatefulController::isOn() const -> bool
{
using namespace sml;
return !pimpl->sm.is("Off"_s) && !isTerminated();
}
auto StatefulController::isTerminated() const -> bool
{
using namespace sml;
return pimpl->sm.is(X);
}
void StatefulController::processCommand(Command command)
{
LOG_INFO("Process command: %s", magic_enum::enum_name(command.getType()).data());
pimpl->sm.process_event(ProcessCommand{command});
command.destroy();
}
} // namespace bluetooth
| 36.333333 | 134 | 0.518941 | bitigchi |
8d0d8605cc351a91a7a01e7f4d83b53c781d18b5 | 2,494 | cc | C++ | src/base/backtrace.cc | biswajit-mandal/contrail-controller | 80c4a7e8515f7296b18ba4c21a439bd3daefcc4a | [
"Apache-2.0"
] | 3 | 2019-01-11T06:16:40.000Z | 2021-02-24T23:48:21.000Z | src/base/backtrace.cc | biswajit-mandal/contrail-controller | 80c4a7e8515f7296b18ba4c21a439bd3daefcc4a | [
"Apache-2.0"
] | 2 | 2018-12-04T02:20:52.000Z | 2018-12-22T06:16:30.000Z | src/base/backtrace.cc | biswajit-mandal/contrail-controller | 80c4a7e8515f7296b18ba4c21a439bd3daefcc4a | [
"Apache-2.0"
] | 18 | 2017-01-12T09:28:44.000Z | 2019-04-18T20:47:42.000Z | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "base/backtrace.h"
#include <boost/algorithm/string.hpp>
#include <execinfo.h>
#include <stdio.h>
#include "base/logging.h"
ssize_t BackTrace::ToString(void * const* callstack, int frames, char *buf,
size_t buf_len) {
#ifdef DARWIN
return 0;
#else
buf[0] = '\0';
char *str = buf;
char **strs = backtrace_symbols(callstack, frames);
int line_pos;
size_t len = 0;
for (int i = 0; i < frames; ++i) {
int status;
std::vector<std::string> SplitVec;
if (i == frames - 1) continue;
boost::split(SplitVec, strs[i], boost::is_any_of("()"),
boost::token_compress_on);
boost::split(SplitVec, SplitVec[1], boost::is_any_of("+"),
boost::token_compress_on);
char *demangledName =
abi::__cxa_demangle(SplitVec[0].c_str(), NULL, NULL, &status);
line_pos = 1;
if (status == 0) {
if (!strstr(demangledName, "boost::") &&
!strstr(demangledName, "tbb::") &&
!strstr(demangledName, "BackTrace::") &&
!strstr(demangledName, "BgpDebug::") &&
!strstr(demangledName, "testing::")) {
len = snprintf(str, buf_len - (str - buf),
"\t%s+%s\n", demangledName,
SplitVec[line_pos].c_str());
if (len > buf_len - (str - buf)) {
// Overflow
free(demangledName);
str += buf_len - (str - buf);
assert((size_t) (str - buf) == buf_len);
break;
}
str += len;
}
free(demangledName);
}
}
free(strs);
return (str - buf);
#endif
}
int BackTrace::Get(void * const* &callstack) {
callstack = (void * const *) calloc(1024, sizeof(void *));
return backtrace((void **) callstack, 1024);
}
void BackTrace::Log(void * const* callstack, int frames,
const std::string &msg) {
char buf[10240];
ToString(callstack, frames, buf, sizeof(buf));
std::string s(buf, strlen(buf));
LOG(DEBUG, msg << ":BackTrace\n" << s);
free((void *) callstack);
}
void BackTrace::Log(const std::string &msg) {
void * const*callstack;
int frames = Get(callstack);
Log(callstack, frames, msg);
}
| 28.666667 | 75 | 0.514435 | biswajit-mandal |
8d0dc6792d46403023b45863ba006a57cf0c1f15 | 4,264 | cpp | C++ | src/mongo/s/commands/cluster_find_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/commands/cluster_find_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/commands/cluster_find_test.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/query/cursor_response.h"
#include "mongo/s/commands/cluster_command_test_fixture.h"
namespace mongo {
namespace {
class ClusterFindTest : public ClusterCommandTestFixture {
protected:
const BSONObj kFindCmdScatterGather = BSON("find"
<< "coll");
const BSONObj kFindCmdTargeted = BSON("find"
<< "coll"
<< "filter" << BSON("_id" << 0));
// The index of the shard expected to receive the response is used to prevent different shards
// from returning documents with the same shard key. This is expected to be 0 for queries
// targeting one shard.
void expectReturnsSuccess(int shardIndex) override {
onCommandForPoolExecutor([&](const executor::RemoteCommandRequest& request) {
ASSERT_EQ(kNss.coll(), request.cmdObj.firstElement().valueStringData());
std::vector<BSONObj> batch = {BSON("_id" << shardIndex)};
CursorResponse cursorResponse(kNss, CursorId(0), batch);
BSONObjBuilder bob;
bob.appendElementsUnique(
cursorResponse.toBSON(CursorResponse::ResponseType::InitialResponse));
appendTxnResponseMetadata(bob);
return bob.obj();
});
}
void expectInspectRequest(int shardIndex, InspectionCallback cb) override {
onCommandForPoolExecutor([&](const executor::RemoteCommandRequest& request) {
ASSERT_EQ(kNss.coll(), request.cmdObj.firstElement().valueStringData());
cb(request);
std::vector<BSONObj> batch = {BSON("_id" << shardIndex)};
CursorResponse cursorResponse(kNss, CursorId(0), batch);
BSONObjBuilder bob;
bob.appendElementsUnique(
cursorResponse.toBSON(CursorResponse::ResponseType::InitialResponse));
appendTxnResponseMetadata(bob);
return bob.obj();
});
}
};
TEST_F(ClusterFindTest, NoErrors) {
testNoErrors(kFindCmdTargeted, kFindCmdScatterGather);
}
TEST_F(ClusterFindTest, RetryOnSnapshotError) {
testRetryOnSnapshotError(kFindCmdTargeted, kFindCmdScatterGather);
}
TEST_F(ClusterFindTest, MaxRetriesSnapshotErrors) {
testMaxRetriesSnapshotErrors(kFindCmdTargeted, kFindCmdScatterGather);
}
TEST_F(ClusterFindTest, AttachesAtClusterTimeForSnapshotReadConcern) {
testAttachesAtClusterTimeForSnapshotReadConcern(kFindCmdTargeted, kFindCmdScatterGather);
}
TEST_F(ClusterFindTest, SnapshotReadConcernWithAfterClusterTime) {
testSnapshotReadConcernWithAfterClusterTime(kFindCmdTargeted, kFindCmdScatterGather);
}
} // namespace
} // namespace mongo
| 41 | 98 | 0.69348 | benety |
8d10dad0aa7ca5f8ea463a773574078df5b9e9ad | 5,235 | hpp | C++ | include/SSVOpenHexagon/Global/Config.hpp | AlphaPromethium/SSVOpenHexagon | f9e15e9397d6188e3dced97da97d5c6e2de4186a | [
"AFL-3.0"
] | null | null | null | include/SSVOpenHexagon/Global/Config.hpp | AlphaPromethium/SSVOpenHexagon | f9e15e9397d6188e3dced97da97d5c6e2de4186a | [
"AFL-3.0"
] | null | null | null | include/SSVOpenHexagon/Global/Config.hpp | AlphaPromethium/SSVOpenHexagon | f9e15e9397d6188e3dced97da97d5c6e2de4186a | [
"AFL-3.0"
] | null | null | null | // Copyright (c) 2013-2020 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
#pragma once
#include <vector>
#include <string>
namespace ssvs
{
class GameWindow;
} // namespace ssvs
namespace ssvs::Input
{
class Trigger;
} // namespace ssvs::Input
namespace hg::Config
{
void loadConfig(const std::vector<std::string>& mOverridesIds);
void saveConfig();
[[nodiscard]] bool isEligibleForScore();
void recalculateSizes();
void setFullscreen(ssvs::GameWindow& mWindow, bool mFullscreen);
void refreshWindowSize(unsigned int mWidth, unsigned int mHeight);
void setCurrentResolution(
ssvs::GameWindow& mWindow, unsigned int mWidth, unsigned int mHeight);
void setCurrentResolutionAuto(ssvs::GameWindow& mWindow);
void setVsync(ssvs::GameWindow& mWindow, bool mValue);
void setLimitFPS(ssvs::GameWindow& mWindow, bool mValue);
void setMaxFPS(ssvs::GameWindow& mWindow, unsigned int mValue);
void setTimerStatic(ssvs::GameWindow& mWindow, bool mValue);
void setAntialiasingLevel(ssvs::GameWindow& mWindow, unsigned int mValue);
void setOnline(bool mOnline);
void setOfficial(bool mOfficial);
void setDebug(bool mDebug);
void setNoRotation(bool mNoRotation);
void setNoBackground(bool mNoBackground);
void setBlackAndWhite(bool mBlackAndWhite);
void setNoSound(bool mNoSound);
void setNoMusic(bool mNoMusic);
void setPulse(bool mPulse);
void set3D(bool m3D);
void setInvincible(bool mInvincible);
void setAutoRestart(bool mAutoRestart);
void setSoundVolume(float mVolume);
void setMusicVolume(float mVolume);
void setFlash(bool mFlash);
void setMusicSpeedDMSync(bool mValue);
void setShowFPS(bool mValue);
void setServerLocal(bool mValue);
void setServerVerbose(bool mValue);
void setMouseVisible(bool mValue);
void setMusicSpeedMult(float mValue);
void setDrawTextOutlines(bool mX);
void setDarkenUnevenBackgroundChunk(bool mX);
void setRotateToStart(bool mX);
void setJoystickDeadzone(float mX);
void setTextPadding(float mX);
void setTextScaling(float mX);
void setTimescale(float mX);
void setShowKeyIcons(bool mX);
void setKeyIconsScale(float mX);
void setFirstTimePlaying(bool mX);
[[nodiscard]] bool getOnline();
[[nodiscard]] bool getOfficial();
[[nodiscard]] std::string getUneligibilityReason();
[[nodiscard]] float getSizeX();
[[nodiscard]] float getSizeY();
[[nodiscard]] float getSpawnDistance();
[[nodiscard]] float getZoomFactor();
[[nodiscard]] int getPixelMultiplier();
[[nodiscard]] float getPlayerSpeed();
[[nodiscard]] float getPlayerFocusSpeed();
[[nodiscard]] float getPlayerSize();
[[nodiscard]] bool getNoRotation();
[[nodiscard]] bool getNoBackground();
[[nodiscard]] bool getBlackAndWhite();
[[nodiscard]] bool getNoSound();
[[nodiscard]] bool getNoMusic();
[[nodiscard]] float getSoundVolume();
[[nodiscard]] float getMusicVolume();
[[nodiscard]] bool getLimitFPS();
[[nodiscard]] bool getVsync();
[[nodiscard]] bool getAutoZoomFactor();
[[nodiscard]] bool getFullscreen();
[[nodiscard]] float getVersion();
[[nodiscard]] const char* getVersionString();
[[nodiscard]] bool getWindowedAutoResolution();
[[nodiscard]] bool getFullscreenAutoResolution();
[[nodiscard]] unsigned int getFullscreenWidth();
[[nodiscard]] unsigned int getFullscreenHeight();
[[nodiscard]] unsigned int getWindowedWidth();
[[nodiscard]] unsigned int getWindowedHeight();
[[nodiscard]] unsigned int getWidth();
[[nodiscard]] unsigned int getHeight();
[[nodiscard]] bool getShowMessages();
[[nodiscard]] bool getRotateToStart();
[[nodiscard]] bool getDebug();
[[nodiscard]] bool getPulse();
[[nodiscard]] bool getBeatPulse();
[[nodiscard]] bool getInvincible();
[[nodiscard]] bool get3D();
[[nodiscard]] unsigned int get3DMaxDepth();
[[nodiscard]] float get3DMultiplier();
[[nodiscard]] bool getAutoRestart();
[[nodiscard]] bool getFlash();
[[nodiscard]] bool getShowTrackedVariables();
[[nodiscard]] bool getMusicSpeedDMSync();
[[nodiscard]] unsigned int getMaxFPS();
[[nodiscard]] bool getShowFPS();
[[nodiscard]] bool getTimerStatic();
[[nodiscard]] unsigned int getAntialiasingLevel();
[[nodiscard]] bool getServerLocal();
[[nodiscard]] bool getServerVerbose();
[[nodiscard]] bool getMouseVisible();
[[nodiscard]] float getMusicSpeedMult();
[[nodiscard]] bool getDrawTextOutlines();
[[nodiscard]] bool getDarkenUnevenBackgroundChunk();
[[nodiscard]] float getJoystickDeadzone();
[[nodiscard]] float getTextPadding();
[[nodiscard]] float getTextScaling();
[[nodiscard]] float getTimescale();
[[nodiscard]] bool getShowKeyIcons();
[[nodiscard]] float getKeyIconsScale();
[[nodiscard]] bool getFirstTimePlaying();
[[nodiscard]] ssvs::Input::Trigger getTriggerRotateCCW();
[[nodiscard]] ssvs::Input::Trigger getTriggerRotateCW();
[[nodiscard]] ssvs::Input::Trigger getTriggerFocus();
[[nodiscard]] ssvs::Input::Trigger getTriggerExit();
[[nodiscard]] ssvs::Input::Trigger getTriggerForceRestart();
[[nodiscard]] ssvs::Input::Trigger getTriggerRestart();
[[nodiscard]] ssvs::Input::Trigger getTriggerReplay();
[[nodiscard]] ssvs::Input::Trigger getTriggerScreenshot();
[[nodiscard]] ssvs::Input::Trigger getTriggerSwap();
[[nodiscard]] ssvs::Input::Trigger getTriggerUp();
[[nodiscard]] ssvs::Input::Trigger getTriggerDown();
} // namespace hg::Config
| 34.668874 | 74 | 0.762751 | AlphaPromethium |
8d12a21817ad54e2579dfea9625d052a3cbea77d | 6,479 | hpp | C++ | arbor/include/arbor/event_generator.hpp | Tadinu/arbor | 981904a542b96f73a6554b3f63049ea4c2de8cfc | [
"BSD-3-Clause"
] | null | null | null | arbor/include/arbor/event_generator.hpp | Tadinu/arbor | 981904a542b96f73a6554b3f63049ea4c2de8cfc | [
"BSD-3-Clause"
] | null | null | null | arbor/include/arbor/event_generator.hpp | Tadinu/arbor | 981904a542b96f73a6554b3f63049ea4c2de8cfc | [
"BSD-3-Clause"
] | 1 | 2021-07-06T11:07:13.000Z | 2021-07-06T11:07:13.000Z | #pragma once
#include <algorithm>
#include <cstdint>
#include <memory>
#include <random>
#include <type_traits>
#include <arbor/assert.hpp>
#include <arbor/common_types.hpp>
#include <arbor/generic_event.hpp>
#include <arbor/spike_event.hpp>
#include <arbor/schedule.hpp>
namespace arb {
// An `event_generator` generates a sequence of events to be delivered to a cell.
// The sequence of events is always in ascending order, i.e. each event will be
// greater than the event that proceded it, where events are ordered by:
// - delivery time;
// - then target id for events with the same delivery time;
// - then weight for events with the same delivery time and target.
//
// An `event_generator` supports two operations:
//
// `void event_generator::reset()`
//
// Reset generator state.
//
// `event_seq event_generator::events(time_type to, time_type from)`
//
// Provide a non-owning view on to the events in the time interval
// [to, from).
//
// The `event_seq` type is a pair of `spike_event` pointers that
// provide a view onto an internally-maintained contiguous sequence
// of generated spike event objects. This view is valid only for
// the lifetime of the generator, and is invalidated upon a call
// to `reset` or another call to `events`.
//
// Calls to the `events` method must be monotonic in time: without an
// intervening call to `reset`, two successive calls `events(t0, t1)`
// and `events(t2, t3)` to the same event generator must satisfy
// 0 ≤ t0 ≤ t1 ≤ t2 ≤ t3.
//
// `event_generator` objects have value semantics, and use type erasure
// to wrap implementation details. An `event_generator` can be constructed
// from an onbject of an implementation class Impl that is copy-constructible
// and otherwise provides `reset` and `events` methods following the
// API described above.
//
// Some pre-defined event generators are included:
// - `empty_generator`: produces no events
// - `schedule_generator`: events to a fixed target according to a time schedule
using event_seq = std::pair<const spike_event*, const spike_event*>;
// The simplest possible generator that generates no events.
// Declared ahead of event_generator so that it can be used as the default
// generator.
struct empty_generator {
void reset() {}
event_seq events(time_type, time_type) {
return {nullptr, nullptr};
}
};
class event_generator {
public:
event_generator(): event_generator(empty_generator()) {}
template <typename Impl, std::enable_if_t<!std::is_same<std::decay_t<Impl>, event_generator>::value, int> = 0>
event_generator(Impl&& impl):
impl_(new wrap<Impl>(std::forward<Impl>(impl)))
{}
event_generator(event_generator&& other) = default;
event_generator& operator=(event_generator&& other) = default;
event_generator(const event_generator& other):
impl_(other.impl_->clone())
{}
event_generator& operator=(const event_generator& other) {
impl_ = other.impl_->clone();
return *this;
}
void reset() {
impl_->reset();
}
event_seq events(time_type t0, time_type t1) {
return impl_->events(t0, t1);
}
private:
struct interface {
virtual void reset() = 0;
virtual event_seq events(time_type, time_type) = 0;
virtual std::unique_ptr<interface> clone() = 0;
virtual ~interface() {}
};
std::unique_ptr<interface> impl_;
template <typename Impl>
struct wrap: interface {
explicit wrap(const Impl& impl): wrapped(impl) {}
explicit wrap(Impl&& impl): wrapped(std::move(impl)) {}
event_seq events(time_type t0, time_type t1) override {
return wrapped.events(t0, t1);
}
void reset() override {
wrapped.reset();
}
std::unique_ptr<interface> clone() override {
return std::unique_ptr<interface>(new wrap<Impl>(wrapped));
}
Impl wrapped;
};
};
// Convenience routines for making schedule_generator:
// Generate events with a fixed target and weight according to
// a provided time schedule.
struct schedule_generator {
schedule_generator(cell_member_type target, float weight, schedule sched):
target_(target), weight_(weight), sched_(std::move(sched))
{}
void reset() {
sched_.reset();
}
event_seq events(time_type t0, time_type t1) {
auto ts = sched_.events(t0, t1);
events_.clear();
events_.reserve(ts.second-ts.first);
for (auto i = ts.first; i!=ts.second; ++i) {
events_.push_back(spike_event{target_, *i, weight_});
}
return {events_.data(), events_.data()+events_.size()};
}
private:
pse_vector events_;
cell_member_type target_;
float weight_;
schedule sched_;
};
// Generate events at integer multiples of dt that lie between tstart and tstop.
inline event_generator regular_generator(
cell_member_type target,
float weight,
time_type tstart,
time_type dt,
time_type tstop=terminal_time)
{
return schedule_generator(target, weight, regular_schedule(tstart, dt, tstop));
}
template <typename RNG>
inline event_generator poisson_generator(
cell_member_type target,
float weight,
time_type tstart,
time_type rate_kHz,
const RNG& rng)
{
return schedule_generator(target, weight, poisson_schedule(tstart, rate_kHz, rng));
}
// Generate events from a predefined sorted event sequence.
struct explicit_generator {
explicit_generator() = default;
explicit_generator(const explicit_generator&) = default;
explicit_generator(explicit_generator&&) = default;
template <typename Seq>
explicit_generator(const Seq& events):
start_index_(0)
{
using std::begin;
using std::end;
events_ = pse_vector(begin(events), end(events));
arb_assert(std::is_sorted(events_.begin(), events_.end()));
}
void reset() {
start_index_ = 0;
}
event_seq events(time_type t0, time_type t1) {
const spike_event* lb = events_.data()+start_index_;
const spike_event* ub = events_.data()+events_.size();
lb = std::lower_bound(lb, ub, t0, event_time_less{});
ub = std::lower_bound(lb, ub, t1, event_time_less{});
start_index_ = ub-events_.data();
return {lb, ub};
}
private:
pse_vector events_;
std::size_t start_index_ = 0;
};
} // namespace arb
| 28.416667 | 114 | 0.674332 | Tadinu |
8d148b40414b0e2292a3fc9ef685f0d63a0d7cfc | 9,383 | hpp | C++ | far/uuids.far.dialogs.hpp | skipik/FarManager | 0080534fd8b8246b31f9587d8e15fe313849e801 | [
"BSD-3-Clause"
] | null | null | null | far/uuids.far.dialogs.hpp | skipik/FarManager | 0080534fd8b8246b31f9587d8e15fe313849e801 | [
"BSD-3-Clause"
] | null | null | null | far/uuids.far.dialogs.hpp | skipik/FarManager | 0080534fd8b8246b31f9587d8e15fe313849e801 | [
"BSD-3-Clause"
] | null | null | null | #ifndef UUIDS_FAR_DIALOGS_HPP_760BACF0_E0D8_4C67_A732_5C075A1CC176
#define UUIDS_FAR_DIALOGS_HPP_760BACF0_E0D8_4C67_A732_5C075A1CC176
#pragma once
/*
uuids.far.dialogs.hpp
UUIDs of common dialogs
*/
/*
Copyright © 2010 Far Group
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
// Internal:
// Platform:
// Common:
#include "common/uuid.hpp"
// External:
//----------------------------------------------------------------------------
namespace uuids::far::dialogs
{
constexpr inline auto
FindFileId = "8C9EAD29-910F-4B24-A669-EDAFBA6ED964"_uuid,
FindFileResultId = "536754EB-C2D1-4626-933F-A25D1E1D110A"_uuid,
CopyOverwriteId = "9FBCB7E1-ACA2-475D-B40D-0F7365B632FF"_uuid,
FileOpenCreateId = "1D07CEE2-8F4F-480A-BE93-069B4FF59A2B"_uuid,
FileSaveAsId = "9162F965-78B8-4476-98AC-D699E5B6AFE7"_uuid,
EditorSavedROId = "3F9311F5-3CA3-4169-A41C-89C76B3A8C1D"_uuid,
EditorSaveF6DeletedId = "85532BD5-1583-456D-A810-41AB345995A9"_uuid,
EditorSaveExitDeletedId = "2D71DCCE-F0B8-4E29-A3A9-1F6D8C1128C2"_uuid,
EditorAskOverwriteId = "4109C8B3-760D-4011-B1D5-14C36763B23E"_uuid,
EditorOpenRSHId = "D8AA706F-DA7E-4BBF-AB78-6B7BDB49E006"_uuid,
EditAskSaveExtId = "40A699F1-BBDD-4E21-A137-97FFF798B0C8"_uuid,
EditAskSaveId = "F776FEC0-50F7-4E7E-BDA6-2A63F84A957B"_uuid,
MakeFolderId = "FAD00DBE-3FFF-4095-9232-E1CC70C67737"_uuid,
FileAttrDlgId = "80695D20-1085-44D6-8061-F3C41AB5569C"_uuid,
CopyReadOnlyId = "879A8DE6-3108-4BEB-80DE-6F264991CE98"_uuid,
CopyFilesId = "FCEF11C4-5490-451D-8B4A-62FA03F52759"_uuid,
CopyCurrentOnlyFileId = "502D00DF-EE31-41CF-9028-442D2E352990"_uuid,
MoveFilesId = "431A2F37-AC01-4ECD-BB6F-8CDE584E5A03"_uuid,
MoveCurrentOnlyFileId = "89664EF4-BB8C-4932-A8C0-59CAFD937ABA"_uuid,
HardSymLinkId = "5EB266F4-980D-46AF-B3D2-2C50E64BCA81"_uuid,
PluginsMenuId = "937F0B1C-7690-4F85-8469-AA935517F202"_uuid,
EditorReloadId = "AFDAD388-494C-41E8-BAC6-BBE9115E1CC0"_uuid,
FarAskQuitId = "72E6E6D8-0BC6-4265-B9C4-C8DB712136AF"_uuid,
AdvancedConfigId = "A204FF09-07FA-478C-98C9-E56F61377BDE"_uuid,
FolderShortcutsId = "4CD742BC-295F-4AFA-A158-7AA05A16BEA1"_uuid,
FolderShortcutsDlgId = "DC8D98AC-475C-4F37-AB1D-45765EF06269"_uuid,
FolderShortcutsMoreId = "601DD149-92FA-4601-B489-74C981BC8E38"_uuid,
ScreensSwitchId = "72EB948A-5F1D-4481-9A91-A4BFD869D127"_uuid,
SelectSortModeId = "B8B6E1DA-4221-47D2-AB2E-9EC67D0DC1E3"_uuid,
HistoryCmdId = "880968A6-6258-43E0-9BDC-F2B8678EC278"_uuid,
HistoryFolderId = "FC3384A8-6608-4C9B-8D6B-EE105F4C5A54"_uuid,
HistoryEditViewId = "E770E044-23A8-4F4D-B268-0E602B98CCF9"_uuid,
PanelViewModesId = "B56D5C08-0336-418B-A2A7-CF0C80F93ACC"_uuid,
PanelViewModesEditId = "98B75500-4A97-4299-BFAD-C3E349BF3674"_uuid,
CodePagesMenuId = "78A4A4E3-C2F0-40BD-9AA7-EAAC11836631"_uuid,
EditorReplaceId = "8BCCDFFD-3B34-49F8-87CD-F4D885B75873"_uuid,
EditorSearchId = "5D3CBA90-F32D-433C-B016-9BB4AF96FACC"_uuid,
HelpSearchId = "F63B558F-9185-46BA-8701-D143B8F62658"_uuid,
FiltersMenuId = "5B87B32E-494A-4982-AF55-DAFFCD251383"_uuid,
FiltersConfigId = "EDDB9286-3B08-4593-8F7F-E5925A3A0FF8"_uuid,
HighlightMenuId = "D0422DF0-AAF5-46E0-B98B-1776B427E70D"_uuid,
HighlightConfigId = "51B6E342-B499-464D-978C-029F18ECCE59"_uuid,
PluginsConfigMenuId = "B4C242E7-AA8E-4449-B0C3-BD8D9FA11AED"_uuid,
ChangeDiskMenuId = "252CE4A3-C415-4B19-956B-83E2FDD85960"_uuid,
FileAssocMenuId = "F6D2437C-FEDC-4075-AA56-275666FC8979"_uuid,
SelectAssocMenuId = "D2BCB5A5-6B82-4EB5-B321-1AE7607A6236"_uuid,
FileAssocModifyId = "6F245B1A-47D9-41A6-AF3F-FA2C8DBEEBD0"_uuid,
EditorSwitchUnicodeCPDisabledId = "15568DC5-4D6B-4C60-B43D-2040EE39871A"_uuid,
GetNameAndPasswordId = "CD2AC546-9E4F-4445-A258-AB5F7A7800E0"_uuid,
SelectFromEditHistoryId = "4406C688-209F-4378-8B7B-465BF16205FF"_uuid,
EditorReloadModalId = "D6F557E8-7E89-4895-BD75-4D3F2C30E382"_uuid,
EditorCanNotEditDirectoryId = "CCA2C4D0-8705-4FA1-9B10-C9E3C8F37A65"_uuid,
EditorFileLongId = "E3AFCD2D-BDE5-4E92-82B6-87C6A7B78FB6"_uuid,
EditorFileGetSizeErrorId = "6AD4B317-C1ED-44C8-A76A-9146CA8AF984"_uuid,
DisconnectDriveId = "A1BDBEB1-2911-41FF-BC08-EEBC44040B50"_uuid,
ChangeDriveModeId = "F87F9351-6A80-4872-BEEE-96EF80C809FB"_uuid,
SUBSTDisconnectDriveId = "75554EEB-A3A7-45FD-9795-4A85887A75A0"_uuid,
VHDDisconnectDriveId = "629A8CA6-25C6-498C-B3DD-0E18D1CC0BCD"_uuid,
EditorFindAllListId = "9BD3E306-EFB8-4113-8405-E7BADE8F0A59"_uuid,
BadEditorCodePageId = "4811039D-03A3-4F15-8D7A-8EBC4BCC97F9"_uuid,
UserMenuUserInputId = "D2750B57-D3E6-42F4-8137-231C50DDC6E4"_uuid,
DescribeFileId = "D8AF7A38-8357-44A5-A44B-A595CF707549"_uuid,
SelectDialogId = "29C03C36-9C50-4F78-AB99-F5DC1A9C67CD"_uuid,
UnSelectDialogId = "34614DDB-2A22-4EA9-BD4A-2DC075643F1B"_uuid,
SUBSTDisconnectDriveError1Id = "FF18299E-1881-42FA-AF7E-AC05D99F269C"_uuid,
SUBSTDisconnectDriveError2Id = "43B0FFC2-70BE-4289-91E6-FE9A3D54311B"_uuid,
EjectHotPlugMediaErrorId = "D6DC3621-877E-4BE2-80CC-BDB2864CE038"_uuid,
RemoteDisconnectDriveError2Id = "F06953B8-25AA-4FC0-9899-422FC1D49F7A"_uuid,
RemoteDisconnectDriveError1Id = "C9439386-9544-49BF-954B-6BEEDE7F1BD0"_uuid,
VHDDisconnectDriveErrorId = "B890E6B0-05A9-4ED8-A4C3-BBC4D29DA3BE"_uuid,
ChangeDriveCannotReadDiskErrorId = "F3D46DC3-380B-4264-8BF8-10B05B897A5E"_uuid,
ApplyCommandId = "044EF83E-8146-41B2-97F0-404C2F4C7B69"_uuid,
DeleteFileFolderId = "6EF09401-6FE1-495A-8539-61B0F761408E"_uuid,
DeleteRecycleId = "85A5F779-A881-4B0B-ACEE-6D05653AE0EB"_uuid,
DeleteWipeId = "9C054039-5C7E-4B04-96CD-3585228C916F"_uuid,
DeleteLinkId = "B1099BC3-14BD-4B22-87AC-44770D4189A3"_uuid,
DeleteFolderId = "4E714029-11BF-476F-9B17-9E47AA0DA8EA"_uuid,
WipeFolderId = "E23BB390-036E-4A30-A9E6-DC621617C7F5"_uuid,
DeleteFolderRecycleId = "A318CBDC-DBA9-49E9-A248-E6A9FF8EC849"_uuid,
DeleteAskWipeROId = "6792A975-57C5-4110-8129-2D8045120964"_uuid,
DeleteAskDeleteROId = "8D4E84B3-08F6-47DF-8C40-7130CD31D0E6"_uuid,
WipeHardLinkId = "5297DDFE-0A37-4465-85EF-CBF9006D65C6"_uuid,
RecycleFolderConfirmDeleteLinkId = "26A7AB9F-51F5-40F7-9061-1AE6E2FBD00A"_uuid,
CannotRecycleFileId = "52CEB5A5-06FA-43DD-B37C-239C02652C99"_uuid,
CannotRecycleFolderId = "BBD9B7AE-9F6B-4444-89BF-C6124A5A83A4"_uuid,
AskInsertMenuOrCommandId = "57209AD5-51F6-4257-BAB6-837462BBCE74"_uuid,
EditUserMenuId = "73BC6E3E-4CC3-4FE3-8709-545FF72B49B4"_uuid,
PluginInformationId = "FC4FD19A-43D2-4987-AC31-0F7A94901692"_uuid,
EditMaskGroupId = "C57682CA-8DC9-4D62-B3F5-9ED37CD207B9"_uuid,
ViewerSearchId = "03B6C098-A3D6-4DFB-AED4-EB32D711D9AA"_uuid;
}
// TODO: Use fully qualified names everywhere
inline namespace uuids_inline
{
using namespace uuids::far::dialogs;
}
#endif // UUIDS_FAR_DIALOGS_HPP_760BACF0_E0D8_4C67_A732_5C075A1CC176
| 62.553333 | 81 | 0.688905 | skipik |
8d14c8506388bf847a1dd3203ede096ac4aa2f20 | 6,671 | cc | C++ | server/core/maxpasswd.cc | Daniel-Xu/MaxScale | 35d12c0c9b75c4571dbbeb983c740de098661de6 | [
"BSD-3-Clause"
] | null | null | null | server/core/maxpasswd.cc | Daniel-Xu/MaxScale | 35d12c0c9b75c4571dbbeb983c740de098661de6 | [
"BSD-3-Clause"
] | null | null | null | server/core/maxpasswd.cc | Daniel-Xu/MaxScale | 35d12c0c9b75c4571dbbeb983c740de098661de6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-04-28
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
/**
* @file maxpasswd.c - Implementation of pasword encoding
*/
#include <maxscale/ccdefs.hh>
#include <cstdio>
#include <getopt.h>
#include <termios.h>
#include <unistd.h>
#include <maxbase/log.hh>
#include <maxscale/paths.hh>
#include <iostream>
#include "internal/secrets.hh"
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::string;
struct option options[] =
{
{"help", no_argument, nullptr, 'h'},
{"decrypt", no_argument, nullptr, 'd'},
{"interactive", no_argument, nullptr, 'i'},
{nullptr, 0, nullptr, 0 }
};
void print_usage(const char* executable, const char* directory)
{
const char msg[] =
R"(Usage: %s [-h|--help] [-i|--interactive] [-d|--decrypt] [path] password
Encrypt a MaxScale plaintext password using the encryption key in the key file
'%s'. The key file may be generated using the 'maxkeys'-utility.
-h, --help Display this help.
-d, --decrypt Decrypt an encrypted password instead.
-i, --interactive - If maxpasswd is reading from a pipe, it will read a line and
use that as the password.
- If maxpasswd is connected to a terminal console, it will prompt
for the password.
If '-i' is specified, a single argument is assumed to be the path
and two arguments is treated like an error.
path The key file directory (default: '%s')
password The password to encrypt or decrypt
)";
printf(msg, executable, SECRETS_FILENAME, directory);
}
bool read_password(string* pPassword)
{
bool rv = false;
string password;
if (isatty(STDIN_FILENO))
{
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
bool echo = (tty.c_lflag & ECHO);
if (echo)
{
tty.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
cout << "Enter password : " << flush;
string s1;
std::getline(std::cin, s1);
cout << endl;
cout << "Repeat password: " << flush;
string s2;
std::getline(std::cin, s2);
cout << endl;
if (echo)
{
tty.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
if (s1 == s2)
{
password = s1;
rv = true;
}
else
{
cout << "Passwords are not identical." << endl;
}
}
else
{
std::getline(std::cin, password);
rv = true;
}
if (rv)
{
*pPassword = password;
}
return rv;
}
int main(int argc, char** argv)
{
std::ios::sync_with_stdio();
mxb::Log log(MXB_LOG_TARGET_STDOUT);
const char* default_directory = mxs::datadir();
enum class Mode
{
ENCRYPT,
DECRYPT
};
auto mode = Mode::ENCRYPT;
bool interactive = false;
int c;
while ((c = getopt_long(argc, argv, "hdi", options, NULL)) != -1)
{
switch (c)
{
case 'h':
print_usage(argv[0], default_directory);
return EXIT_SUCCESS;
case 'd':
mode = Mode::DECRYPT;
break;
case 'i':
interactive = true;
break;
default:
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
}
string input;
string path = default_directory;
switch (argc - optind)
{
case 2:
// Two args provided.
path = argv[optind];
if (!interactive)
{
input = argv[optind + 1];
}
else
{
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
break;
case 1:
// One arg provided.
if (!interactive)
{
input = argv[optind];
}
else
{
path = argv[optind];
}
break;
case 0:
if (!interactive)
{
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
break;
default:
print_usage(argv[0], default_directory);
return EXIT_FAILURE;
}
if (interactive)
{
if (!read_password(&input))
{
return EXIT_FAILURE;
}
}
int rval = EXIT_FAILURE;
string filepath = path;
filepath.append("/").append(SECRETS_FILENAME);
auto keydata = secrets_readkeys(filepath);
if (keydata.ok)
{
bool encrypting = (mode == Mode::ENCRYPT);
bool new_mode = keydata.iv.empty(); // false -> constant IV from file
if (keydata.key.empty())
{
printf("Password encryption key file '%s' not found, cannot %s password.\n",
filepath.c_str(), encrypting ? "encrypt" : "decrypt");
}
else if (encrypting)
{
string encrypted = new_mode ? encrypt_password(keydata.key, input) :
encrypt_password_old(keydata.key, keydata.iv, input);
if (!encrypted.empty())
{
printf("%s\n", encrypted.c_str());
rval = EXIT_SUCCESS;
}
else
{
printf("Password encryption failed.\n");
}
}
else
{
auto is_hex = std::all_of(input.begin(), input.end(), isxdigit);
if (is_hex && input.length() % 2 == 0)
{
string decrypted = new_mode ? decrypt_password(keydata.key, input) :
decrypt_password_old(keydata.key, keydata.iv, input);
if (!decrypted.empty())
{
printf("%s\n", decrypted.c_str());
rval = EXIT_SUCCESS;
}
else
{
printf("Password decryption failed.\n");
}
}
else
{
printf("Input is not a valid hex-encoded encrypted password.\n");
}
}
}
else
{
printf("Could not read encryption key file '%s'.\n", filepath.c_str());
}
return rval;
}
| 24.258182 | 88 | 0.519412 | Daniel-Xu |
8d150c8130b9551bbde55e3bf8bcddd78a2f58f4 | 14,612 | cc | C++ | content/renderer/media/webrtc/webrtc_video_capturer_adapter.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/media/webrtc/webrtc_video_capturer_adapter.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/media/webrtc/webrtc_video_capturer_adapter.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.000Z | // Copyright 2014 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 "content/renderer/media/webrtc/webrtc_video_capturer_adapter.h"
#include "base/bind.h"
#include "base/memory/aligned_memory.h"
#include "base/trace_event/trace_event.h"
#include "media/base/video_frame.h"
#include "media/base/video_frame_pool.h"
#include "third_party/libjingle/source/talk/media/base/videoframe.h"
#include "third_party/libjingle/source/talk/media/base/videoframefactory.h"
#include "third_party/libjingle/source/talk/media/webrtc/webrtcvideoframe.h"
#include "third_party/libyuv/include/libyuv/convert_from.h"
#include "third_party/libyuv/include/libyuv/scale.h"
namespace content {
namespace {
// Empty method used for keeping a reference to the original media::VideoFrame.
// The reference to |frame| is kept in the closure that calls this method.
void ReleaseOriginalFrame(const scoped_refptr<media::VideoFrame>& frame) {
}
// Thin map between an existing media::VideoFrame and cricket::VideoFrame to
// avoid premature deep copies.
// This implementation is only safe to use in a const context and should never
// be written to.
class VideoFrameWrapper : public cricket::VideoFrame {
public:
// Create a shallow cricket::VideoFrame wrapper around the
// media::VideoFrame. The caller has ownership of the returned frame.
VideoFrameWrapper(const scoped_refptr<media::VideoFrame>& frame,
int64 elapsed_time)
: frame_(frame), elapsed_time_(elapsed_time) {}
VideoFrame* Copy() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return new VideoFrameWrapper(media::VideoFrame::WrapVideoFrame(
frame_,
frame_->visible_rect(),
frame_->natural_size(),
base::Bind(&ReleaseOriginalFrame, frame_)),
elapsed_time_);
}
size_t GetWidth() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return static_cast<size_t>(frame_->visible_rect().width());
}
size_t GetHeight() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return static_cast<size_t>(frame_->visible_rect().height());
}
const uint8* GetYPlane() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->visible_data(media::VideoFrame::kYPlane);
}
const uint8* GetUPlane() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->visible_data(media::VideoFrame::kUPlane);
}
const uint8* GetVPlane() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->visible_data(media::VideoFrame::kVPlane);
}
uint8* GetYPlane() override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->visible_data(media::VideoFrame::kYPlane);
}
uint8* GetUPlane() override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->visible_data(media::VideoFrame::kUPlane);
}
uint8* GetVPlane() override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->visible_data(media::VideoFrame::kVPlane);
}
int32 GetYPitch() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->stride(media::VideoFrame::kYPlane);
}
int32 GetUPitch() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->stride(media::VideoFrame::kUPlane);
}
int32 GetVPitch() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->stride(media::VideoFrame::kVPlane);
}
void* GetNativeHandle() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return NULL;
}
size_t GetPixelWidth() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return 1;
}
size_t GetPixelHeight() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return 1;
}
int64 GetElapsedTime() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return elapsed_time_;
}
int64 GetTimeStamp() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return frame_->timestamp().InMicroseconds() *
base::Time::kNanosecondsPerMicrosecond;
}
void SetElapsedTime(int64 elapsed_time) override {
DCHECK(thread_checker_.CalledOnValidThread());
elapsed_time_ = elapsed_time;
}
void SetTimeStamp(int64 time_stamp) override {
DCHECK(thread_checker_.CalledOnValidThread());
// Round to closest microsecond.
frame_->set_timestamp(base::TimeDelta::FromMicroseconds(
(time_stamp + base::Time::kNanosecondsPerMicrosecond / 2) /
base::Time::kNanosecondsPerMicrosecond));
}
int GetRotation() const override {
DCHECK(thread_checker_.CalledOnValidThread());
return 0;
}
// The rest of the public methods are NOTIMPLEMENTED.
bool InitToBlack(int w,
int h,
size_t pixel_width,
size_t pixel_height,
int64 elapsed_time,
int64 time_stamp) override {
NOTIMPLEMENTED();
return false;
}
bool Reset(uint32 fourcc,
int w,
int h,
int dw,
int dh,
uint8* sample,
size_t sample_size,
size_t pixel_width,
size_t pixel_height,
int64 elapsed_time,
int64 time_stamp,
int rotation) override {
NOTIMPLEMENTED();
return false;
}
bool MakeExclusive() override {
NOTIMPLEMENTED();
return false;
}
size_t CopyToBuffer(uint8* buffer, size_t size) const override {
NOTIMPLEMENTED();
return 0;
}
protected:
// TODO(magjed): Refactor as a static method in WebRtcVideoFrame.
VideoFrame* CreateEmptyFrame(int w,
int h,
size_t pixel_width,
size_t pixel_height,
int64 elapsed_time,
int64 time_stamp) const override {
DCHECK(thread_checker_.CalledOnValidThread());
VideoFrame* frame = new cricket::WebRtcVideoFrame();
frame->InitToBlack(
w, h, pixel_width, pixel_height, elapsed_time, time_stamp);
return frame;
}
private:
scoped_refptr<media::VideoFrame> frame_;
int64 elapsed_time_;
base::ThreadChecker thread_checker_;
};
} // anonymous namespace
// A cricket::VideoFrameFactory for media::VideoFrame. The purpose of this
// class is to avoid a premature frame copy. A media::VideoFrame is injected
// with SetFrame, and converted into a cricket::VideoFrame with
// CreateAliasedFrame. SetFrame should be called before CreateAliasedFrame
// for every frame.
class WebRtcVideoCapturerAdapter::MediaVideoFrameFactory
: public cricket::VideoFrameFactory {
public:
void SetFrame(const scoped_refptr<media::VideoFrame>& frame,
int64_t elapsed_time) {
DCHECK(frame.get());
// Create a CapturedFrame that only contains header information, not the
// actual pixel data.
captured_frame_.width = frame->natural_size().width();
captured_frame_.height = frame->natural_size().height();
captured_frame_.elapsed_time = elapsed_time;
captured_frame_.time_stamp = frame->timestamp().InMicroseconds() *
base::Time::kNanosecondsPerMicrosecond;
captured_frame_.pixel_height = 1;
captured_frame_.pixel_width = 1;
captured_frame_.rotation = 0;
captured_frame_.data = NULL;
captured_frame_.data_size = cricket::CapturedFrame::kUnknownDataSize;
captured_frame_.fourcc = static_cast<uint32>(cricket::FOURCC_ANY);
frame_ = frame;
}
void ReleaseFrame() { frame_ = NULL; }
const cricket::CapturedFrame* GetCapturedFrame() const {
return &captured_frame_;
}
cricket::VideoFrame* CreateAliasedFrame(
const cricket::CapturedFrame* input_frame,
int cropped_input_width,
int cropped_input_height,
int output_width,
int output_height) const override {
// Check that captured_frame is actually our frame.
DCHECK(input_frame == &captured_frame_);
DCHECK(frame_.get());
// Create a centered cropped visible rect that preservers aspect ratio for
// cropped natural size.
gfx::Rect visible_rect = frame_->visible_rect();
visible_rect.ClampToCenteredSize(gfx::Size(
visible_rect.width() * cropped_input_width / input_frame->width,
visible_rect.height() * cropped_input_height / input_frame->height));
const gfx::Size output_size(output_width, output_height);
scoped_refptr<media::VideoFrame> video_frame =
media::VideoFrame::WrapVideoFrame(
frame_, visible_rect, output_size,
base::Bind(&ReleaseOriginalFrame, frame_));
// If no scaling is needed, return a wrapped version of |frame_| directly.
if (video_frame->natural_size() == video_frame->visible_rect().size())
return new VideoFrameWrapper(video_frame, captured_frame_.elapsed_time);
// We need to scale the frame before we hand it over to cricket.
scoped_refptr<media::VideoFrame> scaled_frame =
scaled_frame_pool_.CreateFrame(media::VideoFrame::I420, output_size,
gfx::Rect(output_size), output_size,
frame_->timestamp());
libyuv::I420Scale(video_frame->visible_data(media::VideoFrame::kYPlane),
video_frame->stride(media::VideoFrame::kYPlane),
video_frame->visible_data(media::VideoFrame::kUPlane),
video_frame->stride(media::VideoFrame::kUPlane),
video_frame->visible_data(media::VideoFrame::kVPlane),
video_frame->stride(media::VideoFrame::kVPlane),
video_frame->visible_rect().width(),
video_frame->visible_rect().height(),
scaled_frame->data(media::VideoFrame::kYPlane),
scaled_frame->stride(media::VideoFrame::kYPlane),
scaled_frame->data(media::VideoFrame::kUPlane),
scaled_frame->stride(media::VideoFrame::kUPlane),
scaled_frame->data(media::VideoFrame::kVPlane),
scaled_frame->stride(media::VideoFrame::kVPlane),
output_width, output_height, libyuv::kFilterBilinear);
return new VideoFrameWrapper(scaled_frame, captured_frame_.elapsed_time);
}
cricket::VideoFrame* CreateAliasedFrame(
const cricket::CapturedFrame* input_frame,
int output_width,
int output_height) const override {
return CreateAliasedFrame(input_frame, input_frame->width,
input_frame->height, output_width, output_height);
}
private:
scoped_refptr<media::VideoFrame> frame_;
cricket::CapturedFrame captured_frame_;
// This is used only if scaling is needed.
mutable media::VideoFramePool scaled_frame_pool_;
};
WebRtcVideoCapturerAdapter::WebRtcVideoCapturerAdapter(bool is_screencast)
: is_screencast_(is_screencast),
running_(false),
first_frame_timestamp_(media::kNoTimestamp()),
frame_factory_(new MediaVideoFrameFactory) {
thread_checker_.DetachFromThread();
// The base class takes ownership of the frame factory.
set_frame_factory(frame_factory_);
}
WebRtcVideoCapturerAdapter::~WebRtcVideoCapturerAdapter() {
DVLOG(3) << " WebRtcVideoCapturerAdapter::dtor";
}
cricket::CaptureState WebRtcVideoCapturerAdapter::Start(
const cricket::VideoFormat& capture_format) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!running_);
DVLOG(3) << " WebRtcVideoCapturerAdapter::Start w = " << capture_format.width
<< " h = " << capture_format.height;
running_ = true;
return cricket::CS_RUNNING;
}
void WebRtcVideoCapturerAdapter::Stop() {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(3) << " WebRtcVideoCapturerAdapter::Stop ";
DCHECK(running_);
running_ = false;
SetCaptureFormat(NULL);
SignalStateChange(this, cricket::CS_STOPPED);
}
bool WebRtcVideoCapturerAdapter::IsRunning() {
DCHECK(thread_checker_.CalledOnValidThread());
return running_;
}
bool WebRtcVideoCapturerAdapter::GetPreferredFourccs(
std::vector<uint32>* fourccs) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!fourccs || fourccs->empty());
if (fourccs)
fourccs->push_back(cricket::FOURCC_I420);
return fourccs != NULL;
}
bool WebRtcVideoCapturerAdapter::IsScreencast() const {
return is_screencast_;
}
bool WebRtcVideoCapturerAdapter::GetBestCaptureFormat(
const cricket::VideoFormat& desired,
cricket::VideoFormat* best_format) {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(3) << " GetBestCaptureFormat:: "
<< " w = " << desired.width
<< " h = " << desired.height;
// Capability enumeration is done in MediaStreamVideoSource. The adapter can
// just use what is provided.
// Use the desired format as the best format.
best_format->width = desired.width;
best_format->height = desired.height;
best_format->fourcc = cricket::FOURCC_I420;
best_format->interval = desired.interval;
return true;
}
void WebRtcVideoCapturerAdapter::OnFrameCaptured(
const scoped_refptr<media::VideoFrame>& frame) {
DCHECK(thread_checker_.CalledOnValidThread());
TRACE_EVENT0("video", "WebRtcVideoCapturerAdapter::OnFrameCaptured");
if (!(media::VideoFrame::I420 == frame->format() ||
media::VideoFrame::YV12 == frame->format())) {
// Some types of sources support textures as output. Since connecting
// sources and sinks do not check the format, we need to just ignore
// formats that we can not handle.
NOTREACHED();
return;
}
if (first_frame_timestamp_ == media::kNoTimestamp())
first_frame_timestamp_ = frame->timestamp();
const int64 elapsed_time =
(frame->timestamp() - first_frame_timestamp_).InMicroseconds() *
base::Time::kNanosecondsPerMicrosecond;
// Inject the frame via the VideoFrameFractory.
DCHECK(frame_factory_ == frame_factory());
frame_factory_->SetFrame(frame, elapsed_time);
// This signals to libJingle that a new VideoFrame is available.
SignalFrameCaptured(this, frame_factory_->GetCapturedFrame());
frame_factory_->ReleaseFrame(); // Release the frame ASAP.
}
} // namespace content
| 35.990148 | 80 | 0.688201 | hefen1 |
8d16689051dda8f18e8c0dedba0de3f1a7807b0a | 2,071 | cpp | C++ | src/gui-qt4/libs/seiscomp3/gui/core/gradient.cpp | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 94 | 2015-02-04T13:57:34.000Z | 2021-11-01T15:10:06.000Z | src/gui-qt4/libs/seiscomp3/gui/core/gradient.cpp | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 233 | 2015-01-28T15:16:46.000Z | 2021-08-23T11:31:37.000Z | src/gui-qt4/libs/seiscomp3/gui/core/gradient.cpp | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 95 | 2015-02-13T15:53:30.000Z | 2021-11-02T14:54:54.000Z | /***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* 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 *
* SeisComP Public License for more details. *
***************************************************************************/
#include <seiscomp3/gui/core/gradient.h>
namespace Seiscomp {
namespace Gui {
namespace {
QColor blend(const QColor& c1, const QColor& c2, qreal ratio) {
qreal invRatio = 1-ratio;
return QColor((int)(c1.red()*invRatio + c2.red()*ratio),
(int)(c1.green()*invRatio + c2.green()*ratio),
(int)(c1.blue()*invRatio + c2.blue()*ratio),
(int)(c1.alpha()*invRatio + c2.alpha()*ratio));
}
}
Gradient::Gradient() {}
void Gradient::setColorAt(qreal position, const QColor &color, const QString& text) {
insert(position, qMakePair(color, text));
}
QColor Gradient::colorAt(qreal position, bool discrete) const {
const_iterator last = end();
for ( const_iterator it = begin(); it != end(); ++it ) {
if ( it.key() == position )
return it.value().first;
else if ( it.key() > position ) {
if ( last != end() ) {
if ( discrete ) {
return last.value().first;
}
else {
qreal v1 = last.key();
qreal v2 = it.key();
return blend(last.value().first, it.value().first, (position-v1)/(v2-v1));
}
}
else
return it.value().first;
}
last = it;
}
if ( last != end() )
return last.value().first;
return QColor();
}
}
}
| 27.613333 | 85 | 0.48817 | yannikbehr |
8d16fababc5043fac3767090f8c0966ed4bd9480 | 6,194 | cpp | C++ | cpp/template/template.cpp | HieuuuLeee/WorldFinal | ea1b1e697e6e7987018a5a79402d1a2659270591 | [
"MIT"
] | null | null | null | cpp/template/template.cpp | HieuuuLeee/WorldFinal | ea1b1e697e6e7987018a5a79402d1a2659270591 | [
"MIT"
] | null | null | null | cpp/template/template.cpp | HieuuuLeee/WorldFinal | ea1b1e697e6e7987018a5a79402d1a2659270591 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define pf push_front
#define pp push
#define et empty
#define mp make_pair
#define For(i,a,b) for (int i=a;i<=b;i++)
#define Fod(i,b,a) for (int i=b;i>=a;i--)
#define Forl(i,a,b) for (ll i=a;i<=b;i++)
#define Fodl(i,b,a) for (ll i=b;i>=a;i--)
typedef int64_t ll;
typedef uint64_t ull;
#define prno cout<<"NO\n"
#define pryes cout<<"YES\n"
#define pryon pryes; else prno;
#define brln cout << "\n";
#define el "\n"
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define prarr(a,n) For(i,1,n)cout<<a[i]<<" "; brln;
#define bitcount(n) __builtin_popcountll(n)
#define INFILE(name) freopen(name, "r", stdin)
#define OUFILE(name) freopen(name, "w", stdout)
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
const int inf = 1e6+5;
// sort(arr, arr+n, greater<int>());
int sum() { return 0; }
template<typename T, typename... Args>
T sum(T a, Args... args) { return a + sum(args...); }
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
// cout << "\n";
cout << *it << " = " << a << endl;
err(++it, args...);
// cout << "\n";
}
inline ll read(){
ll x=0,t=1;char ch=getchar();
while(ch>'9'||ch<'0'){if(ch=='-')t=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9')
x=x*10+ch-'0',ch=getchar();
return x*t;
}
bool compare(pair<ll,ll> a, pair<ll,ll> b){
return a.second - a.first < b.second -
b.first;
}
pair<ll, ll> factor(ll n) {
ll s = 0;
while ((n & 1) == 0) {
s++;
n >>= 1;
}
return {s, n};
}
ll pow(ll a, ll d, ll n) {
ll result = 1;
a = a % n;
while (d > 0) {
if (d & 1) result = result * a % n;
d >>= 1;
a = a * a % n;
}
return result;
}
bool test_a(ll s, ll d, ll n, ll a) {
if (n == a) return true;
ll p = pow(a, d, n);
if (p == 1) return true;
for (; s > 0; s--) {
if (p == n-1) return true;
p = p * p % n;
}
return false;
}
bool miller(ll n) {
if (n < 2) return false;
if ((n & 1) == 0) return n == 2;
ll s, d;
tie(s, d) = factor(n-1);
// return test_a(s, d, n, 2) && test_a(s, d, n, 3);
return test_a(s, d, n, 2) && test_a(s, d, n, 7) && test_a(s, d, n, 61);
}
ll nCr(ll n, ll r){
ll tmp = n-r;
for(ll i = n-1; i > tmp; i--)
n *= i;
for(ll i = r-1; i > 1; i--)
r *= i;
return n/r;
}
ll NCR(int n, int r){
ll p = 1, k = 1;
if (n - r < r)
r = n - r;
if (r != 0) {
while (r) {
p *= n; k *= r;
ll m = __gcd(p, k);
p /= m; k /= m;
n--; r--;
}
}
else p = 1;
return p;
}
inline ll mul(ll a, ll b, ll MOD = (1LL<<62)){
return ((((a)%MOD)*((b)%MOD))%MOD);
}
inline ll add(ll a, ll b, ll MOD = (1LL<<62)){
return ((((a)%MOD)+((b)%MOD))%MOD);
}
inline ll Pow(ll base, ll exp, ll MOD = (1LL<<62)){
ll ans = 1;
while(exp){
if(exp & 1)
ans = (ans*base)%MOD;
exp >>= 1;
base = (base*base)%MOD;
}
return ans;
}
void sieve(int N) {
bool isPrime[1000000];
for(int i = 0; i <= N;++i) {
isPrime[i] = true;
}
isPrime[0] = false;
isPrime[1] = false;
for(int i = 2; i * i <= N; ++i) {
if(isPrime[i] == true) {
for(int j = i * i; j <= N; j += i)
isPrime[j] = false;
}}}
//=====================================================
// O((R−L+1)loglog(R)+(√R)loglog(√R)).
vector<bool> segmentedSieve(long long L, long long R) {
// generate all primes up to sqrt(R)
long long lim = sqrt(R);
vector<bool> mark(lim + 1, false);
vector<long long> primes;
for (long long i = 2; i <= lim; ++i) {
if (!mark[i]) {
primes.emplace_back(i);
for (long long j = i * i; j <= lim; j += i)
mark[j] = true;
}
}
vector<bool> isPrime(R - L + 1, true);
for (long long i : primes)
for (long long j = max(i * i, (L + i - 1) / i * i); j <= R; j += i)
isPrime[j - L] = false;
if (L == 1)
isPrime[0] = false;
return isPrime;
}
///======================================
ll minPrime[1000000];
void pre_factorize(ll n){
for (ll i = 2; i * i <= n; ++i) {
if (minPrime[i] == 0) { //if i is prime
for (ll j = i * i; j <= n; j += i) {
if (minPrime[j] == 0) {
minPrime[j] = i;
}}}}
for (ll i = 2; i <= n; ++i) {
if (minPrime[i] == 0) {
minPrime[i] = i;
}}
}
vector<ll> factorize(ll n) {
vector<ll> res;
while (n != 1) {
res.push_back(minPrime[n]);
n /= minPrime[n];}
return res;}
vector<ll> factorize_hh(ll n) {
vector<ll> res;
for (ll i = 2; i * i <= n; ++i) {
while (n % i == 0) {
res.push_back(i);
n /= i;}}
if (n != 1) {
res.push_back(n);}
return res;}
ll n;
int main(){
fast;
INFILE("../in.txt");
OUFILE("../out.txt");
cout<<pow(2,5,10);
// cout << nCr(100000000000000000,50);
// cout << miller(23);
// cout << factor(510).first << factor(510).second;
// For(i, 1, 10) cout << i << " " << (i & 1) << "\n";
// cout << (10<<1);
// ll a = 100000;
// DUMP(a);
// pre_factorize(1000000);
// vector<ll> x = factorize(a);
// for(auto i : x) cout << i << " ";
// vector<ll> x = factorize_hh(a);
// for(auto i : x) cout << i << " ";
// CURTIME();
}
// xc = ((a.x * a.x + a.y * a.y) * (b.y - c.y) + (b.x * b.x + b.y * b.y) * (c.y - a.y) + (c.x * c.x + c.y * c.y) * (a.y - b.y)) / d;
// yc = ((a.x * a.x + a.y * a.y) * (c.x - b.x) + (b.x * b.x + b.y * b.y) * (a.x - c.x) + (c.x * c.x + c.y * c.y) * (b.x - a.x)) / d; | 26.583691 | 160 | 0.45092 | HieuuuLeee |
8d17a9708f7d382445bdde2d7b06c3fbb2d322ae | 347 | cpp | C++ | test/compute/Main.cpp | craft095/sere | b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9 | [
"MIT"
] | null | null | null | test/compute/Main.cpp | craft095/sere | b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9 | [
"MIT"
] | null | null | null | test/compute/Main.cpp | craft095/sere | b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9 | [
"MIT"
] | null | null | null | #ifdef GTEST
#include "gtest/gtest.h"
#endif
#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"
int main(int argc, char **argv) {
#ifdef GTEST
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
if (result != 0) {
return result;
}
#endif
int result = Catch::Session().run( argc, argv );
return result;
}
| 16.52381 | 50 | 0.668588 | craft095 |
8d180d3c6da645841f0beecc34ec1e85de2879dc | 18,738 | hpp | C++ | examples/experimental/nvshmem/matrix/grb_util.hpp | ge49nuk/BCLmatrix | f04368cc88ff9b2b652a403c69075a036b2b5586 | [
"BSD-3-Clause"
] | null | null | null | examples/experimental/nvshmem/matrix/grb_util.hpp | ge49nuk/BCLmatrix | f04368cc88ff9b2b652a403c69075a036b2b5586 | [
"BSD-3-Clause"
] | 1 | 2021-05-21T20:27:02.000Z | 2021-05-21T21:54:46.000Z | examples/experimental/nvshmem/matrix/grb_util.hpp | ge49nuk/BCLmatrix | f04368cc88ff9b2b652a403c69075a036b2b5586 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <matrix_sum.cuh>
namespace BCL {
template <typename T>
struct max {
T operator()(const T& a, const T& b) const {
if (a < b) {
return b;
} else {
return a;
}
}
};
template <typename T>
struct min {
T operator()(const T& a, const T& b) const {
if (a < b) {
return a;
} else {
return b;
}
}
};
namespace cuda {
graphblas::Descriptor* grb_desc_ = nullptr;
// TODO: Actually free matrix contents.
template <typename T>
void destroy_grb(graphblas::Matrix<T>* x, const std::string lbl = "hey") {
if (x == nullptr) {
return;
}
auto& m = x->matrix_.sparse_;
if (m.h_csrRowPtr_) free(m.h_csrRowPtr_);
if (m.h_csrColInd_) free(m.h_csrColInd_);
if (m.h_csrVal_ ) free(m.h_csrVal_);
if (BCL::cuda::__is_valid_cuda_gptr(m.d_csrRowPtr_)) {
BCL::cuda::dealloc(BCL::cuda::__to_cuda_gptr(m.d_csrRowPtr_));
} else {
/*
fprintf(stderr, "0x%p is not a valid BCL pointer, checking value for %s (valid segment is 0x%p -> 0x%p\n",
m.d_csrRowPtr_, lbl.c_str(), BCL::cuda::smem_base_ptr, BCL::cuda::smem_base_ptr + BCL::cuda::shared_segment_size);
*/
CUDA_CALL(cudaPeekAtLastError());
if (m.d_csrRowPtr_) CUDA_CALL(cudaFree(m.d_csrRowPtr_));
}
if (BCL::cuda::__is_valid_cuda_gptr(m.d_csrColInd_)) {
BCL::cuda::dealloc(BCL::cuda::__to_cuda_gptr(m.d_csrColInd_));
} else {
if (m.d_csrColInd_) CUDA_CALL(cudaFree(m.d_csrColInd_));
}
if (BCL::cuda::__is_valid_cuda_gptr(m.d_csrVal_ )) {
BCL::cuda::dealloc(BCL::cuda::__to_cuda_gptr(m.d_csrVal_));
} else {
if (m.d_csrVal_ ) CUDA_CALL(cudaFree(m.d_csrVal_ ));
}
if (m.format_ == graphblas::backend::GrB_SPARSE_MATRIX_CSRCSC) {
throw std::runtime_error("destroy_grb: Case not handled.");
}
}
template <typename T, typename Allocator>
graphblas::Matrix<T>* sum_tiles_yuxin(std::vector<graphblas::Matrix<T>*> imp) {
if (imp.size() == 0) {
return nullptr;
}
using index_type = graphblas::Index;
graphblas::Index m, n;
imp[0]->nrows(&m);
imp[0]->ncols(&n);
::cuda::SparseSPAAccumulator<T, index_type, Allocator> acc;
for (auto mat : imp) {
// convert mat into Yuxin's BCL::cuda::CSRMatrix
graphblas::Index nnz;
mat->nvals(&nnz);
::cuda::CSRMatrix<T, index_type, Allocator> cmat(m, n, nnz,
mat->matrix_.sparse_.d_csrVal_,
mat->matrix_.sparse_.d_csrRowPtr_,
mat->matrix_.sparse_.d_csrColInd_);
acc.accumulate(std::move(cmat), {0, 0});
}
acc.sort_mats();
acc.get_lbs();
// Assume a 1 GB memory limit for accumualtor.
size_t max_mem = 1*1000*1000*1000;
size_t max_mem_row = std::min<size_t>(m, max_mem/((sizeof(graphblas::Index)+sizeof(T))*n));
size_t block_size = 512;
auto result_mat = acc.get_matrix(m, n, max_mem_row, block_size);
graphblas::Matrix<T>* grb_result = new graphblas::Matrix<T>(result_mat.m_, result_mat.n_);
grb_result->build(result_mat.row_ptr_, result_mat.col_ind_, result_mat.vals_,
result_mat.nnz_);
return grb_result;
}
template <typename T, typename index_type>
auto get_coo(const std::vector<T>& values,
const std::vector<index_type>& row_indices,
const std::vector<index_type>& col_indices)
{
using coord_type = std::pair<index_type, index_type>;
using tuple_type = std::pair<coord_type, T>;
using coo_t = std::vector<tuple_type>;
coo_t coo_values(values.size());
for (size_t i = 0; i < values.size(); i++) {
coo_values[i] = {{row_indices[i], col_indices[i]}, values[i]};
}
std::sort(coo_values.begin(), coo_values.end(),
[](const auto& a, const auto& b) -> bool {
if (std::get<0>(a) != std::get<0>(b)) {
return std::get<0>(a) < std::get<0>(b);
} else {
return std::get<1>(a) < std::get<1>(b);
}
});
return coo_values;
}
template <typename T, typename index_type>
auto remove_zeros(const std::vector<std::pair<std::pair<index_type, index_type>, T>>& coo_values) {
using coord_type = std::pair<index_type, index_type>;
using tuple_type = std::pair<coord_type, T>;
using coo_t = std::vector<tuple_type>;
coo_t new_coo;
for (const auto& nz : coo_values) {
auto val = std::get<1>(nz);
if (val != 0.0) {
new_coo.push_back(nz);
}
}
return new_coo;
}
template <typename T>
void print_coo(const T& coo, size_t max_idx = std::numeric_limits<size_t>::max()) {
for (size_t i = 0; i < std::min(coo.size(), max_idx); i++) {
auto idx = std::get<0>(coo[i]);
auto val = std::get<1>(coo[i]);
printf("(%lu, %lu) %f\n", idx.first, idx.second, val);
}
}
template <typename T, typename index_type, typename Allocator>
graphblas::Matrix<T>*
get_graphblast_view(CudaCSRMatrix<T, index_type, Allocator>& a) {
graphblas::Matrix<T>* grb_matrix = new graphblas::Matrix<T>(a.m(), a.n());
grb_matrix->build(a.rowptr_data(), a.colind_data(), a.values_data(), a.nnz());
return grb_matrix;
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
convert_to_csr(graphblas::Matrix<T>* a_grb) {
graphblas::Index m, n, nnz;
a_grb->nrows(&m);
a_grb->ncols(&n);
a_grb->nvals(&nnz);
T* values = a_grb->matrix_.sparse_.d_csrVal_;
index_type* rowptr = a_grb->matrix_.sparse_.d_csrRowPtr_;
index_type* colind = a_grb->matrix_.sparse_.d_csrColInd_;
return CudaCSRMatrix<T, index_type, Allocator>({m, n}, nnz, values, rowptr, colind);
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
spgemm_graphblast(CudaCSRMatrix<T, index_type, Allocator>& a,
CudaCSRMatrix<T, index_type, Allocator>& b)
{
// static assert index_type is graphblas::Index
grb_desc_->descriptor_.debug_ = false;
if (a.nnz() == 0 || b.nnz() == 0) {
// return empty matrix
return CudaCSRMatrix<T, index_type, Allocator>({a.shape()[0], b.shape()[1]});
} else {
auto binary_op = GrB_NULL;
auto semiring = graphblas::PlusMultipliesSemiring<T>{};
auto a_grb = get_graphblast_view(a);
auto b_grb = get_graphblast_view(b);
auto* c_grb = new graphblas::Matrix<T>(a.shape()[0], b.shape()[1]);
graphblas::mxm<T, T, T, T, decltype(binary_op), decltype(semiring),
Allocator>
(c_grb, GrB_NULL,
binary_op, semiring,
a_grb, b_grb, grb_desc_);
auto c = convert_to_csr<T, index_type, Allocator>(c_grb);
free(a_grb);
free(b_grb);
free(c_grb);
return c;
}
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
sum_cusparse(CudaCSRMatrix<T, index_type, Allocator>& a,
CudaCSRMatrix<T, index_type, Allocator>& b) {
// XXX: Do an element-wise add using cuSparse
// 'A' here is local_c, and 'B' here is result_c
//. At the end, the new accumulated matrix will be put in local_c.
// TODO: allocate handle elsewhere.
cusparseHandle_t handle;
cusparseStatus_t status =
cusparseCreate(&handle);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetPointerMode(handle, CUSPARSE_POINTER_MODE_HOST);
BCL::cuda::throw_cusparse(status);
index_type arows = a.shape()[0];
index_type acols = a.shape()[1];
index_type brows = b.shape()[0];
index_type bcols = b.shape()[1];
assert(acols == bcols);
assert(arows == brows);
index_type m = arows;
index_type n = acols;
static_assert(std::is_same<int, index_type>::value);
cusparseMatDescr_t descr_a, descr_b, descr_c;
status =
cusparseCreateMatDescr(&descr_a);
BCL::cuda::throw_cusparse(status);
status =
cusparseCreateMatDescr(&descr_b);
BCL::cuda::throw_cusparse(status);
status =
cusparseCreateMatDescr(&descr_c);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatType(descr_a, CUSPARSE_MATRIX_TYPE_GENERAL);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatIndexBase(descr_a, CUSPARSE_INDEX_BASE_ZERO);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatType(descr_b, CUSPARSE_MATRIX_TYPE_GENERAL);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatIndexBase(descr_b, CUSPARSE_INDEX_BASE_ZERO);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatType(descr_c, CUSPARSE_MATRIX_TYPE_GENERAL);
BCL::cuda::throw_cusparse(status);
status =
cusparseSetMatIndexBase(descr_c, CUSPARSE_INDEX_BASE_ZERO);
BCL::cuda::throw_cusparse(status);
index_type a_nnz = a.nnz();
index_type b_nnz = b.nnz();
index_type c_nnz;
index_type* nnzTotalDevHostPtr;
nnzTotalDevHostPtr = &c_nnz;
index_type* row_ptr_c;
row_ptr_c = rebind_allocator_t<Allocator, index_type>{}.allocate(m+1);
if (row_ptr_c == nullptr) {
throw std::runtime_error("Couldn't allocate C.");
}
index_type* a_row_ptr = a.rowptr_data();
index_type* a_col_ind = a.colind_data();
index_type* b_row_ptr = b.rowptr_data();
index_type* b_col_ind = b.colind_data();
status =
cusparseXcsrgeamNnz(handle,
m,
n,
descr_a,
a_nnz,
a_row_ptr,
a_col_ind,
descr_b,
b_nnz,
b_row_ptr,
b_col_ind,
descr_c,
row_ptr_c,
nnzTotalDevHostPtr);
BCL::cuda::throw_cusparse(status);
if (nnzTotalDevHostPtr == nullptr) {
throw std::runtime_error("Unhandled case: nnzTotalDevHostPtr is null.");
} else {
c_nnz = *nnzTotalDevHostPtr;
}
T alpha = 1.0;
T beta = 1.0;
index_type* col_ind_c;
T* values_c;
col_ind_c = rebind_allocator_t<Allocator, index_type>{}.allocate(c_nnz);
values_c = rebind_allocator_t<Allocator, T>{}.allocate(c_nnz);
if (col_ind_c == nullptr || values_c == nullptr) {
throw std::runtime_error("sum_tiles(): out of memory.");
}
status =
cusparseScsrgeam(handle,
m,
n,
&alpha,
descr_a,
a_nnz,
a.values_data(),
a.rowptr_data(),
a.colind_data(),
&beta,
descr_b,
b_nnz,
b.values_data(),
b.rowptr_data(),
b.colind_data(),
descr_c,
values_c,
row_ptr_c,
col_ind_c);
BCL::cuda::throw_cusparse(status);
cudaDeviceSynchronize();
return CudaCSRMatrix<T, index_type, Allocator>({m, n}, c_nnz, values_c, row_ptr_c, col_ind_c);
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
sum_tiles_cusparse(std::vector<CudaCSRMatrix<T, index_type, Allocator>>& imp) {
using csr_type = CudaCSRMatrix<T, index_type, Allocator>;
if (imp.size() == 0) {
return csr_type({0, 0}, 0);
}
csr_type sum = std::move(imp[0]);
for (size_t i = 1; i < imp.size(); i++) {
csr_type comp = std::move(imp[i]);
csr_type result = sum_cusparse<T, index_type, Allocator>(sum, comp);
std::swap(sum, result);
}
return sum;
}
template <typename T, typename index_type, typename Allocator>
bool is_shared_seg(CudaCSRMatrix<T, index_type, Allocator>& mat) {
if (!__is_valid_cuda_gptr(mat.values_data())) {
return false;
} else if (!__is_valid_cuda_gptr(mat.rowptr_data())) {
return false;
} else if (!__is_valid_cuda_gptr(mat.colind_data())) {
return false;
} else {
return true;
}
}
template <typename T, typename index_type, typename Allocator>
CudaCSRMatrix<T, index_type, Allocator>
spgemm_cusparse(CudaCSRMatrix<T, index_type, Allocator>& a,
CudaCSRMatrix<T, index_type, Allocator>& b)
{
// static assert index_type is graphblas::Index
grb_desc_->descriptor_.debug_ = false;
if (a.nnz() == 0 || b.nnz() == 0) {
// return empty matrix
return CudaCSRMatrix<T, index_type, Allocator>({a.shape()[0], b.shape()[1]}, 0);
} else {
size_t m = a.m();
size_t n = b.n();
size_t k = a.n();
cusparseHandle_t handle;
cusparseStatus_t status = cusparseCreate(&handle);
BCL::cuda::throw_cusparse(status);
status = cusparseSetPointerMode(handle, CUSPARSE_POINTER_MODE_HOST);
BCL::cuda::throw_cusparse(status);
int baseC, nnzC;
csrgemm2Info_t info = nullptr;
size_t bufferSize;
char* buffer = nullptr;
// nnzTotalDevHostPtr points to host memory
int* nnzTotalDevHostPtr = &nnzC;
T alpha = 1;
T beta = 0;
cusparseSetPointerMode(handle, CUSPARSE_POINTER_MODE_HOST);
cusparseMatDescr_t descr;
cusparseCreateMatDescr(&descr);
cusparseSetMatType(descr, CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(descr, CUSPARSE_INDEX_BASE_ZERO);
// step1: create an opaque structure
cusparseCreateCsrgemm2Info(&info);
status =
cusparseScsrgemm2_bufferSizeExt(handle, m, n, k, &alpha,
descr, a.nnz(), a.rowptr_data(), a.colind_data(),
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
&beta,
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
info,
&bufferSize);
BCL::cuda::throw_cusparse(status);
buffer = allocate_with<char, Allocator>(bufferSize);
// step 3: compute csrRowPtrC
index_type* csrRowPtrC = allocate_with<index_type, Allocator>(m+1);
status =
cusparseXcsrgemm2Nnz(handle, m, n, k,
descr, a.nnz(), a.rowptr_data(), a.colind_data(),
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
descr, b.nnz(), b.rowptr_data(), b.colind_data(),
descr, csrRowPtrC, nnzTotalDevHostPtr, info, buffer);
BCL::cuda::throw_cusparse(status);
if (nnzTotalDevHostPtr != nullptr) {
nnzC = *nnzTotalDevHostPtr;
} else {
cudaMemcpy(&nnzC, csrRowPtrC+m, sizeof(index_type), cudaMemcpyDeviceToHost);
cudaMemcpy(&baseC, csrRowPtrC, sizeof(index_type), cudaMemcpyDeviceToHost);
nnzC -= baseC;
}
// step 4: finish sparsity pattern and value of C
index_type* csrColIndC = allocate_with<index_type, Allocator>(nnzC);
T* csrValC = allocate_with<T, Allocator>(nnzC);
// Remark: set csrValC to null if only sparsity pattern is required.
status =
cusparseScsrgemm2(handle, m, n, k, &alpha,
descr, a.nnz(), a.values_data(), a.rowptr_data(), a.colind_data(),
descr, b.nnz(), b.values_data(), b.rowptr_data(), b.colind_data(),
&beta,
descr, b.nnz(), b.values_data(), b.rowptr_data(), b.colind_data(),
descr, csrValC, csrRowPtrC, csrColIndC,
info, buffer);
BCL::cuda::throw_cusparse(status);
cudaDeviceSynchronize();
// step 5: destroy the opaque structure
cusparseDestroyCsrgemm2Info(info);
deallocate_with<char, Allocator>(buffer);
cusparseDestroy(handle);
return CudaCSRMatrix<T, index_type, Allocator>({m, n}, nnzC, csrValC, csrRowPtrC, csrColIndC);
}
}
template <typename AMatrixType, typename BMatrixType, typename CMatrixType>
void spmm_cusparse(AMatrixType& a,
BMatrixType& b,
CMatrixType& c)
{
using Allocator = typename AMatrixType::allocator_type;
if (a.nnz() == 0) {
return;
}
static_assert(std::is_same<typename AMatrixType::value_type, float>::value);
static_assert(std::is_same<typename BMatrixType::value_type, float>::value);
static_assert(std::is_same<typename CMatrixType::value_type, float>::value);
static_assert(std::is_same<typename AMatrixType::index_type, int32_t>::value);
cusparseHandle_t handle;
cusparseStatus_t status = cusparseCreate(&handle);
BCL::cuda::throw_cusparse(status);
cusparseSpMatDescr_t a_cusparse;
status =
cusparseCreateCsr(&a_cusparse, a.m(), a.n(), a.nnz(),
a.rowptr_data(), a.colind_data(), a.values_data(),
CUSPARSE_INDEX_32I, CUSPARSE_INDEX_32I,
CUSPARSE_INDEX_BASE_ZERO, CUDA_R_32F);
BCL::cuda::throw_cusparse(status);
cusparseDnMatDescr_t b_cusparse;
status =
cusparseCreateDnMat(&b_cusparse, b.m(), b.n(), b.ld(),
b.data(), CUDA_R_32F, CUSPARSE_ORDER_COL);
BCL::cuda::throw_cusparse(status);
cusparseDnMatDescr_t c_cusparse;
status =
cusparseCreateDnMat(&c_cusparse, c.m(), c.n(), c.ld(),
c.data(), CUDA_R_32F, CUSPARSE_ORDER_COL);
BCL::cuda::throw_cusparse(status);
T alpha = 1.0;
T beta = 1.0;
size_t bufferSize;
status =
cusparseSpMM_bufferSize(handle,
CUSPARSE_OPERATION_NON_TRANSPOSE,
CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha,
a_cusparse,
b_cusparse,
&beta,
c_cusparse,
CUDA_R_32F,
CUSPARSE_MM_ALG_DEFAULT,
&bufferSize);
BCL::cuda::throw_cusparse(status);
char* externalBuffer = allocate_with<char, Allocator>(bufferSize);
status =
cusparseSpMM(handle,
CUSPARSE_OPERATION_NON_TRANSPOSE,
CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha,
a_cusparse,
b_cusparse,
&beta,
c_cusparse,
CUDA_R_32F,
CUSPARSE_MM_ALG_DEFAULT,
externalBuffer);
BCL::cuda::throw_cusparse(status);
cudaDeviceSynchronize();
deallocate_with<char, Allocator>(externalBuffer);
cusparseDestroy(handle);
cusparseDestroySpMat(a_cusparse);
cusparseDestroyDnMat(b_cusparse);
cusparseDestroyDnMat(c_cusparse);
}
// TODO: Put this in another file
template <typename T, typename index_type, typename Allocator = BCL::bcl_allocator<T>>
CudaCSRMatrix<T, index_type, Allocator> to_gpu(CSRMatrix<T, index_type>& mat) {
CudaCSRMatrix<T, index_type, Allocator> mat_gpu({mat.m(), mat.n()}, mat.nnz());
cudaMemcpy(mat_gpu.values_data(), mat.values_data(), sizeof(T)*mat.nnz(), cudaMemcpyHostToDevice);
cudaMemcpy(mat_gpu.rowptr_data(), mat.rowptr_data(), sizeof(index_type)*(mat.m()+1), cudaMemcpyHostToDevice);
cudaMemcpy(mat_gpu.colind_data(), mat.colind_data(), sizeof(index_type)*mat.nnz(), cudaMemcpyHostToDevice);
return mat_gpu;
}
} // end cuda
} // end BCL
| 33.223404 | 126 | 0.631871 | ge49nuk |
8d1a05be6f773b4a111e52f473a53eca9f83a45a | 9,017 | cpp | C++ | Source/Network/src/Socket/UDP.cpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 20 | 2015-04-02T06:55:30.000Z | 2022-03-29T04:27:30.000Z | Source/Network/src/Socket/UDP.cpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 692 | 2015-04-01T21:05:49.000Z | 2020-03-10T10:11:57.000Z | Source/Network/src/Socket/UDP.cpp | appcelerator/titanium_mobile_windows | ec82c011f418cbcf27795eb009deaef5e3fe4b20 | [
"Apache-2.0"
] | 22 | 2015-04-01T20:57:51.000Z | 2022-01-18T17:33:15.000Z | /**
* Copyright (c) 2016 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License.
* Please see the LICENSE included with this distribution for details.
*/
#include "TitaniumWindows/Network/Socket/UDP.hpp"
#include "Titanium/Blob.hpp"
#include "TitaniumWindows/Utility.hpp"
#include "TitaniumWindows/WindowsMacros.hpp"
#include <ppltasks.h>
#include <concrt.h>
using namespace Windows::Foundation;
using namespace Windows::Security::Cryptography;
using namespace Windows::Storage::Streams;
using namespace Windows::Networking;
using namespace Windows::Networking::Sockets;
namespace TitaniumWindows
{
namespace Network
{
namespace Socket
{
UDP::UDP(const JSContext& js_context) TITANIUM_NOEXCEPT
: Titanium::Network::Socket::UDP(js_context)
{
}
UDP::~UDP()
{
socket__ = nullptr;
}
void UDP::JSExportInitialize()
{
JSExport<UDP>::SetClassVersion(1);
JSExport<UDP>::SetParent(JSExport<Titanium::Network::Socket::UDP>::Class());
}
void UDP::postCallAsConstructor(const JSContext& js_context, const std::vector<JSValue>& arguments)
{
Titanium::Network::Socket::UDP::postCallAsConstructor(js_context, arguments);
socket__ = ref new DatagramSocket();
socket__->MessageReceived += ref new TypedEventHandler<DatagramSocket^, DatagramSocketMessageReceivedEventArgs^>
([this](Platform::Object^ sender, DatagramSocketMessageReceivedEventArgs^ e) {
if (data__.IsObject()) {
TitaniumWindows::Utility::RunOnUIThread([this, e]() {
try {
auto callback = static_cast<JSObject>(data__);
if (callback.IsFunction()) {
const auto ctx = get_context();
auto args = get_context().CreateObject();
const auto reader = e->GetDataReader();
std::vector<std::uint8_t> data(reader->UnconsumedBufferLength);
if (!data.empty()) {
auto data_ref = Platform::ArrayReference<std::uint8_t>(&data[0], static_cast<std::uint32_t>(data.size()));
reader->ReadBytes(data_ref);
const auto buffer = CryptographicBuffer::CreateFromByteArray(data_ref);
const auto decoded = CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, buffer);
auto blob = get_context().CreateObject(JSExport<Titanium::Blob>::Class()).CallAsConstructor();
auto blob_ptr = blob.GetPrivate<Titanium::Blob>();
blob_ptr->construct(data);
args.SetProperty("stringData", ctx.CreateString(TitaniumWindows::Utility::ConvertUTF8String(decoded)));
args.SetProperty("bytesData", blob);
} else {
args.SetProperty("stringData", ctx.CreateString(""));
args.SetProperty("bytesData", ctx.CreateNull());
}
args.SetProperty("address", ctx.CreateString(TitaniumWindows::Utility::ConvertUTF8String(e->RemoteAddress->DisplayName)));
args.SetProperty("port", ctx.CreateString(TitaniumWindows::Utility::ConvertUTF8String(e->RemotePort)));
callback({ args }, get_object());
}
} catch (Platform::COMException^ e) {
error(TitaniumWindows::Utility::ConvertUTF8String(e->Message));
} catch (...) {
error("Ti.Network.UDP.data: Unknown error");
}
});
}
});
}
void UDP::start(const std::uint32_t& port, const std::string& host) TITANIUM_NOEXCEPT
{
if (socket__) {
port__ = port;
host__ = host;
Platform::String^ hostname = TitaniumWindows::Utility::ConvertString(host);
const auto portname = TitaniumWindows::Utility::ConvertString(std::to_string(port));
if (host.empty()) {
const auto hostnames = Connectivity::NetworkInformation::GetHostNames();
if (hostnames->Size > 0) {
hostname = hostnames->GetAt(0)->CanonicalName;
}
}
JSValueProtect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
concurrency::create_task(socket__->BindEndpointAsync(ref new HostName(hostname), portname)).then([this, hostname, port](concurrency::task<void> task) {
try {
task.get();
if (started__.IsObject()) {
TitaniumWindows::Utility::RunOnUIThread([this, hostname, port]() {
auto callback = static_cast<JSObject>(started__);
if (callback.IsFunction()) {
const auto ctx = get_context();
auto args = ctx.CreateObject();
args.SetProperty("address", ctx.CreateString(TitaniumWindows::Utility::ConvertUTF8String(hostname)));
args.SetProperty("port", ctx.CreateNumber(port));
callback({ args }, get_object());
}
JSValueUnprotect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
});
}
} catch (Platform::COMException^ e) {
error(TitaniumWindows::Utility::ConvertUTF8String(e->Message));
JSValueUnprotect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
} catch (...) {
error("Ti.Network.UDP.start: Unknown error");
JSValueUnprotect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
}
});
}
}
void UDP::stop() TITANIUM_NOEXCEPT
{
#if defined(IS_WINDOWS_10)
if (socket__) {
concurrency::create_task(socket__->CancelIOAsync()).then([this](concurrency::task<void> task) {
try {
task.get();
} catch (...) {
// do nothing
}
socket__ = nullptr;
});
}
#else
socket__ = nullptr;
#endif
}
void UDP::sendString(const std::uint32_t& port, const std::string& host, const std::string& str) TITANIUM_NOEXCEPT
{
const auto source = TitaniumWindows::Utility::ConvertUTF8String(str);
const auto buffer = CryptographicBuffer::ConvertStringToBinary(source, BinaryStringEncoding::Utf8);
const auto data = TitaniumWindows::Utility::GetContentFromBuffer(buffer);
sendBytes(port, host, data);
}
void UDP::sendBytes(const std::uint32_t& port, const std::string& host, std::vector<std::uint8_t> data) TITANIUM_NOEXCEPT
{
if (socket__) {
const auto hostname = ref new HostName(TitaniumWindows::Utility::ConvertString(host));
const auto portname = TitaniumWindows::Utility::ConvertString(std::to_string(port));
JSValueProtect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
concurrency::create_task(socket__->ConnectAsync(hostname, portname)).then([this, data](concurrency::task<void> task) {
try {
task.get();
const auto writer = ref new DataWriter(socket__->OutputStream);
std::vector<std::uint8_t> read_data = const_cast<std::vector<std::uint8_t>&>(data);
writer->WriteBytes(::Platform::ArrayReference<std::uint8_t>(&read_data[0], static_cast<std::uint32_t>(read_data.size())));
concurrency::create_task(writer->StoreAsync()).then([this, writer](concurrency::task<unsigned int> task) {
try {
task.get();
} catch (Platform::COMException^ e) {
error(TitaniumWindows::Utility::ConvertUTF8String(e->Message));
} catch (...) {
error("Ti.Network.UDP.sendByte: Unknown error");
}
return writer->FlushAsync();
}).then([this](concurrency::task<bool> task) {
try {
task.get();
} catch (Platform::COMException^ e) {
error(TitaniumWindows::Utility::ConvertUTF8String(e->Message));
} catch (...) {
error("Ti.Network.UDP.sendByte: Unknown error");
}
JSValueUnprotect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
});
} catch (Platform::COMException^ e) {
error(TitaniumWindows::Utility::ConvertUTF8String(e->Message));
JSValueUnprotect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
} catch (...) {
error("Ti.Network.UDP.sendByte: Unknown error");
JSValueUnprotect(static_cast<JSContextRef>(get_context()), static_cast<JSValueRef>(get_object()));
}
});
}
}
void UDP::error(const std::string& message) TITANIUM_NOEXCEPT
{
try {
if (error__.IsObject()) {
TitaniumWindows::Utility::RunOnUIThread([this, message]() {
auto callback = static_cast<JSObject>(error__);
if (callback.IsFunction()) {
const auto ctx = get_context();
auto args = get_context().CreateObject();
args.SetProperty("code", ctx.CreateNumber(-1));
args.SetProperty("error", ctx.CreateString(message));
args.SetProperty("success", ctx.CreateBoolean(false));
callback({ args }, get_object());
}
});
}
} catch (...) {
// do nothing...
}
}
}
}
}
| 38.370213 | 157 | 0.639792 | appcelerator |
8d1a59c4632d463f2ba79946c7d246130b41d12c | 57,743 | cpp | C++ | fsck/source/modes/ModeCheckFS.cpp | TomatoYoung/beegfs | edf287940175ecded493183209719d2d90d45374 | [
"BSD-3-Clause"
] | null | null | null | fsck/source/modes/ModeCheckFS.cpp | TomatoYoung/beegfs | edf287940175ecded493183209719d2d90d45374 | [
"BSD-3-Clause"
] | null | null | null | fsck/source/modes/ModeCheckFS.cpp | TomatoYoung/beegfs | edf287940175ecded493183209719d2d90d45374 | [
"BSD-3-Clause"
] | null | null | null | #include "ModeCheckFS.h"
#include <common/toolkit/DisposalCleaner.h>
#include <common/toolkit/ListTk.h>
#include <common/toolkit/UnitTk.h>
#include <common/toolkit/UiTk.h>
#include <common/toolkit/ZipIterator.h>
#include <components/DataFetcher.h>
#include <components/worker/RetrieveChunksWork.h>
#include <net/msghelpers/MsgHelperRepair.h>
#include <toolkit/DatabaseTk.h>
#include <toolkit/FsckTkEx.h>
#include <program/Program.h>
#include <ftw.h>
#include <boost/lexical_cast.hpp>
template<unsigned Actions>
UserPrompter::UserPrompter(const FsckRepairAction (&possibleActions)[Actions],
FsckRepairAction defaultRepairAction)
: askForAction(true), possibleActions(possibleActions, possibleActions + Actions),
repairAction(FsckRepairAction_UNDEFINED)
{
if(Program::getApp()->getConfig()->getReadOnly() )
askForAction = false;
else
if(Program::getApp()->getConfig()->getAutomatic() )
{
askForAction = false;
repairAction = defaultRepairAction;
}
}
FsckRepairAction UserPrompter::chooseAction(const std::string& prompt)
{
if(askForAction)
FsckTkEx::fsckOutput("> " + prompt, OutputOptions_LINEBREAK | OutputOptions_NOLOG);
FsckTkEx::fsckOutput("> " + prompt, OutputOptions_NOSTDOUT);
while(askForAction)
{
for(size_t i = 0; i < possibleActions.size(); i++)
{
FsckTkEx::fsckOutput(
" " + StringTk::uintToStr(i + 1) + ") "
+ FsckTkEx::getRepairActionDesc(possibleActions[i]), OutputOptions_NOLOG |
OutputOptions_LINEBREAK);
}
for(size_t i = 0; i < possibleActions.size(); i++)
{
FsckTkEx::fsckOutput(
" " + StringTk::uintToStr(i + possibleActions.size() + 1) + ") "
+ FsckTkEx::getRepairActionDesc(possibleActions[i]) + " (apply for all)",
OutputOptions_NOLOG | OutputOptions_LINEBREAK);
}
std::string inputStr;
getline(std::cin, inputStr);
unsigned input = StringTk::strToUInt(inputStr);
if( (input > 0) && (input <= possibleActions.size() ) )
{
// user chose for this error
repairAction = possibleActions[input - 1];
break;
}
if( (input > possibleActions.size() ) && (input <= possibleActions.size() * 2) )
{
// user chose for all errors => do not ask again
askForAction = false;
repairAction = possibleActions[input - possibleActions.size() - 1];
break;
}
}
FsckTkEx::fsckOutput(" - [ra: " + FsckTkEx::getRepairActionDesc(repairAction, true) + "]",
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
return repairAction;
}
static FhgfsOpsErr handleDisposalItem(Node& owner, const std::string& entryID,
const bool isMirrored)
{
FhgfsOpsErr err = DisposalCleaner::unlinkFile(owner, entryID, isMirrored);
if (err == FhgfsOpsErr_INUSE)
return FhgfsOpsErr_SUCCESS;
else
return err;
}
ModeCheckFS::ModeCheckFS()
: log("ModeCheckFS")
{
}
ModeCheckFS::~ModeCheckFS()
{
}
void ModeCheckFS::printHelp()
{
std::cout <<
"MODE ARGUMENTS:\n"
" Optional:\n"
" --readOnly Check only, skip repairs.\n"
" --runOffline Run in offline mode, which disables the modification\n"
" logging. Use this only if you are sure there is no user\n"
" access to the file system while the check is running.\n"
" --automatic Do not prompt for repair actions and automatically use\n"
" reasonable default actions.\n"
" --noFetch Do not build a new database from the servers and\n"
" instead work on an existing database (e.g. from a\n"
" previous read-only run).\n"
" --quotaEnabled Enable checks for quota support.\n"
" --databasePath=<path> Path to store for the database files. On systems with \n"
" many files, the database can grow to a size of several \n"
" 100 GB.\n"
" (Default: " CONFIG_DEFAULT_DBPATH ")\n"
" --overwriteDbFile Overwrite an existing database file without prompt.\n"
" --ignoreDBDiskSpace Ignore free disk space check for database file.\n"
" --logOutFile=<path> Path to the fsck output file, which contains a copy of\n"
" the console output.\n"
" (Default: " CONFIG_DEFAULT_OUTFILE ")\n"
" --logStdFile=<path> Path to the program error log file, which contains e.g.\n"
" network error messages.\n"
" (Default: " CONFIG_DEFAULT_LOGFILE ")\n"
" --forceRestart Restart check even though another instance seems to be running.\n"
" Use only if a previous run was aborted, and make sure no other\n"
" fsck is running on the same file system at the same time.\n"
"\n"
"USAGE:\n"
" This mode performs a full check and optional repair of a BeeGFS file system\n"
" instance by building a database of the current file system contents on the\n"
" local machine.\n"
"\n"
" The fsck gathers information from all BeeGFS server daemons in parallel through\n"
" their configured network interfaces. All server components of the file\n"
" system have to be running to start a check.\n"
"\n"
" If the fsck is running with the \"--runoffline\" argument, users may not\n"
" access the file system during a run (otherwise false errors might be reported).\n"
"\n"
" Example: Check for errors, but skip repairs\n"
" $ beegfs-fsck --checkfs --readonly\n";
std::cout << std::flush;
}
int ModeCheckFS::execute()
{
App* app = Program::getApp();
Config *cfg = app->getConfig();
std::string databasePath = cfg->getDatabasePath();
if ( this->checkInvalidArgs(cfg->getUnknownConfigArgs()) )
return APPCODE_INVALID_CONFIG;
FsckTkEx::printVersionHeader(false);
printHeaderInformation();
if (cfg->getNoFetch() && !Program::getApp()->getConfig()->getReadOnly()) {
FsckTkEx::fsckOutput(
" WARNING: RISK OF DATA LOSS!\n"
" NEVER USE THE SAME DATABASE TWICE!\n\n"
"After running fsck, any database obtained previously no longer matches the state\n"
"of the filesystem. A new database MUST be obtained before running fsck again.\n\n"
"You are seeing this warning because you are using the option --nofetch.",
OutputOptions_DOUBLELINEBREAK | OutputOptions_ADDLINEBREAKBEFORE);
if (!uitk::userYNQuestion("Do you wish to continue?"))
return APPCODE_USER_ABORTED;
}
if ( !FsckTkEx::checkReachability() )
return APPCODE_COMMUNICATION_ERROR;
if (!FsckTkEx::checkConsistencyStates())
{
FsckTkEx::fsckOutput("At least one meta or storage target is in NEEDS_RESYNC state. "
"To prevent interference between fsck and resync operations, fsck will abort now. "
"Please make sure that no resyncs are currently pending or running.",
OutputOptions_DOUBLELINEBREAK | OutputOptions_ADDLINEBREAKBEFORE);
return APPCODE_RUNTIME_ERROR;
}
if(cfg->getNoFetch() )
{
try {
this->database.reset(new FsckDB(databasePath + "/fsckdb", cfg->getTuneDbFragmentSize(),
cfg->getTuneDentryCacheSize(), false) );
} catch (const FragmentDoesNotExist& e) {
std::string err = "Database was found to be incomplete in path " + databasePath;
log.logErr(err);
FsckTkEx::fsckOutput(err);
return APPCODE_RUNTIME_ERROR;
}
}
else
{
int initDBRes = initDatabase();
if (initDBRes)
return initDBRes;
disposeUnusedFiles();
boost::scoped_ptr<ModificationEventHandler> modificationEventHandler;
if (!cfg->getRunOffline())
{
modificationEventHandler.reset(
new ModificationEventHandler(*this->database->getModificationEventsTable() ) );
modificationEventHandler->start();
Program::getApp()->setModificationEventHandler(modificationEventHandler.get() );
// start modification logging
auto startLogRes = FsckTkEx::startModificationLogging(app->getMetaNodes(),
app->getLocalNode(), cfg->getForceRestart());
if (startLogRes != FhgfsOpsErr_SUCCESS)
{
std::string errStr;
switch (startLogRes)
{
case FhgfsOpsErr_INUSE:
errStr = "Another instance of beegfs-fsck is still running or was aborted. "
"Cannot start a new one unless --forceRestart command line switch is used. "
"Do this only after making sure there is no other instance of beefs-fsck "
"running.";
// stop the modification event handler
Program::getApp()->setModificationEventHandler(NULL);
modificationEventHandler->selfTerminate();
modificationEventHandler->join();
break;
default:
errStr = "Unable to start file system modification logging. "
"Fsck cannot proceed.";
}
log.logErr(errStr);
FsckTkEx::fsckOutput(errStr);
return APPCODE_RUNTIME_ERROR;
}
}
FhgfsOpsErr gatherDataRes = gatherData(cfg->getForceRestart());
if (!cfg->getRunOffline())
{
// stop modification logging
bool eventLoggingOK = FsckTkEx::stopModificationLogging(app->getMetaNodes());
// stop mod event handler (to make it flush for the last time
Program::getApp()->setModificationEventHandler(NULL);
modificationEventHandler->selfTerminate();
modificationEventHandler->join();
// if event logging is not OK (i.e. that not all events might have been processed), go
// into read-only mode
if ( !eventLoggingOK )
{
Program::getApp()->getConfig()->disableAutomaticRepairMode();
Program::getApp()->getConfig()->setReadOnly();
FsckTkEx::fsckOutput("-----",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"WARNING: Fsck did not get all modification events from metadata servers.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"For instance, this might have happened due to network timeouts.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput(
"This means beegfs-fsck is not aware of all changes in the filesystem and it is "
"not safe to execute repair actions. "
"In the worst case executing repair actions can result in data loss.",
OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
FsckTkEx::fsckOutput(
"Thus, read-only mode was automatically enabled. "
"You can still force repair by running beegfs-fsck again on the existing "
"database with the -noFetch option.",
OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
FsckTkEx::fsckOutput("Please press any key to continue.",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
FsckTkEx::fsckOutput("-----", OutputOptions_FLUSH | OutputOptions_DOUBLELINEBREAK);
std::cin.get();
}
}
if (gatherDataRes != FhgfsOpsErr_SUCCESS)
{
std::string errStr;
switch (gatherDataRes)
{
case FhgfsOpsErr_INUSE:
errStr = "Another instance of beegfs-fsck is still running or was aborted. "
"Cannot start a new one unless --forceRestart command line switch is used. "
"Do this only after making sure there is no other instance of beefs-fsck "
"running.";
break;
default:
errStr = "An error occured while fetching data from servers. Fsck cannot proceed. "
"Please see log file for more information.";
}
log.logErr(errStr);
FsckTkEx::fsckOutput(errStr);
return APPCODE_RUNTIME_ERROR;
}
}
checkAndRepair();
return APPCODE_NO_ERROR;
}
/*
* initializes the database, this is done here and not inside the main app, because we do not want
* it to effect the help modes; DB file shall only be created if user really runs a check
*
* @return integer value symbolizing an appcode
*/
int ModeCheckFS::initDatabase()
{
Config* cfg = Program::getApp()->getConfig();
// create the database path
Path dbPath(cfg->getDatabasePath() + "/fsckdb");
if ( !StorageTk::createPathOnDisk(dbPath, false) )
{
FsckTkEx::fsckOutput("Could not create path for database files: " +
dbPath.str());
return APPCODE_INITIALIZATION_ERROR;
}
// check disk space
if ( !FsckTkEx::checkDiskSpace(dbPath) )
return APPCODE_INITIALIZATION_ERROR;
// check if DB file path already exists and is not empty
if ( StorageTk::pathExists(dbPath.str())
&& StorageTk::pathHasChildren(dbPath.str()) && (!cfg->getOverwriteDbFile()) )
{
FsckTkEx::fsckOutput("The database path already exists: " + dbPath.str());
FsckTkEx::fsckOutput("If you continue now any existing database files in that path will be "
"deleted.");
std::string input;
while (input.size() != 1 || !strchr("YyNn", input[0]))
{
FsckTkEx::fsckOutput("Do you want to continue? (Y/N)");
std::getline(std::cin, input);
}
switch (input[0])
{
case 'Y':
case 'y':
break; // just do nothing and go ahead
case 'N':
case 'n':
default:
// abort here
return APPCODE_USER_ABORTED;
}
}
struct ops
{
static int visit(const char* path, const struct stat*, int type, struct FTW* state)
{
if(state->level == 0)
return 0;
else
if(type == FTW_F || type == FTW_SL)
return ::unlink(path);
else
return ::rmdir(path);
}
};
int ftwRes = ::nftw(dbPath.str().c_str(), ops::visit, 10, FTW_DEPTH | FTW_PHYS);
if(ftwRes)
{
FsckTkEx::fsckOutput("Could not empty path for database files: " + dbPath.str() );
return APPCODE_INITIALIZATION_ERROR;
}
try {
this->database.reset(
new FsckDB(dbPath.str(), cfg->getTuneDbFragmentSize(),
cfg->getTuneDentryCacheSize(), true) );
} catch (const std::runtime_error& e) {
FsckTkEx::fsckOutput("Database " + dbPath.str() + " is corrupt");
return APPCODE_RUNTIME_ERROR;
}
return 0;
}
void ModeCheckFS::printHeaderInformation()
{
Config* cfg = Program::getApp()->getConfig();
// get the current time and create some nice output, so the user can see at which time the run
// was started (especially nice to find older runs in the log file)
time_t t;
time(&t);
std::string timeStr = std::string(ctime(&t));
FsckTkEx::fsckOutput(
"Started BeeGFS fsck in forward check mode [" + timeStr.substr(0, timeStr.length() - 1)
+ "]\nLog will be written to " + cfg->getLogStdFile() + "\nDatabase will be saved in "
+ cfg->getDatabasePath(), OutputOptions_LINEBREAK | OutputOptions_HEADLINE);
if (Program::getApp()->getMetaMirrorBuddyGroupMapper()->getSize() > 0)
{
FsckTkEx::fsckOutput(
"IMPORTANT NOTICE: The initiation of a repair action on a metadata mirror group "
"will temporarily set the consistency state of the secondary node to bad to prevent "
"interaction during the repair. After fsck finishes, it will set the states "
"of all affected nodes to needs-resync, so the repaired data will be synced from their "
"primary. \n\nIf beegfs-fsck is aborted prematurely, a resync needs to be initiated "
"manually so all targets are consistent (good) again." ,
OutputOptions_DOUBLELINEBREAK | OutputOptions_HEADLINE);
}
}
void ModeCheckFS::disposeUnusedFiles()
{
Config* cfg = Program::getApp()->getConfig();
if (cfg->getReadOnly() || cfg->getNoFetch())
return;
FsckTkEx::fsckOutput("Step 2: Delete unused files from disposal: ", OutputOptions_NONE);
using namespace std::placeholders;
uint64_t errors = 0;
DisposalCleaner dc(*Program::getApp()->getMetaMirrorBuddyGroupMapper());
dc.run(Program::getApp()->getMetaNodes()->referenceAllNodes(),
handleDisposalItem,
[&] (const auto&, const auto&) { errors += 1; });
if (errors > 0)
FsckTkEx::fsckOutput("Some files could not be deleted.");
else
FsckTkEx::fsckOutput("Finished.");
}
FhgfsOpsErr ModeCheckFS::gatherData(bool forceRestart)
{
FsckTkEx::fsckOutput("Step 3: Gather data from nodes: ", OutputOptions_DOUBLELINEBREAK);
DataFetcher dataFetcher(*this->database, forceRestart);
const FhgfsOpsErr retVal = dataFetcher.execute();
FsckTkEx::fsckOutput("", OutputOptions_LINEBREAK);
return retVal;
}
template<typename Obj, typename State>
int64_t ModeCheckFS::checkAndRepairGeneric(Cursor<Obj> cursor,
void (ModeCheckFS::*repair)(Obj&, State&), State& state)
{
int64_t errorCount = 0;
while(cursor.step() )
{
Obj* entry = cursor.get();
(this->*repair)(*entry, state);
errorCount++;
}
if(errorCount)
{
database->getDentryTable()->commitChanges();
database->getFileInodesTable()->commitChanges();
database->getDirInodesTable()->commitChanges();
database->getChunksTable()->commitChanges();
database->getContDirsTable()->commitChanges();
database->getFsIDsTable()->commitChanges();
FsckTkEx::fsckOutput(">>> Found " + StringTk::int64ToStr(errorCount)
+ " errors. Detailed information can also be found in "
+ Program::getApp()->getConfig()->getLogOutFile() + ".",
OutputOptions_DOUBLELINEBREAK);
}
else
{
FsckTkEx::fsckOutput(">>> None found", OutputOptions_FLUSH | OutputOptions_LINEBREAK);
}
return errorCount;
}
int64_t ModeCheckFS::checkAndRepairDanglingDentry()
{
FsckRepairAction fileActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEDENTRY,
};
FsckRepairAction dirActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEDENTRY,
FsckRepairAction_CREATEDEFAULTDIRINODE,
};
UserPrompter forFiles(fileActions, FsckRepairAction_DELETEDENTRY);
UserPrompter forDirs(dirActions, FsckRepairAction_CREATEDEFAULTDIRINODE);
std::pair<UserPrompter*, UserPrompter*> prompt(&forFiles, &forDirs);
FsckTkEx::fsckOutput("* Checking: Dangling directory entry ...",
OutputOptions_FLUSH |OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findDanglingDirEntries(),
&ModeCheckFS::repairDanglingDirEntry, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongInodeOwner()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CORRECTOWNER,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CORRECTOWNER);
FsckTkEx::fsckOutput("* Checking: Wrong owner node saved in inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findInodesWithWrongOwner(),
&ModeCheckFS::repairWrongInodeOwner, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongOwnerInDentry()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CORRECTOWNER,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CORRECTOWNER);
FsckTkEx::fsckOutput("* Checking: Dentry points to inode on wrong node ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findDirEntriesWithWrongOwner(),
&ModeCheckFS::repairWrongInodeOwnerInDentry, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedContDir()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CREATEDEFAULTDIRINODE,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CREATEDEFAULTDIRINODE);
FsckTkEx::fsckOutput("* Checking: Content directory without an inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedContDirs(),
&ModeCheckFS::repairOrphanedContDir, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedDirInode()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_LOSTANDFOUND,
};
UserPrompter prompt(possibleActions, FsckRepairAction_LOSTANDFOUND);
FsckTkEx::fsckOutput("* Checking: Dir inode without a dentry pointing to it (orphaned inode) ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
bool result = checkAndRepairGeneric(this->database->findOrphanedDirInodes(),
&ModeCheckFS::repairOrphanedDirInode, prompt);
releaseLostAndFound();
return result;
}
int64_t ModeCheckFS::checkAndRepairOrphanedFileInode()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEINODE,
//FsckRepairAction_LOSTANDFOUND,
};
UserPrompter prompt(possibleActions, FsckRepairAction_DELETEINODE);
FsckTkEx::fsckOutput("* Checking: File inode without a dentry pointing to it (orphaned inode) ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedFileInodes(),
&ModeCheckFS::repairOrphanedFileInode, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedChunk()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
};
UserPrompter prompt(possibleActions, FsckRepairAction_NOTHING);
RepairChunkState state = { &prompt, "", FsckRepairAction_UNDEFINED };
FsckTkEx::fsckOutput("* Checking: Chunk without an inode pointing to it (orphaned chunk) ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedChunks(),
&ModeCheckFS::repairOrphanedChunk, state);
}
int64_t ModeCheckFS::checkAndRepairMissingContDir()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_CREATECONTDIR,
};
UserPrompter prompt(possibleActions, FsckRepairAction_CREATECONTDIR);
FsckTkEx::fsckOutput("* Checking: Directory inode without a content directory ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findInodesWithoutContDir(),
&ModeCheckFS::repairMissingContDir, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongFileAttribs()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_UPDATEATTRIBS,
};
UserPrompter prompt(possibleActions, FsckRepairAction_UPDATEATTRIBS);
FsckTkEx::fsckOutput("* Checking: Attributes of file inode are wrong ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findWrongInodeFileAttribs(),
&ModeCheckFS::repairWrongFileAttribs, prompt);
}
int64_t ModeCheckFS::checkAndRepairWrongDirAttribs()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_UPDATEATTRIBS,
};
UserPrompter prompt(possibleActions, FsckRepairAction_UPDATEATTRIBS);
FsckTkEx::fsckOutput("* Checking: Attributes of dir inode are wrong ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findWrongInodeDirAttribs(),
&ModeCheckFS::repairWrongDirAttribs, prompt);
}
int64_t ModeCheckFS::checkAndRepairFilesWithMissingTargets()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETEFILE,
};
UserPrompter prompt(possibleActions, FsckRepairAction_NOTHING);
FsckTkEx::fsckOutput("* Checking: File has a missing target in stripe pattern ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(
this->database->findFilesWithMissingStripeTargets(
Program::getApp()->getTargetMapper(), Program::getApp()->getMirrorBuddyGroupMapper() ),
&ModeCheckFS::repairFileWithMissingTargets, prompt);
}
int64_t ModeCheckFS::checkAndRepairDirEntriesWithBrokeByIDFile()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_RECREATEFSID,
};
UserPrompter prompt(possibleActions, FsckRepairAction_RECREATEFSID);
FsckTkEx::fsckOutput("* Checking: Dentry-by-ID file is broken or missing ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findDirEntriesWithBrokenByIDFile(),
&ModeCheckFS::repairDirEntryWithBrokenByIDFile, prompt);
}
int64_t ModeCheckFS::checkAndRepairOrphanedDentryByIDFiles()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_RECREATEDENTRY,
};
UserPrompter prompt(possibleActions, FsckRepairAction_RECREATEDENTRY);
FsckTkEx::fsckOutput("* Checking: Dentry-by-ID file is present, but no corresponding dentry ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findOrphanedFsIDFiles(),
&ModeCheckFS::repairOrphanedDentryByIDFile, prompt);
}
int64_t ModeCheckFS::checkAndRepairChunksWithWrongPermissions()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_FIXPERMISSIONS,
};
UserPrompter prompt(possibleActions, FsckRepairAction_FIXPERMISSIONS);
FsckTkEx::fsckOutput("* Checking: Chunk has wrong permissions ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findChunksWithWrongPermissions(),
&ModeCheckFS::repairChunkWithWrongPermissions, prompt);
}
// no repair at the moment
int64_t ModeCheckFS::checkAndRepairChunksInWrongPath()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_MOVECHUNK,
};
UserPrompter prompt(possibleActions, FsckRepairAction_MOVECHUNK);
FsckTkEx::fsckOutput("* Checking: Chunk is saved in wrong path ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(this->database->findChunksInWrongPath(),
&ModeCheckFS::repairWrongChunkPath, prompt);
}
int64_t ModeCheckFS::checkDuplicateInodeIDs()
{
FsckTkEx::fsckOutput("* Checking: Duplicated inode IDs ... ",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findDuplicateInodeIDs(),
&ModeCheckFS::logDuplicateInodeID, dummy);
}
void ModeCheckFS::logDuplicateInodeID(checks::DuplicatedInode& dups, int&)
{
FsckTkEx::fsckOutput(">>> Found duplicated ID " + dups.first.str(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
for(const auto& it : dups.second)
{
FsckTkEx::fsckOutput(" * Found on " + std::string(it.second ? "buddy group " : "node ")
+ StringTk::uintToStr(it.first), OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
}
}
int64_t ModeCheckFS::checkDuplicateChunks()
{
FsckTkEx::fsckOutput("* Checking: Duplicated chunks ...", OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findDuplicateChunks(),
&ModeCheckFS::logDuplicateChunk, dummy);
}
void ModeCheckFS::logDuplicateChunk(std::list<FsckChunk>& dups, int&)
{
FsckTkEx::fsckOutput(">>> Found duplicated Chunks for ID " + dups.begin()->getID(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
for(std::list<FsckChunk>::iterator it = dups.begin(), end = dups.end();
it != end; ++it)
{
FsckTkEx::fsckOutput(" * Found on target " + StringTk::uintToStr(it->getTargetID() )
+ (it->getBuddyGroupID()
? ", buddy group " + StringTk::uintToStr(it->getBuddyGroupID() )
: "")
+ " in path " + it->getSavedPath()->str(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
}
}
int64_t ModeCheckFS::checkDuplicateContDirs()
{
FsckTkEx::fsckOutput("* Checking: Duplicated content directores ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findDuplicateContDirs(),
&ModeCheckFS::logDuplicateContDir, dummy);
}
void ModeCheckFS::logDuplicateContDir(std::list<db::ContDir>& dups, int&)
{
FsckTkEx::fsckOutput(">>> Found duplicated content directories for ID " + dups.front().id.str(),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
for (auto it = dups.begin(), end = dups.end(); it != end; ++it)
{
FsckTkEx::fsckOutput(" * Found on " +
std::string(it->isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(it->saveNodeID),
OutputOptions_LINEBREAK | OutputOptions_NOSTDOUT);
}
}
int64_t ModeCheckFS::checkMismirroredDentries()
{
FsckTkEx::fsckOutput("* Checking: Bad target mirror information in dentry ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findMismirroredDentries(),
&ModeCheckFS::logMismirroredDentry, dummy);
}
void ModeCheckFS::logMismirroredDentry(db::DirEntry& entry, int&)
{
FsckTkEx::fsckOutput(">>> Found mismirrored dentry " +
database->getDentryTable()->getNameOf(entry) + " on " +
(entry.isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(entry.saveNodeID) + " " + StringTk::uintToStr(entry.entryOwnerNodeID));
}
int64_t ModeCheckFS::checkMismirroredDirectories()
{
FsckTkEx::fsckOutput("* Checking: Bad content mirror information in dir inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findMismirroredDirectories(),
&ModeCheckFS::logMismirroredDirectory, dummy);
}
void ModeCheckFS::logMismirroredDirectory(db::DirInode& dir, int&)
{
FsckTkEx::fsckOutput(">>> Found mismirrored directory " + dir.id.str() + " on " +
(dir.isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(dir.saveNodeID));
;
}
int64_t ModeCheckFS::checkMismirroredFiles()
{
FsckTkEx::fsckOutput("* Checking: Bad content mirror information in file inode ...",
OutputOptions_FLUSH | OutputOptions_LINEBREAK);
int dummy = 0;
return checkAndRepairGeneric(this->database->findMismirroredFiles(),
&ModeCheckFS::logMismirroredFile, dummy);
}
void ModeCheckFS::logMismirroredFile(db::FileInode& file, int&)
{
FsckTkEx::fsckOutput(">>> Found mismirrored file " + file.id.str() + " on " +
std::string(file.isBuddyMirrored ? "buddy group " : "node ") +
StringTk::uintToStr(file.saveNodeID));
}
int64_t ModeCheckFS::checkAndRepairMalformedChunk()
{
FsckRepairAction possibleActions[] = {
FsckRepairAction_NOTHING,
FsckRepairAction_DELETECHUNK,
};
UserPrompter prompt(possibleActions, FsckRepairAction_DELETECHUNK);
FsckTkEx::fsckOutput("* Checking: Malformed chunk ...", OutputOptions_FLUSH | OutputOptions_LINEBREAK);
return checkAndRepairGeneric(Cursor<FsckChunk>(database->getMalformedChunksList()->cursor()),
&ModeCheckFS::repairMalformedChunk, prompt);
}
void ModeCheckFS::repairMalformedChunk(FsckChunk& chunk, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Chunk ID: " + chunk.getID() + " on " +
(chunk.getBuddyGroupID()
? "buddy group " + StringTk::uintToStr(chunk.getBuddyGroupID())
: "target " + StringTk::uintToStr(chunk.getTargetID())));
switch (action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETECHUNK: {
FhgfsOpsErr refErr;
NodeStore* storageNodeStore = Program::getApp()->getStorageNodes();
auto node = storageNodeStore->referenceNodeByTargetID(chunk.getTargetID(),
Program::getApp()->getTargetMapper(), &refErr);
if(!node)
{
FsckTkEx::fsckOutput("could not get storage target "
+ StringTk::uintToStr(chunk.getTargetID() ), OutputOptions_LINEBREAK);
return;
}
FsckChunkList chunks(1, chunk);
FsckChunkList failed;
MsgHelperRepair::deleteChunks(*node, &chunks, &failed);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::checkAndRepair()
{
FsckTkEx::fsckOutput("Step 4: Check for errors... ", OutputOptions_DOUBLELINEBREAK);
Config* cfg = Program::getApp()->getConfig();
int64_t errorCount = 0;
errorCount += checkDuplicateInodeIDs();
errorCount += checkDuplicateChunks();
errorCount += checkDuplicateContDirs();
errorCount += checkMismirroredDentries();
errorCount += checkMismirroredDirectories();
errorCount += checkMismirroredFiles();
if(errorCount)
{
FsckTkEx::fsckOutput("Found errors beegfs-fsck cannot fix. Please consult the log for "
"more information.", OutputOptions_LINEBREAK);
return;
}
errorCount += checkAndRepairMalformedChunk();
errorCount += checkAndRepairFilesWithMissingTargets();
errorCount += checkAndRepairOrphanedDentryByIDFiles();
errorCount += checkAndRepairDirEntriesWithBrokeByIDFile();
errorCount += checkAndRepairOrphanedChunk();
errorCount += checkAndRepairChunksInWrongPath();
errorCount += checkAndRepairWrongInodeOwner();
errorCount += checkAndRepairWrongOwnerInDentry();
errorCount += checkAndRepairOrphanedContDir();
errorCount += checkAndRepairOrphanedDirInode();
errorCount += checkAndRepairOrphanedFileInode();
errorCount += checkAndRepairDanglingDentry();
errorCount += checkAndRepairMissingContDir();
errorCount += checkAndRepairWrongFileAttribs();
errorCount += checkAndRepairWrongDirAttribs();
if ( cfg->getQuotaEnabled())
{
errorCount += checkAndRepairChunksWithWrongPermissions();
}
if ( cfg->getReadOnly() )
{
FsckTkEx::fsckOutput(
"Found " + StringTk::int64ToStr(errorCount)
+ " errors. Detailed information can also be found in "
+ Program::getApp()->getConfig()->getLogOutFile() + ".",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_LINEBREAK);
return;
}
for (auto it = secondariesSetBad.begin(); it != secondariesSetBad.end(); ++it)
{
auto secondary = *it;
FsckTkEx::fsckOutput(">>> Setting metadata node " + StringTk::intToStr(secondary.val())
+ " to needs-resync", OutputOptions_LINEBREAK);
auto setRes = MsgHelperRepair::setNodeState(secondary, TargetConsistencyState_NEEDS_RESYNC);
if (setRes != FhgfsOpsErr_SUCCESS)
FsckTkEx::fsckOutput("Failed: " + boost::lexical_cast<std::string>(setRes),
OutputOptions_LINEBREAK);
}
if(errorCount > 0)
FsckTkEx::fsckOutput(">>> Found " + StringTk::int64ToStr(errorCount) + " errors <<< ",
OutputOptions_ADDLINEBREAKBEFORE | OutputOptions_LINEBREAK);
}
//////////////////////////
// internals ///////
/////////////////////////
void ModeCheckFS::repairDanglingDirEntry(db::DirEntry& entry,
std::pair<UserPrompter*, UserPrompter*>& prompt)
{
FsckDirEntry fsckEntry = entry;
FsckRepairAction action;
std::string promptText = "Entry ID: " + fsckEntry.getID() + "; Path: " +
this->database->getDentryTable()->getPathOf(entry) + "; " +
(entry.isBuddyMirrored ? "Buddy group: " : "Node: ") +
StringTk::uintToStr(entry.saveNodeID);
if(fsckEntry.getEntryType() == FsckDirEntryType_DIRECTORY)
action = prompt.second->chooseAction(promptText);
else
action = prompt.first->chooseAction(promptText);
fsckEntry.setName(this->database->getDentryTable()->getNameOf(entry) );
FsckDirEntryList entries(1, fsckEntry);
FsckDirEntryList failedEntries;
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETEDENTRY: {
MsgHelperRepair::deleteDanglingDirEntries(fsckEntry.getSaveNodeID(),
fsckEntry.getIsBuddyMirrored(), &entries, &failedEntries,
secondariesSetBad);
if(failedEntries.empty() )
{
this->database->getDentryTable()->remove(entries);
this->deleteFsIDsFromDB(entries);
}
break;
}
case FsckRepairAction_CREATEDEFAULTDIRINODE: {
FsckDirInodeList createdInodes;
// create mirrored inodes iff the dentry was mirrored. if a contdir with the same id exists,
// a previous check will have created an inode for it, leaving this dentry not dangling.
MsgHelperRepair::createDefDirInodes(fsckEntry.getSaveNodeID(), fsckEntry.getIsBuddyMirrored(),
{std::make_tuple(fsckEntry.getID(), fsckEntry.getIsBuddyMirrored())}, &createdInodes,
secondariesSetBad);
this->database->getDirInodesTable()->insert(createdInodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongInodeOwner(FsckDirInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Entry ID: " + inode.getID()
+ "; Path: "
+ this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(inode.getID() ) ) );
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CORRECTOWNER: {
inode.setOwnerNodeID(inode.getSaveNodeID() );
FsckDirInodeList inodes(1, inode);
FsckDirInodeList failed;
MsgHelperRepair::correctInodeOwners(inode.getSaveNodeID(), inode.getIsBuddyMirrored(),
&inodes, &failed, secondariesSetBad);
if(failed.empty() )
this->database->getDirInodesTable()->update(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongInodeOwnerInDentry(std::pair<db::DirEntry, NumNodeID>& error,
UserPrompter& prompt)
{
FsckDirEntry fsckEntry = error.first;
FsckRepairAction action = prompt.chooseAction("File ID: " + fsckEntry.getID()
+ "; Path: " + this->database->getDentryTable()->getPathOf(error.first) );
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CORRECTOWNER: {
fsckEntry.setName(this->database->getDentryTable()->getNameOf(error.first) );
FsckDirEntryList dentries(1, fsckEntry);
NumNodeIDList owners(1, NumNodeID(error.second) );
FsckDirEntryList failed;
MsgHelperRepair::correctInodeOwnersInDentry(fsckEntry.getSaveNodeID(),
fsckEntry.getIsBuddyMirrored(), &dentries, &owners, &failed,
secondariesSetBad);
if(failed.empty() )
this->database->getDentryTable()->updateFieldsExceptParent(dentries);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedDirInode(FsckDirInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Directory ID: " + inode.getID() + "; " +
(inode.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + inode.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_LOSTANDFOUND: {
if(!ensureLostAndFoundExists() )
{
log.logErr("Orphaned dir inodes could not be linked to lost+found, because lost+found "
"directory could not be created");
return;
}
FsckDirInodeList inodes(1, inode);
FsckDirEntryList created;
FsckDirInodeList failed;
MsgHelperRepair::linkToLostAndFound(*this->lostAndFoundNode, &this->lostAndFoundInfo, &inodes,
&failed, &created, secondariesSetBad);
if(failed.empty() )
this->database->getDentryTable()->insert(created);
// on server side, each dentry also created a dentry-by-ID file
FsckFsIDList createdFsIDs;
for(FsckDirEntryListIter iter = created.begin(); iter != created.end(); iter++)
{
FsckFsID fsID(iter->getID(), iter->getParentDirID(), iter->getSaveNodeID(),
iter->getSaveDevice(), iter->getSaveInode(), iter->getIsBuddyMirrored());
createdFsIDs.push_back(fsID);
}
this->database->getFsIDsTable()->insert(createdFsIDs);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedFileInode(FsckFileInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("File ID: " + inode.getID() + "; " +
(inode.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + inode.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETEINODE: {
FsckFileInodeList inodes(1, inode);
StringList failed;
MsgHelperRepair::deleteFileInodes(inode.getSaveNodeID(), inode.getIsBuddyMirrored(), inodes,
failed, secondariesSetBad);
if(failed.empty() )
this->database->getFileInodesTable()->remove(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedChunk(FsckChunk& chunk, RepairChunkState& state)
{
// ask for repair action only once per chunk id, not once per chunk id and node
if(state.lastID != chunk.getID() )
state.lastChunkAction = state.prompt->chooseAction("Chunk ID: " + chunk.getID() + " on " +
(chunk.getBuddyGroupID()
? "buddy group " + StringTk::uintToStr(chunk.getBuddyGroupID())
: "target " + StringTk::uintToStr(chunk.getTargetID())));
state.lastID = chunk.getID();
switch(state.lastChunkAction)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_DELETECHUNK: {
FhgfsOpsErr refErr;
NodeStore* storageNodeStore = Program::getApp()->getStorageNodes();
auto node = storageNodeStore->referenceNodeByTargetID(chunk.getTargetID(),
Program::getApp()->getTargetMapper(), &refErr);
if(!node)
{
FsckTkEx::fsckOutput("could not get storage target "
+ StringTk::uintToStr(chunk.getTargetID() ), OutputOptions_LINEBREAK);
return;
}
FsckChunkList chunks(1, chunk);
FsckChunkList failed;
MsgHelperRepair::deleteChunks(*node, &chunks, &failed);
if(failed.empty() )
this->database->getChunksTable()->remove(
{db::EntryID::fromStr(chunk.getID()), chunk.getTargetID(), chunk.getBuddyGroupID()});
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairMissingContDir(FsckDirInode& inode, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Directory ID: " + inode.getID() +
"; Path: " +
this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(inode.getID())) + "; " +
(inode.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + inode.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CREATECONTDIR: {
FsckDirInodeList inodes(1, inode);
StringList failed;
MsgHelperRepair::createContDirs(inode.getSaveNodeID(), inode.getIsBuddyMirrored(), &inodes,
&failed, secondariesSetBad);
if(failed.empty() )
{
// create a list of cont dirs from dir inode
FsckContDirList contDirs(1,
FsckContDir(inode.getID(), inode.getSaveNodeID(), inode.getIsBuddyMirrored()));
this->database->getContDirsTable()->insert(contDirs);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedContDir(FsckContDir& dir, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Directory ID: " + dir.getID() + "; " +
(dir.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + dir.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_CREATEDEFAULTDIRINODE: {
FsckDirInodeList createdInodes;
MsgHelperRepair::createDefDirInodes(dir.getSaveNodeID(), dir.getIsBuddyMirrored(),
{std::make_tuple(dir.getID(), dir.getIsBuddyMirrored())}, &createdInodes,
secondariesSetBad);
this->database->getDirInodesTable()->insert(createdInodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongFileAttribs(std::pair<FsckFileInode, checks::InodeAttribs>& error,
UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("File ID: " + error.first.getID() + "; Path: " +
this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(error.first.getID())) +
"; " + (error.first.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") +
error.first.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_UPDATEATTRIBS: {
error.first.setFileSize(error.second.size);
error.first.setNumHardLinks(error.second.nlinks);
FsckFileInodeList inodes(1, error.first);
FsckFileInodeList failed;
MsgHelperRepair::updateFileAttribs(error.first.getSaveNodeID(),
error.first.getIsBuddyMirrored(), &inodes, &failed, secondariesSetBad);
if(failed.empty() )
this->database->getFileInodesTable()->update(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongDirAttribs(std::pair<FsckDirInode, checks::InodeAttribs>& error,
UserPrompter& prompt)
{
std::string filePath = this->database->getDentryTable()->getPathOf(
db::EntryID::fromStr(error.first.getID() ) );
FsckRepairAction action = prompt.chooseAction("Directory ID: " + error.first.getID() +
"; Path: " + filePath + "; " +
(error.first.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") +
error.first.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_UPDATEATTRIBS: {
FsckDirInodeList inodes(1, error.first);
FsckDirInodeList failed;
// update the file attribs in the inode objects (even though they may not be used
// on the server side, we need updated values here to update the DB
error.first.setSize(error.second.size);
error.first.setNumHardLinks(error.second.nlinks);
MsgHelperRepair::updateDirAttribs(error.first.getSaveNodeID(),
error.first.getIsBuddyMirrored(), &inodes, &failed, secondariesSetBad);
if(failed.empty() )
this->database->getDirInodesTable()->update(inodes);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairFileWithMissingTargets(db::DirEntry& entry, UserPrompter& prompt)
{
FsckDirEntry fsckEntry = entry;
FsckRepairAction action = prompt.chooseAction("Entry ID: " + fsckEntry.getID() +
"; Path: " + this->database->getDentryTable()->getPathOf(entry) + "; " +
(entry.isBuddyMirrored ? "Buddy group: " : "Node: ") +
StringTk::uintToStr(entry.entryOwnerNodeID));
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
return;
case FsckRepairAction_DELETEFILE: {
fsckEntry.setName(this->database->getDentryTable()->getNameOf(entry) );
FsckDirEntryList dentries(1, fsckEntry);
FsckDirEntryList failed;
MsgHelperRepair::deleteFiles(fsckEntry.getSaveNodeID(), fsckEntry.getIsBuddyMirrored(),
&dentries, &failed);
if(failed.empty() )
this->deleteFilesFromDB(dentries);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairDirEntryWithBrokenByIDFile(db::DirEntry& entry, UserPrompter& prompt)
{
FsckDirEntry fsckEntry = entry;
FsckRepairAction action = prompt.chooseAction("Entry ID: " + fsckEntry.getID() +
"; Path: " + this->database->getDentryTable()->getPathOf(entry) + "; " +
(entry.isBuddyMirrored ? "Buddy group: " : "Node: ") +
StringTk::uintToStr(entry.entryOwnerNodeID));
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_RECREATEFSID: {
fsckEntry.setName(this->database->getDentryTable()->getNameOf(entry) );
FsckDirEntryList dentries(1, fsckEntry);
FsckDirEntryList failed;
MsgHelperRepair::recreateFsIDs(fsckEntry.getSaveNodeID(), fsckEntry.getIsBuddyMirrored(),
&dentries, &failed, secondariesSetBad);
if(failed.empty() )
{
// create a FsID list from the dentry
FsckFsIDList idList(1,
FsckFsID(fsckEntry.getID(), fsckEntry.getParentDirID(), fsckEntry.getSaveNodeID(),
fsckEntry.getSaveDevice(), fsckEntry.getSaveInode(),
fsckEntry.getIsBuddyMirrored()));
this->database->getFsIDsTable()->insert(idList);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairOrphanedDentryByIDFile(FsckFsID& id, UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction(
"Entry ID: " + id.getID() +
"; Path: " +
this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(id.getID())) + "; " +
(id.getIsBuddyMirrored() ? "Buddy group: " : "Node: ") + id.getSaveNodeID().str());
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_RECREATEDENTRY: {
FsckFsIDList fsIDs(1, id);
FsckFsIDList failed;
FsckDirEntryList createdDentries;
FsckFileInodeList createdInodes;
MsgHelperRepair::recreateDentries(id.getSaveNodeID(), id.getIsBuddyMirrored(), &fsIDs,
&failed, &createdDentries, &createdInodes, secondariesSetBad);
if(failed.empty() )
{
this->database->getDentryTable()->insert(createdDentries);
this->database->getFileInodesTable()->insert(createdInodes);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairChunkWithWrongPermissions(std::pair<FsckChunk, FsckFileInode>& error,
UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction(
"Chunk ID: " + error.first.getID() + "; "
+ (error.first.getBuddyGroupID()
? "Buddy group: " + StringTk::uintToStr(error.first.getBuddyGroupID())
: "Target: " + StringTk::uintToStr(error.first.getTargetID()))
+ "; File path: "
+ this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(error.first.getID())));
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_FIXPERMISSIONS: {
NodeStore* nodeStore = Program::getApp()->getStorageNodes();
TargetMapper* targetMapper = Program::getApp()->getTargetMapper();
// we will need the PathInfo later to send the SetAttr message and we don't have it in the
// chunk
PathInfoList pathInfoList(1, *error.second.getPathInfo() );
// set correct permissions
error.first.setUserID(error.second.getUserID() );
error.first.setGroupID(error.second.getGroupID() );
FsckChunkList chunkList(1, error.first);
FsckChunkList failed;
auto storageNode = nodeStore->referenceNode(
targetMapper->getNodeID(error.first.getTargetID() ) );
MsgHelperRepair::fixChunkPermissions(*storageNode, chunkList, pathInfoList, failed);
if(failed.empty() )
this->database->getChunksTable()->update(chunkList);
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::repairWrongChunkPath(std::pair<FsckChunk, FsckFileInode>& error,
UserPrompter& prompt)
{
FsckRepairAction action = prompt.chooseAction("Entry ID: " + error.first.getID()
+ "; " + (error.first.getBuddyGroupID()
? "Group: " + StringTk::uintToStr(error.first.getBuddyGroupID())
: "Target: " + StringTk::uintToStr(error.first.getTargetID()))
+ "; Chunk path: " + error.first.getSavedPath()->str()
+ "; File path: "
+ this->database->getDentryTable()->getPathOf(db::EntryID::fromStr(error.first.getID() ) ) );
switch(action)
{
case FsckRepairAction_UNDEFINED:
case FsckRepairAction_NOTHING:
break;
case FsckRepairAction_MOVECHUNK: {
NodeStore* nodeStore = Program::getApp()->getStorageNodes();
TargetMapper* targetMapper = Program::getApp()->getTargetMapper();
auto storageNode = nodeStore->referenceNode(
targetMapper->getNodeID(error.first.getTargetID() ) );
std::string moveToPath = DatabaseTk::calculateExpectedChunkPath(error.first.getID(),
error.second.getPathInfo()->getOrigUID(),
error.second.getPathInfo()->getOrigParentEntryID(),
error.second.getPathInfo()->getFlags() );
if(MsgHelperRepair::moveChunk(*storageNode, error.first, moveToPath, false) )
{
FsckChunkList chunks(1, error.first);
this->database->getChunksTable()->update(chunks);
break;
}
// chunk file exists at the correct location
FsckTkEx::fsckOutput("Chunk file for " + error.first.getID()
+ " already exists at the correct location. ", OutputOptions_NONE);
if(Program::getApp()->getConfig()->getAutomatic() )
{
FsckTkEx::fsckOutput("Will not attempt automatic repair.", OutputOptions_LINEBREAK);
break;
}
char chosen = 0;
while(chosen != 'y' && chosen != 'n')
{
FsckTkEx::fsckOutput("Move anyway? (y/n) ", OutputOptions_NONE);
std::string line;
std::getline(std::cin, line);
if(line.size() == 1)
chosen = line[0];
}
if(chosen != 'y')
break;
if(MsgHelperRepair::moveChunk(*storageNode, error.first, moveToPath, true) )
{
FsckChunkList chunks(1, error.first);
this->database->getChunksTable()->update(chunks);
}
else
{
FsckTkEx::fsckOutput("Repair failed, see log file for more details.",
OutputOptions_LINEBREAK);
}
break;
}
default:
throw std::runtime_error("bad repair action");
}
}
void ModeCheckFS::deleteFsIDsFromDB(FsckDirEntryList& dentries)
{
// create the fsID list
FsckFsIDList fsIDs;
for ( FsckDirEntryListIter iter = dentries.begin(); iter != dentries.end(); iter++ )
{
FsckFsID fsID(iter->getID(), iter->getParentDirID(), iter->getSaveNodeID(),
iter->getSaveDevice(), iter->getSaveInode(), iter->getIsBuddyMirrored());
fsIDs.push_back(fsID);
}
this->database->getFsIDsTable()->remove(fsIDs);
}
void ModeCheckFS::deleteFilesFromDB(FsckDirEntryList& dentries)
{
for ( FsckDirEntryListIter dentryIter = dentries.begin(); dentryIter != dentries.end();
dentryIter++ )
{
std::pair<bool, db::FileInode> inode = this->database->getFileInodesTable()->get(
dentryIter->getID() );
if(inode.first)
{
this->database->getFileInodesTable()->remove(inode.second.id);
this->database->getChunksTable()->remove(inode.second.id);
}
}
this->database->getDentryTable()->remove(dentries);
// delete the dentry-by-id files
this->deleteFsIDsFromDB(dentries);
}
bool ModeCheckFS::ensureLostAndFoundExists()
{
this->lostAndFoundNode = MsgHelperRepair::referenceLostAndFoundOwner(&this->lostAndFoundInfo);
if(!this->lostAndFoundNode)
{
if(!MsgHelperRepair::createLostAndFound(this->lostAndFoundNode, this->lostAndFoundInfo) )
return false;
}
std::pair<bool, FsckDirInode> dbLaF = this->database->getDirInodesTable()->get(
this->lostAndFoundInfo.getEntryID() );
if(dbLaF.first)
this->lostAndFoundInode.reset(new FsckDirInode(dbLaF.second) );
return true;
}
void ModeCheckFS::releaseLostAndFound()
{
if(!this->lostAndFoundNode)
return;
if(this->lostAndFoundInode)
{
FsckDirInodeList updates(1, *this->lostAndFoundInode);
this->database->getDirInodesTable()->update(updates);
}
this->lostAndFoundInode.reset();
}
| 33.319677 | 108 | 0.667423 | TomatoYoung |
8d1a7ec064dc8cea90086e0320845f0c256f8aa0 | 371 | cpp | C++ | LeetCode/Problems/Algorithms/#848_ShiftingLetters_sol2_suffix_sum_O(N)_time_O(1)_extra_space_193ms_68MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#848_ShiftingLetters_sol2_suffix_sum_O(N)_time_O(1)_extra_space_193ms_68MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#848_ShiftingLetters_sol2_suffix_sum_O(N)_time_O(1)_extra_space_193ms_68MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
string shiftingLetters(string s, vector<int>& shifts) {
const int N = shifts.size();
int suffixShifts = 0;
for(int i = N - 1; i >= 0; --i){
suffixShifts += shifts[i];
suffixShifts %= 26;
s[i] = 'a' + (s[i] - 'a' + suffixShifts) % 26;
}
return s;
}
}; | 28.538462 | 60 | 0.455526 | Tudor67 |
8d1c6192344d63bc5d4271fa53cb76ac4c70a4e5 | 10,129 | cxx | C++ | src/Core/Common/DoDataParallelThreading/Code.cxx | ldqcarbon/ITKExamples | 5e550d4085755f88ba13956767f4af0a2b4a0ae7 | [
"Apache-2.0"
] | null | null | null | src/Core/Common/DoDataParallelThreading/Code.cxx | ldqcarbon/ITKExamples | 5e550d4085755f88ba13956767f4af0a2b4a0ae7 | [
"Apache-2.0"
] | null | null | null | src/Core/Common/DoDataParallelThreading/Code.cxx | ldqcarbon/ITKExamples | 5e550d4085755f88ba13956767f4af0a2b4a0ae7 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkDomainThreader.h"
#include "itkThreadedIndexedContainerPartitioner.h"
// We have central nervous system cells of different types.
enum CELL_TYPE {
NEURON,
ASTROCYTE,
OLIGODENDROCYTE
};
// Type to hold our list of cells to count.
typedef std::vector< CELL_TYPE > CellContainerType;
// Type to hold the count for each CELL_TYPE.
typedef std::map< CELL_TYPE, unsigned int > CellCountType;
// This class performs the multi-threaded cell type counting for the
// CellCounter class, show below. The CellCounter class is the TAssociate, and
// since this class is declared as a friend, it can access the CellCounter's
// private members to compute the cell type count for the CellCounter.
//
// While the threading class can access its associate's private members, it
// generally should only do so in a read-only manner. Otherwise, attempting to
// write to the same member from multiple threads will cause race conditions
// and result in erroreous output or crash the program. For this reason, the
// threading class contains its own data structures that can be written to in
// individual threads. These data structures are set up in the
// BeforeThreadedExecution method, and the results contained in each data
// structure are collected in AfterThreadedExecution. In this case, we have
// m_CellCountPerThread whose counts are initialized to zero in
// BeforeThreadedExecution and collected together in AfterThreadedExecution.
//
// All members and methods related to the multi-threaded computation are
// encapsulated in this class.
//
// The class inherits from itk::DomainThreader, which provides common
// functionality and defines the stages of the multi-threaded operation.
//
// The itk::DomainThreader is templated over the type of DomainPartitioner used
// to split up the domain, and type of the associated class. The domain in
// this case is a range of indices of a std::vector< CELL_TYPE > to process, so
// we use a ThreadedIndexedContainerPartitioner. Other options for a domains
// defined as an iterator range or an image region are the
// ThreadedIteratorRangePartitioner and the ThreadedImageRegionPartitioner,
// respectively.
template< class TAssociate >
class ComputeCellCountThreader :
public itk::DomainThreader<
itk::ThreadedIndexedContainerPartitioner, TAssociate >
{
public:
// Standard ITK typedefs.
typedef ComputeCellCountThreader Self;
typedef itk::DomainThreader<
itk::ThreadedIndexedContainerPartitioner,
TAssociate > Superclass;
typedef itk::SmartPointer< Self > Pointer;
typedef itk::SmartPointer< const Self > ConstPointer;
// The domain is an index range.
typedef typename Superclass::DomainType DomainType;
// This creates the ::New() method for instantiating the class.
itkNewMacro( Self );
protected:
// We need a constructor for the itkNewMacro.
ComputeCellCountThreader() {}
private:
virtual void BeforeThreadedExecution()
{
// Reset the counts for all cell types to zero.
this->m_Associate->m_CellCount[NEURON] = 0;
this->m_Associate->m_CellCount[ASTROCYTE] = 0;
this->m_Associate->m_CellCount[OLIGODENDROCYTE] = 0;
// Resize our per-thread data structures to the number of threads that we
// are actually going to use. At this point the number of threads that
// will be used have already been calculated and are available. The number
// of threads used depends on the number of cores or processors available
// on the current system. It will also be truncated if, for example, the
// number of cells in the CellContainer is smaller than the number of cores
// available.
const itk::ThreadIdType numberOfThreads = this->GetNumberOfThreadsUsed();
this->m_CellCountPerThread.resize( numberOfThreads );
for( itk::ThreadIdType ii = 0; ii < numberOfThreads; ++ii )
{
this->m_CellCountPerThread[ii][NEURON] = 0;
this->m_CellCountPerThread[ii][ASTROCYTE] = 0;
this->m_CellCountPerThread[ii][OLIGODENDROCYTE] = 0;
}
}
virtual void ThreadedExecution( const DomainType & subDomain,
const itk::ThreadIdType threadId )
{
// Look only at the range of cells by the set of indices in the subDomain.
for( size_t ii = subDomain[0]; ii <= subDomain[1]; ++ii )
{
switch( this->m_Associate->m_Cells[ii] )
{
case NEURON:
// Accumulate in the per thread cell count.
++(this->m_CellCountPerThread[threadId][NEURON]);
break;
case ASTROCYTE:
++(this->m_CellCountPerThread[threadId][ASTROCYTE]);
break;
case OLIGODENDROCYTE:
++(this->m_CellCountPerThread[threadId][OLIGODENDROCYTE]);
break;
}
}
}
virtual void AfterThreadedExecution()
{
// Accumulate the cell counts per thread in the associate's total cell
// count.
const itk::ThreadIdType numberOfThreads = this->GetNumberOfThreadsUsed();
for( itk::ThreadIdType ii = 0; ii < numberOfThreads; ++ii )
{
this->m_Associate->m_CellCount[NEURON] +=
this->m_CellCountPerThread[ii][NEURON];
this->m_Associate->m_CellCount[ASTROCYTE] +=
this->m_CellCountPerThread[ii][ASTROCYTE];
this->m_Associate->m_CellCount[OLIGODENDROCYTE] +=
this->m_CellCountPerThread[ii][OLIGODENDROCYTE];
}
}
std::vector< CellCountType > m_CellCountPerThread;
};
// A class to count the cells.
class CellCounter
{
public:
typedef CellCounter Self;
typedef ComputeCellCountThreader< Self > ComputeCellCountThreaderType;
// Constructor. Create our Threader class instance.
CellCounter()
{
this->m_ComputeCellCountThreader = ComputeCellCountThreaderType::New();
}
// Set the cells we want to count.
void SetCells( const CellContainerType & cells )
{
this->m_Cells.resize( cells.size() );
for( size_t ii = 0; ii < cells.size(); ++ii )
{
this->m_Cells[ii] = cells[ii];
}
}
// Count the cells and return the count of each type.
const CellCountType & ComputeCellCount()
{
ComputeCellCountThreaderType::DomainType completeDomain;
completeDomain[0] = 0;
completeDomain[1] = this->m_Cells.size() - 1;
this->m_ComputeCellCountThreader->Execute( this, completeDomain );
return this->m_CellCount;
}
private:
// Stores the count of each type of cell.
CellCountType m_CellCount;
// Stores the cells to count.
CellContainerType m_Cells;
// The ComputeCellCountThreader gets to access m_CellCount and m_Cells as
// needed.
friend class ComputeCellCountThreader< Self >;
ComputeCellCountThreaderType::Pointer m_ComputeCellCountThreader;
};
int main( int, char* [] )
{
// Our cells.
static const CELL_TYPE cellsArr[] =
{ NEURON, ASTROCYTE, ASTROCYTE, OLIGODENDROCYTE,
ASTROCYTE, NEURON, NEURON, ASTROCYTE, ASTROCYTE, OLIGODENDROCYTE };
CellContainerType cells( cellsArr,
cellsArr + sizeof(cellsArr) / sizeof(cellsArr[0]) );
// Count them in a multi-threader way.
CellCounter cellCounter;
cellCounter.SetCells( cells );
const CellCountType multiThreadedCellCount = cellCounter.ComputeCellCount();
std::cout << "Result of the multi-threaded cell count:\n";
std::cout << "\tNEURON: " <<
(*multiThreadedCellCount.find(NEURON)).second << "\n";
std::cout << "\tASTROCYTE: " <<
(*multiThreadedCellCount.find(ASTROCYTE)).second << "\n";
std::cout << "\tOLIGODENDROCYTE: " <<
(*multiThreadedCellCount.find(OLIGODENDROCYTE)).second << "\n";
// Count them in a single-threaded way.
CellCountType singleThreadedCellCount;
singleThreadedCellCount[NEURON] = 0;
singleThreadedCellCount[ASTROCYTE] = 0;
singleThreadedCellCount[OLIGODENDROCYTE] = 0;
for( size_t ii = 0; ii < cells.size(); ++ii )
{
switch( cells[ii] )
{
case NEURON:
// Accumulate in the per thread cell count.
++(singleThreadedCellCount[NEURON]);
break;
case ASTROCYTE:
++(singleThreadedCellCount[ASTROCYTE]);
break;
case OLIGODENDROCYTE:
++(singleThreadedCellCount[OLIGODENDROCYTE]);
break;
}
}
std::cout << "Result of the single-threaded cell count:\n";
std::cout << "\tNEURON: " <<
(*singleThreadedCellCount.find(NEURON)).second << "\n";
std::cout << "\tASTROCYTE: " <<
(*singleThreadedCellCount.find(ASTROCYTE)).second << "\n";
std::cout << "\tOLIGODENDROCYTE: " <<
(*singleThreadedCellCount.find(OLIGODENDROCYTE)).second << "\n";
// Did we get what was expected? It is always good to check a multi-threaded
// implementation against a single-threaded implementation to ensure that it
// gets the same results.
if( (*multiThreadedCellCount.find(NEURON)).second !=
singleThreadedCellCount[NEURON] ||
(*multiThreadedCellCount.find(ASTROCYTE)).second !=
singleThreadedCellCount[ASTROCYTE] ||
(*multiThreadedCellCount.find(OLIGODENDROCYTE)).second !=
singleThreadedCellCount[OLIGODENDROCYTE] )
{
std::cerr << "Error: did not get the same results"
<< "for a single-threaded and multi-threaded calculation." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 36.832727 | 79 | 0.68605 | ldqcarbon |
8d1e0ee582941eb03c4ad82eaea4a2f8c1bebe61 | 1,391 | cpp | C++ | BeanDogEngine/cVortex.cpp | RoyFilipchuk56/BeanDogEngine | 189ff606b1568b8c2228602b545767bb827d3065 | [
"MIT"
] | null | null | null | BeanDogEngine/cVortex.cpp | RoyFilipchuk56/BeanDogEngine | 189ff606b1568b8c2228602b545767bb827d3065 | [
"MIT"
] | null | null | null | BeanDogEngine/cVortex.cpp | RoyFilipchuk56/BeanDogEngine | 189ff606b1568b8c2228602b545767bb827d3065 | [
"MIT"
] | null | null | null | #include "cFirework.h"
namespace nPhysics
{
cVortex::cVortex(float mass, const glm::vec3& position) : cFirework(mass, position)
{
}
cVortex::~cVortex()
{
}
void cVortex::GenerateChildren(std::vector<cFirework*>& childrenOut, glm::vec3 location)
{
//Genereate 50 new stage 2 particles
for (int i = 0; i < 50; i++)
{
nPhysics::cVortex* particle = new nPhysics::cVortex(1.0f, location);
particle->SetStageTwo();
childrenOut.push_back(particle);
}
}
void cVortex::Integrate(float deltaTime)
{
if (mInverseMass == 0.f)
{
return; // static things don't move!
}
//Set the new age
age += deltaTime;
mPosition += mVelocity * deltaTime;
// F*(1/m) = a
mVelocity += (mAcceleration + mAppliedForce * mInverseMass) * deltaTime;
// apply damping
mVelocity *= glm::pow(mDamping, deltaTime);
//Check if its still alive
if (mVelocity.y <= 0 && stage == 1)
{
isAlive = false;
}
if (age >= 1.5f && stage == 2)
{
isAlive = false;
}
// clear applied forces
ClearAppliedForces();
}
void cVortex::SetStageOne()
{
//set the stage
stage = 1;
//launch it in the air
this->SetVelocity(glm::vec3(0, getRandom(10, 15), 0));
}
void cVortex::SetStageTwo()
{
//set the stage
stage = 2;
//send them in a random direction
this->SetVelocity(getRandomVec3XZ(10));
this->SetAcceleration(glm::vec3(0.0f, 9.8f, 0.0f));
}
} | 20.455882 | 89 | 0.640546 | RoyFilipchuk56 |
8d22fb1052419774d27b3cbb4147b5040b5933f1 | 35,544 | cpp | C++ | src/superscalar.cpp | Teredic/DefyX | 5d71a3e8076e850acfeb18ec3612a2ec2a5b1308 | [
"BSD-3-Clause"
] | 2 | 2020-01-04T02:35:40.000Z | 2021-11-29T19:11:27.000Z | src/superscalar.cpp | Teredic/DefyX | 5d71a3e8076e850acfeb18ec3612a2ec2a5b1308 | [
"BSD-3-Clause"
] | null | null | null | src/superscalar.cpp | Teredic/DefyX | 5d71a3e8076e850acfeb18ec3612a2ec2a5b1308 | [
"BSD-3-Clause"
] | 2 | 2019-07-30T18:40:07.000Z | 2019-12-22T11:01:13.000Z | /*
Copyright (c) 2018-2019, tevador <tevador@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the 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 "configuration.h"
#include "program.hpp"
#include "blake2/endian.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iomanip>
#include "superscalar.hpp"
#include "intrin_portable.h"
#include "reciprocal.h"
#include "common.hpp"
namespace defyx {
static bool isMultiplication(SuperscalarInstructionType type) {
return type == SuperscalarInstructionType::IMUL_R || type == SuperscalarInstructionType::IMULH_R || type == SuperscalarInstructionType::ISMULH_R || type == SuperscalarInstructionType::IMUL_RCP;
}
//uOPs (micro-ops) are represented only by the execution port they can go to
namespace ExecutionPort {
using type = int;
constexpr type Null = 0;
constexpr type P0 = 1;
constexpr type P1 = 2;
constexpr type P5 = 4;
constexpr type P01 = P0 | P1;
constexpr type P05 = P0 | P5;
constexpr type P015 = P0 | P1 | P5;
}
//Macro-operation as output of the x86 decoder
//Usually one macro-op = one x86 instruction, but 2 instructions are sometimes fused into 1 macro-op
//Macro-op can consist of 1 or 2 uOPs.
class MacroOp {
public:
MacroOp(const char* name, int size)
: name_(name), size_(size), latency_(0), uop1_(ExecutionPort::Null), uop2_(ExecutionPort::Null) {}
MacroOp(const char* name, int size, int latency, ExecutionPort::type uop)
: name_(name), size_(size), latency_(latency), uop1_(uop), uop2_(ExecutionPort::Null) {}
MacroOp(const char* name, int size, int latency, ExecutionPort::type uop1, ExecutionPort::type uop2)
: name_(name), size_(size), latency_(latency), uop1_(uop1), uop2_(uop2) {}
MacroOp(const MacroOp& parent, bool dependent)
: name_(parent.name_), size_(parent.size_), latency_(parent.latency_), uop1_(parent.uop1_), uop2_(parent.uop2_), dependent_(dependent) {}
const char* getName() const {
return name_;
}
int getSize() const {
return size_;
}
int getLatency() const {
return latency_;
}
ExecutionPort::type getUop1() const {
return uop1_;
}
ExecutionPort::type getUop2() const {
return uop2_;
}
bool isSimple() const {
return uop2_ == ExecutionPort::Null;
}
bool isEliminated() const {
return uop1_ == ExecutionPort::Null;
}
bool isDependent() const {
return dependent_;
}
static const MacroOp Add_rr;
static const MacroOp Add_ri;
static const MacroOp Lea_sib;
static const MacroOp Sub_rr;
static const MacroOp Imul_rr;
static const MacroOp Imul_r;
static const MacroOp Mul_r;
static const MacroOp Mov_rr;
static const MacroOp Mov_ri64;
static const MacroOp Xor_rr;
static const MacroOp Xor_ri;
static const MacroOp Ror_rcl;
static const MacroOp Ror_ri;
static const MacroOp TestJz_fused;
static const MacroOp Xor_self;
static const MacroOp Cmp_ri;
static const MacroOp Setcc_r;
private:
const char* name_;
int size_;
int latency_;
ExecutionPort::type uop1_;
ExecutionPort::type uop2_;
bool dependent_ = false;
};
//Size: 3 bytes
const MacroOp MacroOp::Add_rr = MacroOp("add r,r", 3, 1, ExecutionPort::P015);
const MacroOp MacroOp::Sub_rr = MacroOp("sub r,r", 3, 1, ExecutionPort::P015);
const MacroOp MacroOp::Xor_rr = MacroOp("xor r,r", 3, 1, ExecutionPort::P015);
const MacroOp MacroOp::Imul_r = MacroOp("imul r", 3, 4, ExecutionPort::P1, ExecutionPort::P5);
const MacroOp MacroOp::Mul_r = MacroOp("mul r", 3, 4, ExecutionPort::P1, ExecutionPort::P5);
const MacroOp MacroOp::Mov_rr = MacroOp("mov r,r", 3);
//Size: 4 bytes
const MacroOp MacroOp::Lea_sib = MacroOp("lea r,r+r*s", 4, 1, ExecutionPort::P01);
const MacroOp MacroOp::Imul_rr = MacroOp("imul r,r", 4, 3, ExecutionPort::P1);
const MacroOp MacroOp::Ror_ri = MacroOp("ror r,i", 4, 1, ExecutionPort::P05);
//Size: 7 bytes (can be optionally padded with nop to 8 or 9 bytes)
const MacroOp MacroOp::Add_ri = MacroOp("add r,i", 7, 1, ExecutionPort::P015);
const MacroOp MacroOp::Xor_ri = MacroOp("xor r,i", 7, 1, ExecutionPort::P015);
//Size: 10 bytes
const MacroOp MacroOp::Mov_ri64 = MacroOp("mov rax,i64", 10, 1, ExecutionPort::P015);
//Unused:
const MacroOp MacroOp::Ror_rcl = MacroOp("ror r,cl", 3, 1, ExecutionPort::P0, ExecutionPort::P5);
const MacroOp MacroOp::Xor_self = MacroOp("xor rcx,rcx", 3);
const MacroOp MacroOp::Cmp_ri = MacroOp("cmp r,i", 7, 1, ExecutionPort::P015);
const MacroOp MacroOp::Setcc_r = MacroOp("setcc cl", 3, 1, ExecutionPort::P05);
const MacroOp MacroOp::TestJz_fused = MacroOp("testjz r,i", 13, 0, ExecutionPort::P5);
const MacroOp IMULH_R_ops_array[] = { MacroOp::Mov_rr, MacroOp::Mul_r, MacroOp::Mov_rr };
const MacroOp ISMULH_R_ops_array[] = { MacroOp::Mov_rr, MacroOp::Imul_r, MacroOp::Mov_rr };
const MacroOp IMUL_RCP_ops_array[] = { MacroOp::Mov_ri64, MacroOp(MacroOp::Imul_rr, true) };
class SuperscalarInstructionInfo {
public:
const char* getName() const {
return name_;
}
int getSize() const {
return ops_.size();
}
bool isSimple() const {
return getSize() == 1;
}
int getLatency() const {
return latency_;
}
const MacroOp& getOp(int index) const {
return ops_[index];
}
SuperscalarInstructionType getType() const {
return type_;
}
int getResultOp() const {
return resultOp_;
}
int getDstOp() const {
return dstOp_;
}
int getSrcOp() const {
return srcOp_;
}
static const SuperscalarInstructionInfo ISUB_R;
static const SuperscalarInstructionInfo IXOR_R;
static const SuperscalarInstructionInfo IADD_RS;
static const SuperscalarInstructionInfo IMUL_R;
static const SuperscalarInstructionInfo IROR_C;
static const SuperscalarInstructionInfo IADD_C7;
static const SuperscalarInstructionInfo IXOR_C7;
static const SuperscalarInstructionInfo IADD_C8;
static const SuperscalarInstructionInfo IXOR_C8;
static const SuperscalarInstructionInfo IADD_C9;
static const SuperscalarInstructionInfo IXOR_C9;
static const SuperscalarInstructionInfo IMULH_R;
static const SuperscalarInstructionInfo ISMULH_R;
static const SuperscalarInstructionInfo IMUL_RCP;
static const SuperscalarInstructionInfo NOP;
private:
const char* name_;
SuperscalarInstructionType type_;
std::vector<MacroOp> ops_;
int latency_;
int resultOp_ = 0;
int dstOp_ = 0;
int srcOp_;
SuperscalarInstructionInfo(const char* name)
: name_(name), type_(SuperscalarInstructionType::INVALID), latency_(0) {}
SuperscalarInstructionInfo(const char* name, SuperscalarInstructionType type, const MacroOp& op, int srcOp)
: name_(name), type_(type), latency_(op.getLatency()), srcOp_(srcOp) {
ops_.push_back(MacroOp(op));
}
template <size_t N>
SuperscalarInstructionInfo(const char* name, SuperscalarInstructionType type, const MacroOp(&arr)[N], int resultOp, int dstOp, int srcOp)
: name_(name), type_(type), latency_(0), resultOp_(resultOp), dstOp_(dstOp), srcOp_(srcOp) {
for (unsigned i = 0; i < N; ++i) {
ops_.push_back(MacroOp(arr[i]));
latency_ += ops_.back().getLatency();
}
static_assert(N > 1, "Invalid array size");
}
};
const SuperscalarInstructionInfo SuperscalarInstructionInfo::ISUB_R = SuperscalarInstructionInfo("ISUB_R", SuperscalarInstructionType::ISUB_R, MacroOp::Sub_rr, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_R = SuperscalarInstructionInfo("IXOR_R", SuperscalarInstructionType::IXOR_R, MacroOp::Xor_rr, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_RS = SuperscalarInstructionInfo("IADD_RS", SuperscalarInstructionType::IADD_RS, MacroOp::Lea_sib, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IMUL_R = SuperscalarInstructionInfo("IMUL_R", SuperscalarInstructionType::IMUL_R, MacroOp::Imul_rr, 0);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IROR_C = SuperscalarInstructionInfo("IROR_C", SuperscalarInstructionType::IROR_C, MacroOp::Ror_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_C7 = SuperscalarInstructionInfo("IADD_C7", SuperscalarInstructionType::IADD_C7, MacroOp::Add_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_C7 = SuperscalarInstructionInfo("IXOR_C7", SuperscalarInstructionType::IXOR_C7, MacroOp::Xor_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_C8 = SuperscalarInstructionInfo("IADD_C8", SuperscalarInstructionType::IADD_C8, MacroOp::Add_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_C8 = SuperscalarInstructionInfo("IXOR_C8", SuperscalarInstructionType::IXOR_C8, MacroOp::Xor_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IADD_C9 = SuperscalarInstructionInfo("IADD_C9", SuperscalarInstructionType::IADD_C9, MacroOp::Add_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IXOR_C9 = SuperscalarInstructionInfo("IXOR_C9", SuperscalarInstructionType::IXOR_C9, MacroOp::Xor_ri, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IMULH_R = SuperscalarInstructionInfo("IMULH_R", SuperscalarInstructionType::IMULH_R, IMULH_R_ops_array, 1, 0, 1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::ISMULH_R = SuperscalarInstructionInfo("ISMULH_R", SuperscalarInstructionType::ISMULH_R, ISMULH_R_ops_array, 1, 0, 1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::IMUL_RCP = SuperscalarInstructionInfo("IMUL_RCP", SuperscalarInstructionType::IMUL_RCP, IMUL_RCP_ops_array, 1, 1, -1);
const SuperscalarInstructionInfo SuperscalarInstructionInfo::NOP = SuperscalarInstructionInfo("NOP");
//these are some of the options how to split a 16-byte window into 3 or 4 x86 instructions.
//DefyX uses instructions with a native size of 3 (sub, xor, mul, mov), 4 (lea, mul), 7 (xor, add immediate) or 10 bytes (mov 64-bit immediate).
//Slots with sizes of 8 or 9 bytes need to be padded with a nop instruction.
const int buffer0[] = { 4, 8, 4 };
const int buffer1[] = { 7, 3, 3, 3 };
const int buffer2[] = { 3, 7, 3, 3 };
const int buffer3[] = { 4, 9, 3 };
const int buffer4[] = { 4, 4, 4, 4 };
const int buffer5[] = { 3, 3, 10 };
class DecoderBuffer {
public:
static const DecoderBuffer Default;
template <size_t N>
DecoderBuffer(const char* name, int index, const int(&arr)[N])
: name_(name), index_(index), counts_(arr), opsCount_(N) {}
const int* getCounts() const {
return counts_;
}
int getSize() const {
return opsCount_;
}
int getIndex() const {
return index_;
}
const char* getName() const {
return name_;
}
const DecoderBuffer* fetchNext(SuperscalarInstructionType instrType, int cycle, int mulCount, Blake2Generator& gen) const {
//If the current DefyX instruction is "IMULH", the next fetch configuration must be 3-3-10
//because the full 128-bit multiplication instruction is 3 bytes long and decodes to 2 uOPs on Intel CPUs.
//Intel CPUs can decode at most 4 uOPs per cycle, so this requires a 2-1-1 configuration for a total of 3 macro ops.
if (instrType == SuperscalarInstructionType::IMULH_R || instrType == SuperscalarInstructionType::ISMULH_R)
return &decodeBuffer3310;
//To make sure that the multiplication port is saturated, a 4-4-4-4 configuration is generated if the number of multiplications
//is lower than the number of cycles.
if (mulCount < cycle + 1)
return &decodeBuffer4444;
//If the current DefyX instruction is "IMUL_RCP", the next buffer must begin with a 4-byte slot for multiplication.
if(instrType == SuperscalarInstructionType::IMUL_RCP)
return (gen.getByte() & 1) ? &decodeBuffer484 : &decodeBuffer493;
//Default: select a random fetch configuration.
return fetchNextDefault(gen);
}
private:
const char* name_;
int index_;
const int* counts_;
int opsCount_;
DecoderBuffer() : index_(-1) {}
static const DecoderBuffer decodeBuffer484;
static const DecoderBuffer decodeBuffer7333;
static const DecoderBuffer decodeBuffer3733;
static const DecoderBuffer decodeBuffer493;
static const DecoderBuffer decodeBuffer4444;
static const DecoderBuffer decodeBuffer3310;
static const DecoderBuffer* decodeBuffers[4];
const DecoderBuffer* fetchNextDefault(Blake2Generator& gen) const {
return decodeBuffers[gen.getByte() & 3];
}
};
const DecoderBuffer DecoderBuffer::decodeBuffer484 = DecoderBuffer("4,8,4", 0, buffer0);
const DecoderBuffer DecoderBuffer::decodeBuffer7333 = DecoderBuffer("7,3,3,3", 1, buffer1);
const DecoderBuffer DecoderBuffer::decodeBuffer3733 = DecoderBuffer("3,7,3,3", 2, buffer2);
const DecoderBuffer DecoderBuffer::decodeBuffer493 = DecoderBuffer("4,9,3", 3, buffer3);
const DecoderBuffer DecoderBuffer::decodeBuffer4444 = DecoderBuffer("4,4,4,4", 4, buffer4);
const DecoderBuffer DecoderBuffer::decodeBuffer3310 = DecoderBuffer("3,3,10", 5, buffer5);
const DecoderBuffer* DecoderBuffer::decodeBuffers[4] = {
&DecoderBuffer::decodeBuffer484,
&DecoderBuffer::decodeBuffer7333,
&DecoderBuffer::decodeBuffer3733,
&DecoderBuffer::decodeBuffer493,
};
const DecoderBuffer DecoderBuffer::Default = DecoderBuffer();
const SuperscalarInstructionInfo* slot_3[] = { &SuperscalarInstructionInfo::ISUB_R, &SuperscalarInstructionInfo::IXOR_R };
const SuperscalarInstructionInfo* slot_3L[] = { &SuperscalarInstructionInfo::ISUB_R, &SuperscalarInstructionInfo::IXOR_R, &SuperscalarInstructionInfo::IMULH_R, &SuperscalarInstructionInfo::ISMULH_R };
const SuperscalarInstructionInfo* slot_4[] = { &SuperscalarInstructionInfo::IROR_C, &SuperscalarInstructionInfo::IADD_RS };
const SuperscalarInstructionInfo* slot_7[] = { &SuperscalarInstructionInfo::IXOR_C7, &SuperscalarInstructionInfo::IADD_C7 };
const SuperscalarInstructionInfo* slot_8[] = { &SuperscalarInstructionInfo::IXOR_C8, &SuperscalarInstructionInfo::IADD_C8 };
const SuperscalarInstructionInfo* slot_9[] = { &SuperscalarInstructionInfo::IXOR_C9, &SuperscalarInstructionInfo::IADD_C9 };
const SuperscalarInstructionInfo* slot_10 = &SuperscalarInstructionInfo::IMUL_RCP;
static bool selectRegister(std::vector<int>& availableRegisters, Blake2Generator& gen, int& reg) {
int index;
if (availableRegisters.size() == 0)
return false;
if (availableRegisters.size() > 1) {
index = gen.getUInt32() % availableRegisters.size();
}
else {
index = 0;
}
reg = availableRegisters[index];
return true;
}
class RegisterInfo {
public:
RegisterInfo() : latency(0), lastOpGroup(SuperscalarInstructionType::INVALID), lastOpPar(-1), value(0) {}
int latency;
SuperscalarInstructionType lastOpGroup;
int lastOpPar;
int value;
};
//"SuperscalarInstruction" consists of one or more macro-ops
class SuperscalarInstruction {
public:
void toInstr(Instruction& instr) { //translate to a DefyX instruction format
instr.opcode = (int)getType();
instr.dst = dst_;
instr.src = src_ >= 0 ? src_ : dst_;
instr.setMod(mod_);
instr.setImm32(imm32_);
}
void createForSlot(Blake2Generator& gen, int slotSize, int fetchType, bool isLast, bool isFirst) {
switch (slotSize)
{
case 3:
//if this is the last slot, we can also select "IMULH" instructions
if (isLast) {
create(slot_3L[gen.getByte() & 3], gen);
}
else {
create(slot_3[gen.getByte() & 1], gen);
}
break;
case 4:
//if this is the 4-4-4-4 buffer, issue multiplications as the first 3 instructions
if (fetchType == 4 && !isLast) {
create(&SuperscalarInstructionInfo::IMUL_R, gen);
}
else {
create(slot_4[gen.getByte() & 1], gen);
}
break;
case 7:
create(slot_7[gen.getByte() & 1], gen);
break;
case 8:
create(slot_8[gen.getByte() & 1], gen);
break;
case 9:
create(slot_9[gen.getByte() & 1], gen);
break;
case 10:
create(slot_10, gen);
break;
default:
UNREACHABLE;
}
}
void create(const SuperscalarInstructionInfo* info, Blake2Generator& gen) {
info_ = info;
reset();
switch (info->getType())
{
case SuperscalarInstructionType::ISUB_R: {
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IADD_RS;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IXOR_R: {
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IXOR_R;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IADD_RS: {
mod_ = gen.getByte();
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IADD_RS;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IMUL_R: {
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IMUL_R;
groupParIsSource_ = true;
} break;
case SuperscalarInstructionType::IROR_C: {
mod_ = 0;
do {
imm32_ = gen.getByte() & 63;
} while (imm32_ == 0);
opGroup_ = SuperscalarInstructionType::IROR_C;
opGroupPar_ = -1;
} break;
case SuperscalarInstructionType::IADD_C7:
case SuperscalarInstructionType::IADD_C8:
case SuperscalarInstructionType::IADD_C9: {
mod_ = 0;
imm32_ = gen.getUInt32();
opGroup_ = SuperscalarInstructionType::IADD_C7;
opGroupPar_ = -1;
} break;
case SuperscalarInstructionType::IXOR_C7:
case SuperscalarInstructionType::IXOR_C8:
case SuperscalarInstructionType::IXOR_C9: {
mod_ = 0;
imm32_ = gen.getUInt32();
opGroup_ = SuperscalarInstructionType::IXOR_C7;
opGroupPar_ = -1;
} break;
case SuperscalarInstructionType::IMULH_R: {
canReuse_ = true;
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::IMULH_R;
opGroupPar_ = gen.getUInt32();
} break;
case SuperscalarInstructionType::ISMULH_R: {
canReuse_ = true;
mod_ = 0;
imm32_ = 0;
opGroup_ = SuperscalarInstructionType::ISMULH_R;
opGroupPar_ = gen.getUInt32();
} break;
case SuperscalarInstructionType::IMUL_RCP: {
mod_ = 0;
do {
imm32_ = gen.getUInt32();
} while (isZeroOrPowerOf2(imm32_));
opGroup_ = SuperscalarInstructionType::IMUL_RCP;
opGroupPar_ = -1;
} break;
default:
break;
}
}
bool selectDestination(int cycle, bool allowChainedMul, RegisterInfo (®isters)[8], Blake2Generator& gen) {
/*if (allowChainedMultiplication && opGroup_ == SuperscalarInstructionType::IMUL_R)
std::cout << "Selecting destination with chained MUL enabled" << std::endl;*/
std::vector<int> availableRegisters;
//Conditions for the destination register:
// * value must be ready at the required cycle
// * cannot be the same as the source register unless the instruction allows it
// - this avoids optimizable instructions such as "xor r, r" or "sub r, r"
// * register cannot be multiplied twice in a row unless allowChainedMul is true
// - this avoids accumulation of trailing zeroes in registers due to excessive multiplication
// - allowChainedMul is set to true if an attempt to find source/destination registers failed (this is quite rare, but prevents a catastrophic failure of the generator)
// * either the last instruction applied to the register or its source must be different than this instruction
// - this avoids optimizable instruction sequences such as "xor r1, r2; xor r1, r2" or "ror r, C1; ror r, C2" or "add r, C1; add r, C2"
// * register r5 cannot be the destination of the IADD_RS instruction (limitation of the x86 lea instruction)
for (unsigned i = 0; i < 8; ++i) {
if (registers[i].latency <= cycle && (canReuse_ || i != src_) && (allowChainedMul || opGroup_ != SuperscalarInstructionType::IMUL_R || registers[i].lastOpGroup != SuperscalarInstructionType::IMUL_R) && (registers[i].lastOpGroup != opGroup_ || registers[i].lastOpPar != opGroupPar_) && (info_->getType() != SuperscalarInstructionType::IADD_RS || i != RegisterNeedsDisplacement))
availableRegisters.push_back(i);
}
return selectRegister(availableRegisters, gen, dst_);
}
bool selectSource(int cycle, RegisterInfo(®isters)[8], Blake2Generator& gen) {
std::vector<int> availableRegisters;
//all registers that are ready at the cycle
for (unsigned i = 0; i < 8; ++i) {
if (registers[i].latency <= cycle)
availableRegisters.push_back(i);
}
//if there are only 2 available registers for IADD_RS and one of them is r5, select it as the source because it cannot be the destination
if (availableRegisters.size() == 2 && info_->getType() == SuperscalarInstructionType::IADD_RS) {
if (availableRegisters[0] == RegisterNeedsDisplacement || availableRegisters[1] == RegisterNeedsDisplacement) {
opGroupPar_ = src_ = RegisterNeedsDisplacement;
return true;
}
}
if (selectRegister(availableRegisters, gen, src_)) {
if (groupParIsSource_)
opGroupPar_ = src_;
return true;
}
return false;
}
SuperscalarInstructionType getType() {
return info_->getType();
}
int getSource() {
return src_;
}
int getDestination() {
return dst_;
}
SuperscalarInstructionType getGroup() {
return opGroup_;
}
int getGroupPar() {
return opGroupPar_;
}
const SuperscalarInstructionInfo& getInfo() const {
return *info_;
}
static const SuperscalarInstruction Null;
private:
const SuperscalarInstructionInfo* info_;
int src_ = -1;
int dst_ = -1;
int mod_;
uint32_t imm32_;
SuperscalarInstructionType opGroup_;
int opGroupPar_;
bool canReuse_ = false;
bool groupParIsSource_ = false;
void reset() {
src_ = dst_ = -1;
canReuse_ = groupParIsSource_ = false;
}
SuperscalarInstruction(const SuperscalarInstructionInfo* info) : info_(info) {
}
};
const SuperscalarInstruction SuperscalarInstruction::Null = SuperscalarInstruction(&SuperscalarInstructionInfo::NOP);
constexpr int CYCLE_MAP_SIZE = RANDOMX_SUPERSCALAR_LATENCY + 4;
constexpr int LOOK_FORWARD_CYCLES = 4;
constexpr int MAX_THROWAWAY_COUNT = 256;
template<bool commit>
static int scheduleUop(ExecutionPort::type uop, ExecutionPort::type(&portBusy)[CYCLE_MAP_SIZE][3], int cycle) {
//The scheduling here is done optimistically by checking port availability in order P5 -> P0 -> P1 to not overload
//port P1 (multiplication) by instructions that can go to any port.
for (; cycle < CYCLE_MAP_SIZE; ++cycle) {
if ((uop & ExecutionPort::P5) != 0 && !portBusy[cycle][2]) {
if (commit) {
if (trace) std::cout << "; P5 at cycle " << cycle << std::endl;
portBusy[cycle][2] = uop;
}
return cycle;
}
if ((uop & ExecutionPort::P0) != 0 && !portBusy[cycle][0]) {
if (commit) {
if (trace) std::cout << "; P0 at cycle " << cycle << std::endl;
portBusy[cycle][0] = uop;
}
return cycle;
}
if ((uop & ExecutionPort::P1) != 0 && !portBusy[cycle][1]) {
if (commit) {
if (trace) std::cout << "; P1 at cycle " << cycle << std::endl;
portBusy[cycle][1] = uop;
}
return cycle;
}
}
return -1;
}
template<bool commit>
static int scheduleMop(const MacroOp& mop, ExecutionPort::type(&portBusy)[CYCLE_MAP_SIZE][3], int cycle, int depCycle) {
//if this macro-op depends on the previous one, increase the starting cycle if needed
//this handles an explicit dependency chain in IMUL_RCP
if (mop.isDependent()) {
cycle = std::max(cycle, depCycle);
}
//move instructions are eliminated and don't need an execution unit
if (mop.isEliminated()) {
if (commit)
if (trace) std::cout << "; (eliminated)" << std::endl;
return cycle;
}
else if (mop.isSimple()) {
//this macro-op has only one uOP
return scheduleUop<commit>(mop.getUop1(), portBusy, cycle);
}
else {
//macro-ops with 2 uOPs are scheduled conservatively by requiring both uOPs to execute in the same cycle
for (; cycle < CYCLE_MAP_SIZE; ++cycle) {
int cycle1 = scheduleUop<false>(mop.getUop1(), portBusy, cycle);
int cycle2 = scheduleUop<false>(mop.getUop2(), portBusy, cycle);
if (cycle1 == cycle2) {
if (commit) {
scheduleUop<true>(mop.getUop1(), portBusy, cycle1);
scheduleUop<true>(mop.getUop2(), portBusy, cycle2);
}
return cycle1;
}
}
}
return -1;
}
void generateSuperscalar(SuperscalarProgram& prog, Blake2Generator& gen) {
ExecutionPort::type portBusy[CYCLE_MAP_SIZE][3];
memset(portBusy, 0, sizeof(portBusy));
RegisterInfo registers[8];
const DecoderBuffer* decodeBuffer = &DecoderBuffer::Default;
SuperscalarInstruction currentInstruction = SuperscalarInstruction::Null;
int macroOpIndex = 0;
int codeSize = 0;
int macroOpCount = 0;
int cycle = 0;
int depCycle = 0;
int retireCycle = 0;
bool portsSaturated = false;
int programSize = 0;
int mulCount = 0;
int decodeCycle;
int throwAwayCount = 0;
//decode instructions for RANDOMX_SUPERSCALAR_LATENCY cycles or until an execution port is saturated.
//Each decode cycle decodes 16 bytes of x86 code.
//Since a decode cycle produces on average 3.45 macro-ops and there are only 3 ALU ports, execution ports are always
//saturated first. The cycle limit is present only to guarantee loop termination.
//Program size is limited to SuperscalarMaxSize instructions.
for (decodeCycle = 0; decodeCycle < RANDOMX_SUPERSCALAR_LATENCY && !portsSaturated && programSize < SuperscalarMaxSize; ++decodeCycle) {
//select a decode configuration
decodeBuffer = decodeBuffer->fetchNext(currentInstruction.getType(), decodeCycle, mulCount, gen);
if (trace) std::cout << "; ------------- fetch cycle " << cycle << " (" << decodeBuffer->getName() << ")" << std::endl;
int bufferIndex = 0;
//fill all instruction slots in the current decode buffer
while (bufferIndex < decodeBuffer->getSize()) {
int topCycle = cycle;
//if we have issued all macro-ops for the current DefyX instruction, create a new instruction
if (macroOpIndex >= currentInstruction.getInfo().getSize()) {
if (portsSaturated || programSize >= SuperscalarMaxSize)
break;
//select an instruction so that the first macro-op fits into the current slot
currentInstruction.createForSlot(gen, decodeBuffer->getCounts()[bufferIndex], decodeBuffer->getIndex(), decodeBuffer->getSize() == bufferIndex + 1, bufferIndex == 0);
macroOpIndex = 0;
if (trace) std::cout << "; " << currentInstruction.getInfo().getName() << std::endl;
}
const MacroOp& mop = currentInstruction.getInfo().getOp(macroOpIndex);
if (trace) std::cout << mop.getName() << " ";
//calculate the earliest cycle when this macro-op (all of its uOPs) can be scheduled for execution
int scheduleCycle = scheduleMop<false>(mop, portBusy, cycle, depCycle);
if (scheduleCycle < 0) {
if (trace) std::cout << "Unable to map operation '" << mop.getName() << "' to execution port (cycle " << cycle << ")" << std::endl;
//__debugbreak();
portsSaturated = true;
break;
}
//find a source register (if applicable) that will be ready when this instruction executes
if (macroOpIndex == currentInstruction.getInfo().getSrcOp()) {
int forward;
//if no suitable operand is ready, look up to LOOK_FORWARD_CYCLES forward
for (forward = 0; forward < LOOK_FORWARD_CYCLES && !currentInstruction.selectSource(scheduleCycle, registers, gen); ++forward) {
if (trace) std::cout << "; src STALL at cycle " << cycle << std::endl;
++scheduleCycle;
++cycle;
}
//if no register was found, throw the instruction away and try another one
if (forward == LOOK_FORWARD_CYCLES) {
if (throwAwayCount < MAX_THROWAWAY_COUNT) {
throwAwayCount++;
macroOpIndex = currentInstruction.getInfo().getSize();
if (trace) std::cout << "; THROW away " << currentInstruction.getInfo().getName() << std::endl;
//cycle = topCycle;
continue;
}
//abort this decode buffer
if (trace) std::cout << "Aborting at cycle " << cycle << " with decode buffer " << decodeBuffer->getName() << " - source registers not available for operation " << currentInstruction.getInfo().getName() << std::endl;
currentInstruction = SuperscalarInstruction::Null;
break;
}
if (trace) std::cout << "; src = r" << currentInstruction.getSource() << std::endl;
}
//find a destination register that will be ready when this instruction executes
if (macroOpIndex == currentInstruction.getInfo().getDstOp()) {
int forward;
for (forward = 0; forward < LOOK_FORWARD_CYCLES && !currentInstruction.selectDestination(scheduleCycle, throwAwayCount > 0, registers, gen); ++forward) {
if (trace) std::cout << "; dst STALL at cycle " << cycle << std::endl;
++scheduleCycle;
++cycle;
}
if (forward == LOOK_FORWARD_CYCLES) { //throw instruction away
if (throwAwayCount < MAX_THROWAWAY_COUNT) {
throwAwayCount++;
macroOpIndex = currentInstruction.getInfo().getSize();
if (trace) std::cout << "; THROW away " << currentInstruction.getInfo().getName() << std::endl;
//cycle = topCycle;
continue;
}
//abort this decode buffer
if (trace) std::cout << "Aborting at cycle " << cycle << " with decode buffer " << decodeBuffer->getName() << " - destination registers not available" << std::endl;
currentInstruction = SuperscalarInstruction::Null;
break;
}
if (trace) std::cout << "; dst = r" << currentInstruction.getDestination() << std::endl;
}
throwAwayCount = 0;
//recalculate when the instruction can be scheduled for execution based on operand availability
scheduleCycle = scheduleMop<true>(mop, portBusy, scheduleCycle, scheduleCycle);
//calculate when the result will be ready
depCycle = scheduleCycle + mop.getLatency();
//if this instruction writes the result, modify register information
// RegisterInfo.latency - which cycle the register will be ready
// RegisterInfo.lastOpGroup - the last operation that was applied to the register
// RegisterInfo.lastOpPar - the last operation source value (-1 = constant, 0-7 = register)
if (macroOpIndex == currentInstruction.getInfo().getResultOp()) {
int dst = currentInstruction.getDestination();
RegisterInfo& ri = registers[dst];
retireCycle = depCycle;
ri.latency = retireCycle;
ri.lastOpGroup = currentInstruction.getGroup();
ri.lastOpPar = currentInstruction.getGroupPar();
if (trace) std::cout << "; RETIRED at cycle " << retireCycle << std::endl;
}
codeSize += mop.getSize();
bufferIndex++;
macroOpIndex++;
macroOpCount++;
//terminating condition
if (scheduleCycle >= RANDOMX_SUPERSCALAR_LATENCY) {
portsSaturated = true;
}
cycle = topCycle;
//when all macro-ops of the current instruction have been issued, add the instruction into the program
if (macroOpIndex >= currentInstruction.getInfo().getSize()) {
currentInstruction.toInstr(prog(programSize++));
mulCount += isMultiplication(currentInstruction.getType());
}
}
++cycle;
}
double ipc = (macroOpCount / (double)retireCycle);
memset(prog.asicLatencies, 0, sizeof(prog.asicLatencies));
//Calculate ASIC latency:
//Assumes 1 cycle latency for all operations and unlimited parallelization.
for (int i = 0; i < programSize; ++i) {
Instruction& instr = prog(i);
int latDst = prog.asicLatencies[instr.dst] + 1;
int latSrc = instr.dst != instr.src ? prog.asicLatencies[instr.src] + 1 : 0;
prog.asicLatencies[instr.dst] = std::max(latDst, latSrc);
}
//address register is the register with the highest ASIC latency
int asicLatencyMax = 0;
int addressReg = 0;
for (int i = 0; i < 8; ++i) {
if (prog.asicLatencies[i] > asicLatencyMax) {
asicLatencyMax = prog.asicLatencies[i];
addressReg = i;
}
prog.cpuLatencies[i] = registers[i].latency;
}
prog.setSize(programSize);
prog.setAddressRegister(addressReg);
prog.cpuLatency = retireCycle;
prog.asicLatency = asicLatencyMax;
prog.codeSize = codeSize;
prog.macroOps = macroOpCount;
prog.decodeCycles = decodeCycle;
prog.ipc = ipc;
prog.mulCount = mulCount;
/*if(INFO) std::cout << "; ALU port utilization:" << std::endl;
if (INFO) std::cout << "; (* = in use, _ = idle)" << std::endl;
int portCycles = 0;
for (int i = 0; i < CYCLE_MAP_SIZE; ++i) {
std::cout << "; " << std::setw(3) << i << " ";
for (int j = 0; j < 3; ++j) {
std::cout << (portBusy[i][j] ? '*' : '_');
portCycles += !!portBusy[i][j];
}
std::cout << std::endl;
}*/
}
void executeSuperscalar(int_reg_t(&r)[8], SuperscalarProgram& prog, std::vector<uint64_t> *reciprocals) {
for (unsigned j = 0; j < prog.getSize(); ++j) {
Instruction& instr = prog(j);
switch ((SuperscalarInstructionType)instr.opcode)
{
case SuperscalarInstructionType::ISUB_R:
r[instr.dst] -= r[instr.src];
break;
case SuperscalarInstructionType::IXOR_R:
r[instr.dst] ^= r[instr.src];
break;
case SuperscalarInstructionType::IADD_RS:
r[instr.dst] += r[instr.src] << instr.getModShift();
break;
case SuperscalarInstructionType::IMUL_R:
r[instr.dst] *= r[instr.src];
break;
case SuperscalarInstructionType::IROR_C:
r[instr.dst] = rotr(r[instr.dst], instr.getImm32());
break;
case SuperscalarInstructionType::IADD_C7:
case SuperscalarInstructionType::IADD_C8:
case SuperscalarInstructionType::IADD_C9:
r[instr.dst] += signExtend2sCompl(instr.getImm32());
break;
case SuperscalarInstructionType::IXOR_C7:
case SuperscalarInstructionType::IXOR_C8:
case SuperscalarInstructionType::IXOR_C9:
r[instr.dst] ^= signExtend2sCompl(instr.getImm32());
break;
case SuperscalarInstructionType::IMULH_R:
r[instr.dst] = mulh(r[instr.dst], r[instr.src]);
break;
case SuperscalarInstructionType::ISMULH_R:
r[instr.dst] = smulh(r[instr.dst], r[instr.src]);
break;
case SuperscalarInstructionType::IMUL_RCP:
if (reciprocals != nullptr)
r[instr.dst] *= (*reciprocals)[instr.getImm32()];
else
r[instr.dst] *= defyx_reciprocal(instr.getImm32());
break;
default:
UNREACHABLE;
}
}
}
}
| 39.581292 | 381 | 0.71064 | Teredic |
8d23bd7fec398c47e83030a985c02a77263b4609 | 390 | cpp | C++ | all/native/datasources/components/VectorData.cpp | JianYT/mobile-sdk | 1835603e6cb7994222fea681928dc90055816628 | [
"BSD-3-Clause"
] | 155 | 2016-10-20T08:39:13.000Z | 2022-02-27T14:08:32.000Z | all/native/datasources/components/VectorData.cpp | JianYT/mobile-sdk | 1835603e6cb7994222fea681928dc90055816628 | [
"BSD-3-Clause"
] | 448 | 2016-10-20T12:33:06.000Z | 2022-03-22T14:42:58.000Z | all/native/datasources/components/VectorData.cpp | JianYT/mobile-sdk | 1835603e6cb7994222fea681928dc90055816628 | [
"BSD-3-Clause"
] | 64 | 2016-12-05T16:04:31.000Z | 2022-02-07T09:36:22.000Z | #include "VectorData.h"
#include "vectorelements/VectorElement.h"
namespace carto {
VectorData::VectorData(std::vector<std::shared_ptr<VectorElement> > elements) :
_elements(std::move(elements))
{
}
VectorData::~VectorData() {
}
const std::vector<std::shared_ptr<VectorElement> >& VectorData::getElements() const {
return _elements;
}
}
| 20.526316 | 89 | 0.653846 | JianYT |
8d273a6664605dcbda1e3dfcf03ee13ee67c36da | 1,009 | cpp | C++ | grade.cpp | BranchofLight/Chunk | 5f9ef6acab5b9553af471c95fe315896f17803aa | [
"MIT"
] | null | null | null | grade.cpp | BranchofLight/Chunk | 5f9ef6acab5b9553af471c95fe315896f17803aa | [
"MIT"
] | null | null | null | grade.cpp | BranchofLight/Chunk | 5f9ef6acab5b9553af471c95fe315896f17803aa | [
"MIT"
] | null | null | null | #include <iostream>
#include "chunk.h"
int main()
{
Chunk grade;
std::cout << "What was your grade?";
do
{
std::cout << "\n> ";
getchunk(std::cin, grade);
if (!grade.isFloat())
std::cout << "Please enter a valid grade between 0-100.";
else
{
if (grade.toFloat() < 0 || grade.toFloat() > 100)
std::cout << "Please enter a valid grade between 0-100.";
}
} while (!grade.isFloat() || grade.toFloat() < 0 || grade.toFloat() > 100);
float gradeCheck = grade.toFloat();
if (gradeCheck >= 90 && gradeCheck <= 100)
std::cout << "Congratulations! You got an A!";
else if (gradeCheck >= 80 && gradeCheck < 90)
std::cout << "Congratulations! You got a B!";
else if (gradeCheck >= 70 && gradeCheck < 80)
std::cout << "You got a C!";
else if (gradeCheck >= 60 && gradeCheck < 70)
std::cout << "You got a D!";
else if (gradeCheck >= 0 && gradeCheck < 60)
std::cout << "Sorry! You got an F!";
return 0;
}
| 25.871795 | 77 | 0.556987 | BranchofLight |
8d306544728dd80129b583599067b3b815bd7faf | 11,675 | cpp | C++ | src/gateway/ocg_bss/virtual_ocg/ocg_encoder.cpp | liutongwei/ft | c75c1ea6b4e53128248113f9810b997d2f7ff236 | [
"MIT"
] | null | null | null | src/gateway/ocg_bss/virtual_ocg/ocg_encoder.cpp | liutongwei/ft | c75c1ea6b4e53128248113f9810b997d2f7ff236 | [
"MIT"
] | null | null | null | src/gateway/ocg_bss/virtual_ocg/ocg_encoder.cpp | liutongwei/ft | c75c1ea6b4e53128248113f9810b997d2f7ff236 | [
"MIT"
] | null | null | null | // Copyright [2020] <Copyright Kevin, kevin.lau.gd@gmail.com>
#include "virtual_ocg/ocg_encoder.h"
using namespace ft::bss;
void OcgEncoder::encode_msg(const ExecutionReport& report, MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(EXECUTION_REPORT);
header->body_fields_presence_map[0] = 0b11110011;
header->body_fields_presence_map[1] = 0b01000000;
header->body_fields_presence_map[2] = 0b00000111;
header->body_fields_presence_map[3] = 0b11000000;
encode(report.client_order_id);
encode(report.submitting_broker_id);
encode(report.security_id);
encode(report.security_id_source);
if (report.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 4);
encode(report.security_exchange);
}
if (report.broker_location_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(report.broker_location_id);
}
encode(report.transaction_time);
encode(report.side);
if (report.original_client_order_id[0] != 0) {
set_presence(header->body_fields_presence_map, 8);
encode(report.original_client_order_id);
}
encode(report.order_id);
if (report.owning_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 10);
encode(report.owning_broker_id);
}
if (report.order_type != 0) {
set_presence(header->body_fields_presence_map, 11);
encode(report.order_type);
}
if (report.price != 0) {
set_presence(header->body_fields_presence_map, 12);
encode(report.price);
}
if (report.order_quantity != 0) {
set_presence(header->body_fields_presence_map, 13);
encode(report.order_quantity);
}
if (1) {
set_presence(header->body_fields_presence_map, 14);
encode(report.tif);
}
if (report.position_effect != 0) {
set_presence(header->body_fields_presence_map, 15);
encode(report.position_effect);
}
if (report.order_restrictions[0] != 0) {
set_presence(header->body_fields_presence_map, 16);
encode(report.order_restrictions);
}
if (report.max_price_levels != 0) {
set_presence(header->body_fields_presence_map, 17);
encode(report.max_price_levels);
}
if (report.order_capacity != 0) {
set_presence(header->body_fields_presence_map, 18);
encode(report.order_capacity);
}
if (report.text.len > 0) {
set_presence(header->body_fields_presence_map, 19);
encode(report.text);
}
if (report.reason.len > 0) {
set_presence(header->body_fields_presence_map, 20);
encode(report.reason);
}
encode(report.execution_id);
encode(report.order_status);
encode(report.exec_type);
encode(report.cumulative_quantity);
encode(report.leaves_quantity);
if (report.order_reject_code != 0) {
set_presence(header->body_fields_presence_map, 26);
encode(report.order_reject_code);
}
if (report.lot_type != 0) {
set_presence(header->body_fields_presence_map, 27);
encode(report.lot_type);
}
if (report.exec_restatement_reason != 0) {
set_presence(header->body_fields_presence_map, 28);
encode(report.exec_restatement_reason);
}
if (report.cancel_reject_code != 0) {
set_presence(header->body_fields_presence_map, 29);
encode(report.cancel_reject_code);
}
if (report.match_type != 0) {
set_presence(header->body_fields_presence_map, 30);
encode(report.match_type);
}
if (report.counterparty_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 31);
encode(report.counterparty_broker_id);
}
if (report.execution_quantity != 0) {
set_presence(header->body_fields_presence_map, 32);
encode(report.execution_quantity);
}
if (report.execution_price != 0) {
set_presence(header->body_fields_presence_map, 33);
encode(report.execution_price);
}
if (report.reference_execution_id[0] != 0) {
set_presence(header->body_fields_presence_map, 34);
encode(report.reference_execution_id);
}
if (report.order_category != 0) {
set_presence(header->body_fields_presence_map, 35);
encode(report.order_category);
}
if (report.amend_reject_code != 0) {
set_presence(header->body_fields_presence_map, 36);
encode(report.amend_reject_code);
}
// 37 skip
if (report.trade_match_id[0] != 0) {
set_presence(header->body_fields_presence_map, 38);
encode(report.trade_match_id);
}
if (report.exchange_trade_type != 0) {
set_presence(header->body_fields_presence_map, 39);
encode(report.exchange_trade_type);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const TradeCaptureReportAck& ack,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(EXECUTION_REPORT);
header->body_fields_presence_map[0] = 0b11101001;
header->body_fields_presence_map[1] = 0b10110000;
encode(ack.trade_report_id);
encode(ack.trade_report_trans_type); //
encode(ack.trade_report_type);
if (ack.trade_handling_instructions != 0) {
set_presence(header->body_fields_presence_map, 3);
encode(ack.trade_handling_instructions);
}
encode(ack.submitting_broker_id);
if (ack.counterparty_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(ack.counterparty_broker_id);
}
if (ack.broker_location_id[0] != 0) {
set_presence(header->body_fields_presence_map, 6);
encode(ack.broker_location_id);
}
encode(ack.security_id);
encode(ack.security_id_source);
if (ack.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 9);
encode(ack.security_exchange);
}
encode(ack.side);
encode(ack.transaction_time);
if (ack.trade_id[0] != 0) {
set_presence(header->body_fields_presence_map, 12);
encode(ack.trade_id);
}
if (ack.trade_report_status != 0) {
set_presence(header->body_fields_presence_map, 13);
encode(ack.trade_report_status);
}
if (ack.trade_report_reject_code != 0) {
set_presence(header->body_fields_presence_map, 14);
encode(ack.trade_report_reject_code);
}
if (ack.reason.len > 0) {
set_presence(header->body_fields_presence_map, 15);
encode(ack.reason);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const QuoteStatusReport& report,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(QUOTE_STATUS_REPORT);
header->body_fields_presence_map[0] = 0b10000000;
header->body_fields_presence_map[1] = 0b10000000;
encode(report.submitting_broker_id);
if (report.broker_location_id[0] != 0) {
set_presence(header->body_fields_presence_map, 1);
encode(report.broker_location_id);
}
if (report.security_id[0] != 0) {
set_presence(header->body_fields_presence_map, 2);
encode(report.security_id);
}
if (report.security_id_source != 0) {
set_presence(header->body_fields_presence_map, 3);
encode(report.security_id_source);
}
if (report.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 4);
encode(report.security_exchange);
}
if (report.quote_bid_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(report.quote_bid_id);
}
if (report.quote_offer_id[0] != 0) {
set_presence(header->body_fields_presence_map, 6);
encode(report.quote_offer_id);
}
if (report.quote_type != 0) {
set_presence(header->body_fields_presence_map, 7);
encode(report.quote_type);
}
encode(report.transaction_time);
if (report.quote_message_id[0] != 0) {
set_presence(header->body_fields_presence_map, 9);
encode(report.quote_message_id);
}
if (report.quote_cancel_type != 0) {
set_presence(header->body_fields_presence_map, 10);
encode(report.quote_cancel_type);
}
if (report.quote_status != 0) {
set_presence(header->body_fields_presence_map, 11);
encode(report.quote_status);
}
if (report.quote_reject_code != 0) {
set_presence(header->body_fields_presence_map, 12);
encode(report.quote_reject_code);
}
if (report.reason.len > 0) {
set_presence(header->body_fields_presence_map, 13);
encode(report.reason);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const OrderMassCancelReport& report,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(ORDER_MASS_CANCEL_REPORT);
header->body_fields_presence_map[0] = 0b00000011;
header->body_fields_presence_map[1] = 0b01100000;
if (report.client_order_id[0] != 0) {
set_presence(header->body_fields_presence_map, 0);
encode(report.client_order_id);
}
if (report.submitting_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 1);
encode(report.submitting_broker_id);
}
if (report.security_id[0] != 0) {
set_presence(header->body_fields_presence_map, 2);
encode(report.security_id);
}
if (report.security_id_source != 0) {
set_presence(header->body_fields_presence_map, 4);
encode(report.security_id_source);
}
if (report.security_exchange[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(report.security_exchange);
}
encode(report.transaction_time);
encode(report.mass_cancel_request_type);
if (report.owning_broker_id[0] != 0) {
set_presence(header->body_fields_presence_map, 8);
encode(report.owning_broker_id);
}
encode(report.mass_action_report_id);
encode(report.mass_cancel_response);
if (report.mass_cancel_reject_code != 0) {
set_presence(header->body_fields_presence_map, 11);
encode(report.mass_cancel_reject_code);
}
if (report.reason.len > 0) {
set_presence(header->body_fields_presence_map, 12);
encode(report.reason);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const BusinessRejectMessage& msg,
MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(BUSINESS_MESSAGE_REJECT);
header->body_fields_presence_map[0] = 0b10100000;
encode(msg.business_reject_code);
if (msg.reason.len > 0) {
set_presence(header->body_fields_presence_map, 1);
encode(msg.reason);
}
encode(msg.reference_message_type);
if (msg.reference_field_name[0] != 0) {
set_presence(header->body_fields_presence_map, 3);
encode(msg.reference_field_name);
}
if (msg.reference_sequence_number > 0) {
set_presence(header->body_fields_presence_map, 4);
encode(msg.reference_sequence_number);
}
if (msg.business_reject_reference_id[0] != 0) {
set_presence(header->body_fields_presence_map, 5);
encode(msg.business_reject_reference_id);
}
fill_header_and_trailer();
}
void OcgEncoder::encode_msg(const LookupResponse& rsp, MsgBuffer* buffer) {
buffer->size = 0;
cur_msg_buf_ = buffer;
auto header = encode_header(LOOKUP_RESPONSE);
header->sequence_number = 1;
header->body_fields_presence_map[0] = 0b10000000;
encode(rsp.status);
if (rsp.status != LOOKUP_SERVICE_ACCEPTED) {
set_presence(header->body_fields_presence_map, 1);
encode(rsp.lookup_reject_code);
}
if (rsp.reason.len > 0) {
set_presence(header->body_fields_presence_map, 2);
encode(rsp.reason);
}
if (rsp.status == LOOKUP_SERVICE_ACCEPTED) {
set_presence(header->body_fields_presence_map, 3);
set_presence(header->body_fields_presence_map, 4);
set_presence(header->body_fields_presence_map, 5);
set_presence(header->body_fields_presence_map, 6);
encode(rsp.primary_ip);
encode(rsp.primary_port);
encode(rsp.secondary_ip);
encode(rsp.secondary_port);
}
fill_header_and_trailer();
}
| 32.34072 | 79 | 0.719572 | liutongwei |
8d31fe997730fd6090d6480468af8a0edfcd27e4 | 4,788 | cpp | C++ | GerchbergSaxton/test.cpp | daelsepara/hipSLM | bb85cc24413e2bb7517b85e9cca45dd42fd2baf7 | [
"MIT"
] | 1 | 2021-08-30T15:26:22.000Z | 2021-08-30T15:26:22.000Z | GerchbergSaxton/test.cpp | daelsepara/hipSLM | bb85cc24413e2bb7517b85e9cca45dd42fd2baf7 | [
"MIT"
] | 1 | 2021-09-30T19:23:14.000Z | 2021-09-30T19:23:22.000Z | GerchbergSaxton/test.cpp | daelsepara/hipSLM | bb85cc24413e2bb7517b85e9cca45dd42fd2baf7 | [
"MIT"
] | null | null | null | #define _USE_MATH_DEFINES
#include "../Includes/lodepng.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dlfcn.h>
#include <stdexcept>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif // !M_PI
#undef min
#undef max
// Allocate double array on host
double* Double(int Length, double val)
{
auto host = (double*)malloc(Length * sizeof(double));
if (host != NULL)
{
for (auto x = 0; x < Length; x++)
{
host[x] = val;
}
}
return host;
}
void phasepng(const char* filename, double* data, int gray, int xdim, int ydim)
{
unsigned char* buffer = (unsigned char*)malloc(xdim * ydim);
for (int index = 0; index < xdim * ydim; index++)
{
unsigned char c = (unsigned char)((double)gray * (data[index]) / (2.0 * M_PI));
buffer[index] = c;
}
unsigned error = lodepng_encode_file(filename, buffer, xdim, ydim, LCT_GREY, 8);
if (error)
{
fprintf(stderr, "error %u: %s\n", error, lodepng_error_text(error));
}
free(buffer);
}
void amppng(const char* filename, double* data, int xdim, int ydim, double scale = 1.0)
{
unsigned char* buffer = (unsigned char*)malloc(xdim * ydim);
for (int index = 0; index < xdim * ydim; index++)
{
unsigned char c = (unsigned char)(data[index] * scale);
buffer[index] = c;
}
unsigned error = lodepng_encode_file(filename, buffer, xdim, ydim, LCT_GREY, 8);
if (error)
{
fprintf(stderr, "error %u: %s\n", error, lodepng_error_text(error));
}
free(buffer);
}
inline double Mod(double a, double m)
{
return a - m * floor(a / m);
}
double* loadpng(const char* filename, int& xdim, int& ydim, double scale = 1.0)
{
unsigned error;
unsigned char* image;
unsigned w, h;
// load PNG
error = lodepng_decode24_file(&image, &w, &h, filename);
// exit on error
if (error)
{
fprintf(stderr, "decoder error %u: %s\n", error, lodepng_error_text(error));
exit(1);
}
// allocate w x h double image
int memsize = w * h * sizeof(double);
auto png = (double*)malloc(memsize);
if (!png)
{
fprintf(stderr, "unable to allocate %u bytes for image\n", memsize);
exit(1);
}
for (int index = 0; index < (int)(w * h); index++)
{
unsigned char r, g, b;
r = image[3 * index + 0]; // red
g = image[3 * index + 1]; // green
b = image[3 * index + 2]; // blue
// convert RGB to grey
auto val = (0.299 * (double)r + 0.587 * (double)g + 0.114 * (double)b) * scale;
png[index] = val;
}
xdim = w;
ydim = h;
free(image);
return png;
}
void ParseInt(std::string arg, const char* str, const char* var, int& dst)
{
auto len = strlen(str);
if (len > 0)
{
if (!arg.compare(0, len, str) && arg.length() > len)
{
try
{
auto val = stoi(arg.substr(len));
fprintf(stderr, "... %s = %d\n", var, val);
dst = val;
}
catch (const std::invalid_argument& ia)
{
fprintf(stderr, "... %s = NaN %s\n", var, ia.what());
exit(1);
}
}
}
}
int main(int argc, char** argv)
{
auto M = 800; // SLM width in # of pixels
auto N = 600; // SLM height in # of pixels
auto Ngs = 1000; // Ngs
auto gpu = false;
char InputFile[200];
InputFile[0] = '\0';
for (int i = 0; i < argc; i++)
{
std::string arg = argv[i];
std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower);
ParseInt(arg, "/m=", "SLM Width", M);
ParseInt(arg, "/n=", "SLM Height", N);
ParseInt(arg, "/i=", "GS Iterations", Ngs);
if (!arg.compare(0, 8, "/target=") && arg.length() > 8)
{
strncpy(InputFile, &argv[i][8], sizeof(InputFile));
}
if (!arg.compare("/gpu"))
{
gpu = true;
fprintf(stderr, "... use GPU\n");
}
}
if (strlen(InputFile) > 0)
{
int targetw;
int targeth;
double* target = loadpng(InputFile, targetw, targeth, 1.0);
double h = 20e-6; // hologram pixel size
bool gaussian = false;
double r = 960e-6; // input gaussian beam waist
// No aperture
int aperture = 0;
int aperturew = targetw;
int apertureh = targeth;
char Libname[200];
void *lib_handle;
void (*Calculate)(int, void**);
char *error;
sprintf(Libname, "./GerchbergSaxton.so");
lib_handle = dlopen(Libname, RTLD_LAZY);
if (!lib_handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(1);
}
Calculate = (void (*)(int, void**)) dlsym(lib_handle, "Calculate");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(1);
}
double *GerchbergSaxtonPhase = Double(M * N, 0.0);
// Gerchberg-Saxton
void* Params[] = { GerchbergSaxtonPhase, &M, &N, &Ngs, &h, &gaussian, &r, &aperture, &aperturew, &apertureh, target, &targetw, &targeth, &gpu };
(*Calculate)(14, Params);
phasepng("phase-gs.png", GerchbergSaxtonPhase, 255, M, N);
free(GerchbergSaxtonPhase);
free(target);
}
return 0;
}
| 19.703704 | 146 | 0.606099 | daelsepara |
8d33cce301e5c6bec2ee950e812d8b47ca6892c8 | 12,594 | cpp | C++ | test/window/comoment_suite.cpp | breese/trial.online | d28f8025082682ce10d9eb97c63ed0d4e62c7511 | [
"BSL-1.0"
] | 6 | 2017-11-19T15:12:33.000Z | 2021-12-18T08:21:45.000Z | test/window/comoment_suite.cpp | breese/trial.online | d28f8025082682ce10d9eb97c63ed0d4e62c7511 | [
"BSL-1.0"
] | 1 | 2019-02-20T11:28:49.000Z | 2019-02-20T11:28:49.000Z | test/window/comoment_suite.cpp | breese/trial.online | d28f8025082682ce10d9eb97c63ed0d4e62c7511 | [
"BSL-1.0"
] | 2 | 2019-02-19T16:00:03.000Z | 2020-10-29T08:26:44.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018 Bjorn Reese <breese@users.sourceforge.net>
//
// 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 <trial/online/detail/lightweight_test.hpp>
#include <trial/online/detail/functional.hpp>
#include <trial/online/window/moment.hpp>
#include <trial/online/window/comoment.hpp>
using namespace trial::online;
//-----------------------------------------------------------------------------
namespace properties_suite
{
void test_constant()
{
// Cov(X, a) = 0
const double a = 0.0;
window::covariance<double, 32> filter;
filter.push(0.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
filter.push(1.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
filter.push(10.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
filter.push(100.0, a);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
}
void test_same()
{
// Cov(X, X) = Var(X)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> filter;
window::moment_variance<double, 32> average;
{
double x = 0.0;
filter.push(x, x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.0, tolerance);
TRIAL_TEST_WITH(filter.variance(), 0.0, tolerance);
average.push(x);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
{
double x = 1.0;
filter.push(x, x);
average.push(x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.5, tolerance);
TRIAL_TEST_WITH(filter.variance(), 0.25, tolerance);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
{
double x = 10.0;
filter.push(x, x);
average.push(x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 30.333333, tolerance);
TRIAL_TEST_WITH(filter.variance(), 20.222222, tolerance);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
{
double x = 100.0;
filter.push(x, x);
average.push(x);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2340.25, tolerance);
TRIAL_TEST_WITH(filter.variance(), 1755.1875, tolerance);
TRIAL_TEST_WITH(filter.variance(), average.variance(), tolerance);
}
}
void test_commutative()
{
// Cov(X, Y) = Cov(Y, X)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> lhs;
window::covariance<double, 32> rhs;
{
const double x = 0.0;
const double y = 0.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -1.0;
const double y = 1.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -2.0;
const double y = 10.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -3.0;
const double y = 100.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -4.0;
const double y = 1000.0;
lhs.push(x, y);
rhs.push(y, x);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
}
void test_distributive()
{
// Cov(aX, bY) = ab Cov(Y, X)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> lhs;
window::covariance<double, 32> rhs;
const double a = 0.5;
const double b = 2.0;
{
const double x = 0.0;
const double y = 0.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -1.0;
const double y = 1.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -2.0;
const double y = 10.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -3.0;
const double y = 100.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
{
const double x = -4.0;
const double y = 1000.0;
lhs.push(a * x, b * y);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), a * b * rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), a * b * rhs.variance(), tolerance);
}
}
void test_shift_invariant()
{
// Cov(X + a, Y + b) = Cov(X, Y)
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 32> lhs;
window::covariance<double, 32> rhs;
const double a = 0.5;
const double b = 2.0;
{
const double x = 0.0;
const double y = 0.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -1.0;
const double y = 1.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -2.0;
const double y = 10.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -3.0;
const double y = 100.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
{
const double x = -4.0;
const double y = 1000.0;
lhs.push(x + a, y + b);
rhs.push(x, y);
TRIAL_TEST_WITH(lhs.unbiased_variance(), rhs.unbiased_variance(), tolerance);
TRIAL_TEST_WITH(lhs.variance(), rhs.variance(), tolerance);
}
}
void run()
{
test_constant();
test_same();
test_commutative();
test_distributive();
test_shift_invariant();
}
} // namespace properties_suite
//-----------------------------------------------------------------------------
namespace double_suite
{
void test_empty()
{
window::covariance<double, 4> filter;
TRIAL_TEST_EQ(filter.size(), 0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
}
void test_same_no_increment()
{
window::covariance<double, 4> filter;
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
}
void test_same_increment_by_one()
{
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 4> filter;
filter.push(1.0, 1.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(2.0, 2.0);
TRIAL_TEST_WITH(filter.variance(), 0.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.5, tolerance);
filter.push(3.0, 3.0);
TRIAL_TEST_WITH(filter.variance(), 0.666667, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 1.0, tolerance);
filter.push(4.0, 4.0);
TRIAL_TEST_WITH(filter.variance(), 1.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 1.666667, tolerance);
// Window full
filter.push(5.0, 5.0);
TRIAL_TEST_WITH(filter.variance(), 1.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 1.666667, tolerance);
}
void test_same_increment_by_half()
{
const auto tolerance = detail::close_to<double>(1e-6);
window::covariance<double, 4> filter;
filter.push(1.0, 1.0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(1.5, 1.5);
TRIAL_TEST_WITH(filter.variance(), 0.0625, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.125, tolerance);
filter.push(2.0, 2.0);
TRIAL_TEST_WITH(filter.variance(), 0.1666667, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.25, tolerance);
filter.push(2.5, 2.5);
TRIAL_TEST_WITH(filter.variance(), 0.3125, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.416667, tolerance);
// Window full
filter.push(3.0, 3.0);
TRIAL_TEST_WITH(filter.variance(), 0.3125, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 0.416667, tolerance);
}
void test_exponential_increase()
{
const auto tolerance = detail::close_to<double>(1e-5);
window::covariance<double, 4> filter;
filter.push(1e0, 1e0);
TRIAL_TEST_EQ(filter.variance(), 0.0);
TRIAL_TEST_EQ(filter.unbiased_variance(), 0.0);
filter.push(1e1, 1e1);
TRIAL_TEST_WITH(filter.variance(), 20.25, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 40.5, tolerance);
filter.push(1e2, 1e2);
TRIAL_TEST_WITH(filter.variance(), 1998.0, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2997.0, tolerance);
filter.push(1e3, 1e3);
TRIAL_TEST_WITH(filter.variance(), 1.7538e5, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e5, tolerance);
filter.push(1e4, 1e4);
TRIAL_TEST_WITH(filter.variance(), 1.7538e7, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e7, tolerance);
filter.push(1e5, 1e5);
TRIAL_TEST_WITH(filter.variance(), 1.7538e9, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e9, tolerance);
filter.push(1e6, 1e6);
TRIAL_TEST_WITH(filter.variance(), 1.7538e11, tolerance);
TRIAL_TEST_WITH(filter.unbiased_variance(), 2.3384e11, tolerance);
}
void test_clear()
{
window::covariance<double, 4> filter;
TRIAL_TEST_EQ(filter.size(), 0);
filter.push(0.0, 0.0);
TRIAL_TEST_EQ(filter.size(), 1);
filter.clear();
TRIAL_TEST_EQ(filter.size(), 0);
}
void run()
{
test_empty();
test_clear();
test_same_no_increment();
test_same_increment_by_one();
test_same_increment_by_half();
test_exponential_increase();
}
} // namespace double_suite
//-----------------------------------------------------------------------------
// main
//-----------------------------------------------------------------------------
int main()
{
properties_suite::run();
double_suite::run();
return boost::report_errors();
}
| 33.31746 | 93 | 0.607035 | breese |
8d34c7bae19e7362e8219977ccad3b3ffe386c1c | 468 | cpp | C++ | map/extra features.cpp | FirdausJawed/DSA | caf72a4606746009bc4616bfe11cdcb6ca103dcd | [
"MIT"
] | 2 | 2021-08-31T11:20:29.000Z | 2021-09-05T10:51:36.000Z | map/extra features.cpp | FirdausJawed/DSA | caf72a4606746009bc4616bfe11cdcb6ca103dcd | [
"MIT"
] | null | null | null | map/extra features.cpp | FirdausJawed/DSA | caf72a4606746009bc4616bfe11cdcb6ca103dcd | [
"MIT"
] | 1 | 2021-09-01T14:30:49.000Z | 2021-09-01T14:30:49.000Z | #include<bits/stdc++.h>
using namespace std;
void print (map<int,string>&m){
cout<<m.size()<<endl;
for(auto pr:m){
cout<<pr.first<<" "<<pr.second<<endl;
}
}
int main(){
map<int,string>m;
m[1]="fj";
m[5]="fird";
m[3]="muskan";
m[2]="tgb";
m[7]="firdaus";
m.insert({4,"the great fj"});
int x;
cin>>x;
auto it = m.find(x);
if (it != m.end())
{
cout<<"yes "<<m[x]<<endl;
}
else{
cout<<"no"<<endl;
}
//print(m);
return 0;
} | 14.625 | 45 | 0.510684 | FirdausJawed |
8d35a94753a14a68fcbd9857667d9f59ba0332fc | 199 | hpp | C++ | src/modules/osg/generated_code/StateSet.pypp.hpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osg/generated_code/StateSet.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osg/generated_code/StateSet.pypp.hpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#ifndef StateSet_hpp__pyplusplus_wrapper
#define StateSet_hpp__pyplusplus_wrapper
void register_StateSet_class();
#endif//StateSet_hpp__pyplusplus_wrapper
| 22.111111 | 40 | 0.844221 | JaneliaSciComp |
8d397e79a3dc52bf5a40f85b8e6431fca4fd4789 | 840 | cc | C++ | ports/www/chromium-legacy/newport/files/patch-content_shell_app_shell__main__delegate.cc | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ports/www/chromium-legacy/newport/files/patch-content_shell_app_shell__main__delegate.cc | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ports/www/chromium-legacy/newport/files/patch-content_shell_app_shell__main__delegate.cc | danielfojt/DeltaPorts | 5710b4af4cacca5eb1ac577df304c788c07c4217 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | --- content/shell/app/shell_main_delegate.cc.orig 2019-10-21 19:06:33 UTC
+++ content/shell/app/shell_main_delegate.cc
@@ -170,7 +170,7 @@ bool ShellMainDelegate::BasicStartupComplete(int* exit
v8_crashpad_support::SetUp();
#endif
-#if defined(OS_LINUX)
+#if defined(OS_LINUX) || defined(OS_BSD)
breakpad::SetFirstChanceExceptionHandler(v8::TryHandleWebAssemblyTrapPosix);
#endif
#if defined(OS_MACOSX)
@@ -317,7 +317,7 @@ bool ShellMainDelegate::BasicStartupComplete(int* exit
}
void ShellMainDelegate::PreSandboxStartup() {
-#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
+#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_BSD))
// Create an instance of the CPU class to parse /proc/cpuinfo and cache
// cpu_brand info.
base::CPU cpu_info;
| 40 | 98 | 0.746429 | danielfojt |
8d3983fdcc301d428f164a2773dacad7b52f6844 | 742 | hpp | C++ | src/hash_map.hpp | ecnerwala/cp-book | 89ba206e1d65ab48819d956d76073057fb43434e | [
"CC0-1.0"
] | 351 | 2019-11-26T14:56:22.000Z | 2022-03-30T10:40:13.000Z | src/hash_map.hpp | Mastermind-git/cp-book | 53d97ec192a60e2956c2b4fbe17840ab74c066d6 | [
"CC0-1.0"
] | 8 | 2019-12-24T21:37:19.000Z | 2021-05-17T07:33:55.000Z | src/hash_map.hpp | Mastermind-git/cp-book | 53d97ec192a60e2956c2b4fbe17840ab74c066d6 | [
"CC0-1.0"
] | 57 | 2020-04-28T09:20:17.000Z | 2022-02-13T09:35:31.000Z | #pragma once
#include<bits/stdc++.h>
#include<bits/extc++.h>
struct splitmix64_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = std::chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
template <typename K, typename V, typename Hash = splitmix64_hash>
using hash_map = __gnu_pbds::gp_hash_table<K, V, Hash>;
template <typename K, typename Hash = splitmix64_hash>
using hash_set = hash_map<K, __gnu_pbds::null_type, Hash>;
| 28.538462 | 99 | 0.700809 | ecnerwala |
8d3d220db6678fa822eb0358f6a79288b9a21f3f | 624 | cpp | C++ | Nmeetings.cpp | KaranKaira/Questions-Algorithms | c6416592d335be94656f3d58a01c972059d41528 | [
"MIT"
] | null | null | null | Nmeetings.cpp | KaranKaira/Questions-Algorithms | c6416592d335be94656f3d58a01c972059d41528 | [
"MIT"
] | null | null | null | Nmeetings.cpp | KaranKaira/Questions-Algorithms | c6416592d335be94656f3d58a01c972059d41528 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct job{
int st, end,ind;
};
bool comp(job a,job b)
{
return a.end < b.end;
}
int main() {
int t;cin>>t;while(t--)
{
int n;cin>>n;
job a[n];
for(int i=0;i<n;i++) cin>>a[i].st;
for(int i=0;i<n;i++) {cin>>a[i].end;a[i].ind = i+1;}
sort(a,a+n,comp);
int k=0;
cout<<a[k].ind<<" ";
for(int i=1;i<n;i++)
{
if(a[i].st >= a[k].end) {
cout<<a[i].ind<<" ";
k = i;
}
}
cout<<endl;
}
return 0;
}
| 18.909091 | 60 | 0.375 | KaranKaira |
8d3d9425d2a317b010def452cc92830e97ca601e | 18,622 | cpp | C++ | Plugins/Main/mcplugin_main.cpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | null | null | null | Plugins/Main/mcplugin_main.cpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | null | null | null | Plugins/Main/mcplugin_main.cpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | null | null | null | /*++
Copyright (C) 2020 Autodesk Inc.
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 Autodesk Inc. 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 AUTODESK INC. 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 "libmcplugin_statefactory.hpp"
#include "libmcplugin_interfaceexception.hpp"
#include "libmcplugin_state.hpp"
using namespace LibMCPlugin::Impl;
#include "libmcenv_drivercast.hpp"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4250)
#endif
/*************************************************************************************************************************
Class definition of CMainData
**************************************************************************************************************************/
class CMainData : public virtual CPluginData {
protected:
public:
};
/*************************************************************************************************************************
Class definition of CMainState
**************************************************************************************************************************/
typedef CState<CMainData> CMainState;
/*************************************************************************************************************************
Class definition of CMainState_Init
**************************************************************************************************************************/
class CMainState_Init : public virtual CMainState {
public:
CMainState_Init(const std::string& sStateName, PPluginData pPluginData)
: CMainState (getStateName (), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "init";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Initializing...");
pStateEnvironment->SetIntegerParameter("jobinfo", "layercount", 0);
pStateEnvironment->SetIntegerParameter("jobinfo", "currentlayer", 0);
pStateEnvironment->SetBoolParameter("jobinfo", "printinprogress", false);
pStateEnvironment->SetNextState("idle");
}
};
/*************************************************************************************************************************
Class definition of CMainState_Idle
**************************************************************************************************************************/
class CMainState_Idle : public virtual CMainState {
public:
CMainState_Idle(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "idle";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
LibMCEnv::PSignalHandler pSignalHandler;
double targetO2 = pStateEnvironment->GetDoubleParameter("processsettings", "targeto2");
pStateEnvironment->SetDoubleParameter("processsettings", "targeto2", targetO2 + 1.0);
pStateEnvironment->SetBoolParameter("ui", "preparebuilddisabled", !pStateEnvironment->GetBoolParameter("ui", "preparebuilddisabled"));
pStateEnvironment->LogMessage ("Waiting for user input...");
if (pStateEnvironment->WaitForSignal("signal_preparebuildjob", 100, pSignalHandler)) {
auto sJobUUID = pSignalHandler->GetUUID("jobuuid");
pStateEnvironment->SetStringParameter("jobinfo", "jobuuid", sJobUUID);
pSignalHandler->SignalHandled();
pStateEnvironment->LogMessage("Preparing job " + sJobUUID);
pStateEnvironment->SetNextState("preparebuild");
}
else if (pStateEnvironment->WaitForSignal("signal_changeprocesssettings", 100, pSignalHandler)) {
double dTargetO2 = pSignalHandler->GetDouble("targeto2");
double dRecoaterSpeed = pSignalHandler->GetDouble("recoaterspeed");
double dGasFlowSpeed = pSignalHandler->GetDouble("gasflowspeed");
pSignalHandler->SignalHandled();
pStateEnvironment->SetDoubleParameter("processsettings", "targeto2", dTargetO2);
pStateEnvironment->SetDoubleParameter("processsettings", "recoaterspeed", dRecoaterSpeed);
pStateEnvironment->SetDoubleParameter("processsettings", "gasflowspeed", dGasFlowSpeed);
pStateEnvironment->LogMessage("Updated process Parameters!");
pStateEnvironment->SetNextState("idle");
}
else {
pStateEnvironment->SetNextState("idle");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_PrepareBuild
**************************************************************************************************************************/
class CMainState_PrepareBuild : public virtual CMainState {
public:
CMainState_PrepareBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "preparebuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Waiting for build preparation...");
LibMCEnv::PSignalHandler pSignalHandler;
if (pStateEnvironment->WaitForSignal("signal_cancelbuildpreparation", 100, pSignalHandler)) {
pStateEnvironment->SetStringParameter("jobinfo", "jobuuid", "00000000-0000-0000-0000-000000000000");
pSignalHandler->SignalHandled();
pStateEnvironment->SetNextState("idle");
}
else if (pStateEnvironment->WaitForSignal("signal_startbuild", 100, pSignalHandler)) {
pSignalHandler->SignalHandled();
pStateEnvironment->SetNextState("initbuild");
}
else {
pStateEnvironment->SetNextState("preparebuild");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_InitBuild
**************************************************************************************************************************/
class CMainState_InitBuild : public virtual CMainState {
public:
CMainState_InitBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "initbuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Initializing build...");
auto sJobUUID = pStateEnvironment->GetUUIDParameter("jobinfo", "jobuuid");
pStateEnvironment->LogMessage("Loading Toolpath...");
auto pBuildJob = pStateEnvironment->GetBuildJob (sJobUUID);
pBuildJob->LoadToolpath();
auto sJobName = pBuildJob->GetName();
auto nLayerCount = pBuildJob->GetLayerCount();
pStateEnvironment->LogMessage("Job Name: " + sJobName);
pStateEnvironment->LogMessage("Layer Count: " + std::to_string (nLayerCount));
pStateEnvironment->SetIntegerParameter("jobinfo", "currentlayer", 0);
pStateEnvironment->SetIntegerParameter("jobinfo", "layercount", nLayerCount);
pStateEnvironment->Sleep(1000);
pStateEnvironment->LogMessage("Waiting for atmosphere...");
pStateEnvironment->Sleep(3000);
pStateEnvironment->SetNextState("beginlayer");
}
};
/*************************************************************************************************************************
Class definition of CMainState_BeginLayer
**************************************************************************************************************************/
class CMainState_BeginLayer : public virtual CMainState {
public:
CMainState_BeginLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "beginlayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
auto nLayer = pStateEnvironment->GetIntegerParameter("jobinfo", "currentlayer");
pStateEnvironment->LogMessage("Starting layer " + std::to_string (nLayer));
pStateEnvironment->SetNextState("recoatlayer");
}
};
/*************************************************************************************************************************
Class definition of CMainState_BeginLayer
**************************************************************************************************************************/
class CMainState_RecoatLayer : public virtual CMainState {
public:
CMainState_RecoatLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "recoatlayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Recoating layer...");
auto nRecoatingTimeOut = pStateEnvironment->GetIntegerParameter("jobinfo", "recoatingtimeout");
auto pSignal = pStateEnvironment->PrepareSignal("plc", "signal_recoatlayer");
pSignal->Trigger();
if (pSignal->WaitForHandling((uint32_t)nRecoatingTimeOut)) {
if (pSignal->GetBoolResult("success")) {
pStateEnvironment->LogMessage("Recoating successful...");
pStateEnvironment->SetNextState("exposelayer");
}
else {
pStateEnvironment->LogMessage("Recoating failed...");
pStateEnvironment->SetNextState("fatalerror");
}
}
else {
pStateEnvironment->LogMessage("Recoating timeout...");
pStateEnvironment->SetNextState("fatalerror");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_ExposeLayer
**************************************************************************************************************************/
class CMainState_ExposeLayer : public virtual CMainState {
public:
CMainState_ExposeLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "exposelayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Exposing layer...");
auto sJobUUID = pStateEnvironment->GetStringParameter("jobinfo", "jobuuid");
auto nCurrentLayer = pStateEnvironment->GetIntegerParameter("jobinfo", "currentlayer");
auto nExposureTimeOut = pStateEnvironment->GetIntegerParameter("jobinfo", "exposuretimeout");
auto pSignal = pStateEnvironment->PrepareSignal("laser", "signal_exposure");
pSignal->SetString("jobuuid", sJobUUID);
pSignal->SetInteger("layerindex", nCurrentLayer);
pSignal->SetInteger("timeout", nExposureTimeOut);
pSignal->Trigger();
if (pSignal->WaitForHandling((uint32_t)nExposureTimeOut)) {
pStateEnvironment->LogMessage("Layer successfully exposed...");
pStateEnvironment->SetNextState("finishlayer");
}
else {
pStateEnvironment->LogMessage("Layer exposure failed...");
pStateEnvironment->SetNextState("fatalerror");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_FinishLayer
**************************************************************************************************************************/
class CMainState_FinishLayer : public virtual CMainState {
public:
CMainState_FinishLayer(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "finishlayer";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
auto nLayer = pStateEnvironment->GetIntegerParameter("jobinfo", "currentlayer");
auto nLayerCount = pStateEnvironment->GetIntegerParameter("jobinfo", "layercount");
pStateEnvironment->LogMessage("Finished layer " + std::to_string (nLayer));
nLayer++;
pStateEnvironment->SetIntegerParameter("jobinfo", "currentlayer", nLayer);
if (nLayer < nLayerCount) {
pStateEnvironment->SetNextState("beginlayer");
}
else {
pStateEnvironment->SetNextState("finishbuild");
}
}
};
/*************************************************************************************************************************
Class definition of CMainState_FinishBuild
**************************************************************************************************************************/
class CMainState_FinishBuild : public virtual CMainState {
public:
CMainState_FinishBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "finishbuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Finishing Build...");
pStateEnvironment->LogMessage("Turning laser off...");
pStateEnvironment->Sleep(1000);
pStateEnvironment->SetNextState("idle");
}
};
/*************************************************************************************************************************
Class definition of CMainState_PauseBuild
**************************************************************************************************************************/
class CMainState_PauseBuild : public virtual CMainState {
public:
CMainState_PauseBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "pausebuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Build paused");
pStateEnvironment->Sleep(3000);
pStateEnvironment->SetNextState("pausebuild");
}
};
/*************************************************************************************************************************
Class definition of CMainState_FatalError
**************************************************************************************************************************/
class CMainState_FatalError : public virtual CMainState {
public:
CMainState_FatalError(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "fatalerror";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
// Unload all toolpathes that might be in memory
pStateEnvironment->UnloadAllToolpathes();
pStateEnvironment->SetNextState("fatalerror");
}
};
/*************************************************************************************************************************
Class definition of CMainState_CancelBuild
**************************************************************************************************************************/
class CMainState_CancelBuild : public virtual CMainState {
public:
CMainState_CancelBuild(const std::string& sStateName, PPluginData pPluginData)
: CMainState(getStateName(), sStateName, pPluginData)
{
}
static const std::string getStateName()
{
return "cancelbuild";
}
void Execute(LibMCEnv::PStateEnvironment pStateEnvironment)
{
pStateEnvironment->LogMessage("Canceling Build...");
pStateEnvironment->LogMessage("Turning laser off...");
pStateEnvironment->Sleep(1000);
pStateEnvironment->SetNextState("idle");
}
};
/*************************************************************************************************************************
Class definition of CStateFactory
**************************************************************************************************************************/
CStateFactory::CStateFactory(const std::string& sInstanceName)
{
m_pPluginData = std::make_shared<CMainData>();
}
IState * CStateFactory::CreateState(const std::string & sStateName)
{
IState* pStateInstance = nullptr;
if (createStateInstanceByName<CMainState_Init>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_Idle>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_FatalError>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_PrepareBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_InitBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_BeginLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_RecoatLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_ExposeLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_FinishLayer>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_FinishBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_PauseBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
if (createStateInstanceByName<CMainState_CancelBuild>(sStateName, pStateInstance, m_pPluginData))
return pStateInstance;
throw ELibMCPluginInterfaceException(LIBMCPLUGIN_ERROR_INVALIDSTATENAME);
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
| 31.509306 | 136 | 0.619106 | alexanderoster |
8d408677d1cfba6b8bae0aa9395cf5ca37691f5c | 4,016 | cpp | C++ | 14.image_text_glut/text.cpp | JackeyLea/OpenGL_Freshman | d17468d7f2faf752c9a0ccb8f12a2ca4cb8e3a91 | [
"MIT"
] | 1 | 2022-02-08T01:24:50.000Z | 2022-02-08T01:24:50.000Z | 14.image_text_glut/text.cpp | JackeyLea/OpenGL_Beginner | d17468d7f2faf752c9a0ccb8f12a2ca4cb8e3a91 | [
"MIT"
] | null | null | null | 14.image_text_glut/text.cpp | JackeyLea/OpenGL_Beginner | d17468d7f2faf752c9a0ccb8f12a2ca4cb8e3a91 | [
"MIT"
] | null | null | null | ///
/// \note 加载字体并显示文字
///
#include <GL/gl.h>
#include <GL/glut.h>
#include <GL/glx.h>
#include <unistd.h>//延时
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#define ESCAPE 27//esc键ASCII码值
int window; //glut窗口标识号
GLuint base;//字体集的基本显示列表
GLfloat cnt1;//用于移动文字和颜色的计数器
GLfloat cnt2;//同上
void buildFont(){
Display *dpy;
XFontStruct *fontInfo;//存储字体
base = glGenLists(96);//存储96个字符
/*
加载字体。
你拥有什么字体由操作系统决定,
我的系统中字体位于/usr/X11R6/lib/X11/fonts/*,
同时包含fonts.alias和fonts.dir文件来说明.pcf.gz文件中是什么字体。
在任何情况下,你的系统应该至少包含一种字体,否则你将看不见任何文字
获取当前显示。
这将根据环境变量打开与显示服务的第二个连接,并且至少持续到加载完字体为止。
*/
dpy = XOpenDisplay(NULL);//默认为环境变量值
fontInfo = XLoadQueryFont(dpy,"-adobe-helvetica-medium-r-normal--18-*-*-*-p-*-iso8859-1");
if(fontInfo==NULL){
fontInfo = XLoadQueryFont(dpy,"fixed");
if(fontInfo==NULL){
std::cout<<"No X font found.\n"<<std::endl;
}
}
/*
加载字体信息之后,可以处理(旋转、缩放等)字体
*/
/*
从32(空格)开始,获取96个字符(z之后的一些字符),将其存储在base中
*/
glXUseXFont(fontInfo->fid,32,96,base);
//获取完显示列表后缩放内存
XFreeFont(dpy,fontInfo);
//关闭与显示服务器的连接
XCloseDisplay(dpy);
}
void killFont(){
glDeleteLists(base,96);//删除全部96个字符
}
//自定义显示方法
void glPrint(char *text){
if(text==NULL){//没有东西显示就退出
return ;
}
glPushAttrib(GL_LIST_BIT);//我们将通过glListBase偏移显示列表
glListBase(base-32);//设置基准字符为32
glCallLists(strlen(text),GL_UNSIGNED_BYTE,text);//绘制显示文本
glPopAttrib();//取消glPushAtrrib的功能
}
//初始化函数,设置所有初始化值
void initGL(int width, int height)
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //将界面背景清空为红绿蓝alpha值对应的颜色
glClearDepth(1.0);//设置清空深度缓冲区(depth buffer)
glDepthFunc(GL_LESS);//设置深度测试的类型
glEnable(GL_DEPTH_TEST);//设置进行深度测试(depth test)
glShadeModel(GL_SMOOTH);//栅格化模式为平滑,只有平滑和两种模式
glMatrixMode(GL_PROJECTION);//矩阵模式为投影模式
glLoadIdentity();//重置投影矩阵
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);//计算窗口的显示比例
glMatrixMode(GL_MODELVIEW);//
buildFont();
}
//OpenGL的主要绘图函数,绘制什么显示什么。
void displayGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//清空界面和depth缓冲区
glLoadIdentity();//调整视场
glTranslatef(0.0f,0.0f,-1.0f);//平移
//基于文本位置的颜色
glColor3f(1.0f*((float)(cos(cnt1))),1.0f*((float)(sin(cnt2))),1.0f-0.5f*((float)(cos(cnt1+cnt2))));
//文本在屏幕的位置
glRasterPos2f(-0.2f+0.35f*((float)(cos(cnt1))),0.35f*((float)(sin(cnt2))));
glPrint("My name is JackeyLea");//显示文本
cnt1+=0.001f;
cnt2+=0.0081f;
//双缓冲技术,交换缓冲区以显示刚刚绘制的图像
glutSwapBuffers();
}
// 窗口大小变化回调函数
void reshapeGL(int w, int h)
{
if(h==0){//防止出现长度为0的情况,尤其是下面还将h用作除数
h=1;
}
glViewport(0, 0, w, h);//重置当前窗口的视场和角度
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, static_cast<GLfloat>(w/h),0.1f,100.0f); //设置长宽视景
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
//如果有按键按下调用此函数
void keyboard(unsigned char key, int x, int y)
{
usleep(100);//稍微延时以免干扰
if (key == ESCAPE)//如果是escape键
{
glutDestroyWindow(window); //销毁窗口
exit(0);//正常退出程序
}
}
int main(int argc,char **argv)
{
//初始化glut状态,并且接管所有传给程序的参数
glutInit(&argc, argv);
//设置显示模式:双缓冲、RGBA颜色、alpha支持、depth缓冲支持
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
// 初始化窗口
glutInitWindowSize(640, 480); //初始界面大小
glutInitWindowPosition(100, 100); //界面初始位置,相对于屏幕左上角的像素值
//创建界面,界面标题为argv[0],即程序名称,也可以以字符串进行指定
//同时获取创建的窗口ID号,销毁时使用
window = glutCreateWindow(argv[0]);
glutIdleFunc(&displayGL);//即使没有任何事件,也重绘场景
glutReshapeFunc(&reshapeGL);//注册调整窗口大小回调函数
glutDisplayFunc(&displayGL);//注册主要绘图回调函数
glutKeyboardFunc(&keyboard);//注册键盘回调函数
initGL(640,480);//初始化窗口
glutMainLoop();//开始事件处理引擎
return 0;
}
| 23.213873 | 104 | 0.630976 | JackeyLea |
8d427a9c0dc7f0a1a80d092a1643a661f7d54740 | 1,260 | cpp | C++ | Pops.cpp | privacore/open-source-search-engine | dac28de673068039381ca3f66521ea4c1eaf6a1e | [
"Apache-2.0"
] | 134 | 2016-05-30T13:29:37.000Z | 2021-06-18T02:13:51.000Z | Pops.cpp | mehmet-biter/open-source-search-engine | dac28de673068039381ca3f66521ea4c1eaf6a1e | [
"Apache-2.0"
] | 65 | 2016-10-31T16:02:28.000Z | 2020-04-30T14:18:57.000Z | Pops.cpp | mehmet-biter/open-source-search-engine | dac28de673068039381ca3f66521ea4c1eaf6a1e | [
"Apache-2.0"
] | 22 | 2016-05-30T13:29:39.000Z | 2020-06-30T08:43:38.000Z | #include "Pops.h"
#include "tokenizer.h"
#include "Speller.h"
#include "Mem.h"
#include "Sanity.h"
Pops::Pops () {
m_pops = NULL;
m_popsSize = 0;
memset(m_localBuf, 0, sizeof(m_localBuf));
}
Pops::~Pops() {
if ( m_pops && m_pops != (int32_t *)m_localBuf ) {
mfree ( m_pops , m_popsSize , "Pops" );
}
}
bool Pops::set ( const TokenizerResult *tr , int32_t a , int32_t b ) {
int32_t nw = tr->size();
int32_t need = nw * 4;
if ( need > POPS_BUF_SIZE ) m_pops = (int32_t *)mmalloc(need,"Pops");
else m_pops = (int32_t *)m_localBuf;
if ( ! m_pops ) return false;
m_popsSize = need;
for ( int32_t i = a ; i < b && i < nw ; i++ ) {
const auto &token = (*tr)[i];
// skip if not indexable
if ( !token.is_alfanum ) {
m_pops[i] = 0;
continue;
}
// once again for the 50th time partap's utf16 crap gets in
// the way... we have to have all kinds of different hashing
// methods because of it...
uint64_t key;
const char *wp = token.token_start;
int32_t wlen = token.token_len;
key = hash64d( wp, wlen );
m_pops[i] = g_speller.getPhrasePopularity( wp, key, 0 );
// sanity check
if ( m_pops[i] < 0 ) gbshutdownLogicError();
if ( m_pops[i] == 0 ) {
m_pops[i] = 1;
}
}
return true;
}
| 22.105263 | 70 | 0.604762 | privacore |
8d42dc7dba9c7cc3254acac2957982f28f1dec98 | 3,075 | cpp | C++ | src/game/localization.cpp | ftk/XXLDDRace | 68ae75092f4483f003e165d93e6334524015dfec | [
"Zlib"
] | 2 | 2015-04-23T16:38:41.000Z | 2016-05-24T00:59:25.000Z | src/game/localization.cpp | ftk/XXLDDRace | 68ae75092f4483f003e165d93e6334524015dfec | [
"Zlib"
] | null | null | null | src/game/localization.cpp | ftk/XXLDDRace | 68ae75092f4483f003e165d93e6334524015dfec | [
"Zlib"
] | 1 | 2019-10-21T23:12:12.000Z | 2019-10-21T23:12:12.000Z | /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include "localization.h"
#include <base/tl/algorithm.h>
#include <engine/shared/linereader.h>
#include <engine/console.h>
#include <engine/storage.h>
#include <unordered_map>
static std::unordered_map<const char*, const char*> loc;
const char *Localize(const char *pStr)
{
//dbg_msg("localize", "searching for %s", pStr);
auto it = loc.find(pStr);
if(it != loc.end())
return it->second;
const char *pNewStr = g_Localization.FindString(str_quickhash(pStr));
pNewStr = pNewStr ? pNewStr : pStr;
//dbg_msg("localize", "%s -> %s", pStr, pNewStr);
loc[pStr] = pNewStr;
return pNewStr;
}
CLocConstString::CLocConstString(const char *pStr)
{
m_pDefaultStr = pStr;
m_Hash = str_quickhash(m_pDefaultStr);
m_Version = -1;
}
void CLocConstString::Reload()
{
m_Version = g_Localization.Version();
const char *pNewStr = g_Localization.FindString(m_Hash);
m_pCurrentStr = pNewStr;
if(!m_pCurrentStr)
m_pCurrentStr = m_pDefaultStr;
}
CLocalizationDatabase::CLocalizationDatabase()
{
m_VersionCounter = 0;
m_CurrentVersion = 0;
}
void CLocalizationDatabase::AddString(const char *pOrgStr, const char *pNewStr)
{
CString s;
s.m_Hash = str_quickhash(pOrgStr);
s.m_Replacement = *pNewStr ? pNewStr : pOrgStr;
m_Strings.add(s);
}
bool CLocalizationDatabase::Load(const char *pFilename, IStorage *pStorage, IConsole *pConsole)
{
// empty string means unload
if(pFilename[0] == 0)
{
m_Strings.clear();
m_CurrentVersion = 0;
return true;
}
IOHANDLE IoHandle = pStorage->OpenFile(pFilename, IOFLAG_READ, IStorage::TYPE_ALL);
if(!IoHandle)
return false;
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "loaded '%s'", pFilename);
pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
m_Strings.clear();
loc.clear();
char aOrigin[512];
CLineReader LineReader;
LineReader.Init(IoHandle);
char *pLine;
while((pLine = LineReader.Get()))
{
if(!str_length(pLine))
continue;
if(pLine[0] == '#') // skip comments
continue;
str_copy(aOrigin, pLine, sizeof(aOrigin));
char *pReplacement = LineReader.Get();
if(!pReplacement)
{
pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", "unexpected end of file");
break;
}
if(pReplacement[0] != '=' || pReplacement[1] != '=' || pReplacement[2] != ' ')
{
str_format(aBuf, sizeof(aBuf), "malform replacement line for '%s'", aOrigin);
pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "localization", aBuf);
continue;
}
pReplacement += 3;
AddString(aOrigin, pReplacement);
}
io_close(IoHandle);
m_CurrentVersion = ++m_VersionCounter;
return true;
}
const char *CLocalizationDatabase::FindString(unsigned Hash)
{
CString String;
String.m_Hash = Hash;
sorted_array<CString>::range r = ::find_binary(m_Strings.all(), String);
if(r.empty())
return 0;
return r.front().m_Replacement;
}
CLocalizationDatabase g_Localization;
| 23.837209 | 95 | 0.708618 | ftk |
1d26a58741cb817f07b0c97e73cfc5dc972dbd2f | 1,428 | cpp | C++ | BAC_2nd/ch6/UVa12657.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | BAC_2nd/ch6/UVa12657.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | BAC_2nd/ch6/UVa12657.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa12657 Boxes in a Line
// Rujia Liu
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100000 + 5;
int n, left[maxn], right[maxn];
inline void link(int L, int R) {
right[L] = R; left[R] = L;
}
int main() {
int m, kase = 0;
while(scanf("%d%d", &n, &m) == 2) {
for(int i = 1; i <= n; i++) {
left[i] = i-1;
right[i] = (i+1) % (n+1);
}
right[0] = 1; left[0] = n;
int op, X, Y, inv = 0;
while(m--) {
scanf("%d", &op);
if(op == 4) inv = !inv;
else {
scanf("%d%d", &X, &Y);
if(op == 3 && right[Y] == X) swap(X, Y);
if(op != 3 && inv) op = 3 - op;
if(op == 1 && X == left[Y]) continue;
if(op == 2 && X == right[Y]) continue;
int LX = left[X], RX = right[X], LY = left[Y], RY = right[Y];
if(op == 1) {
link(LX, RX); link(LY, X); link(X, Y);
}
else if(op == 2) {
link(LX, RX); link(Y, X); link(X, RY);
}
else if(op == 3) {
if(right[X] == Y) { link(LX, Y); link(Y, X); link(X, RY); }
else { link(LX, Y); link(Y, RX); link(LY, X); link(X, RY); }
}
}
}
int b = 0;
long long ans = 0;
for(int i = 1; i <= n; i++) {
b = right[b];
if(i % 2 == 1) ans += b;
}
if(inv && n % 2 == 0) ans = (long long)n*(n+1)/2 - ans;
printf("Case %d: %lld\n", ++kase, ans);
}
return 0;
}
| 24.20339 | 70 | 0.418768 | Anyrainel |
1d2833ff5699a215520ab7aa31c330213b2b6ecc | 675 | cpp | C++ | Contest/Al-Khawarizmi National Programming Contest 2016/J.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | Contest/Al-Khawarizmi National Programming Contest 2016/J.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | Contest/Al-Khawarizmi National Programming Contest 2016/J.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include <bits/stdc++.h>
using namespace std;
int a[11][11],n,ans,kas;
inline void read(int &x)
{
x=0;char ch=getchar();bool f=false;
while (ch<'0'||ch>'9'){if (ch=='-') f=true;ch=getchar();}
while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
if (f) x=-x;return ;
}
int main()
{
while (true)
{
read(n);ans=0;if (!n) break;
printf("Case #%d:", ++kas);
if (n==1)
{
read(a[1][1]);
printf("%d\n",a[1][1]);
continue;
}
for (int i=1;i<=n;i++)
for (int j=1;j<=i;j++)
read(a[i][j]);
for (int i=1;i<n;i++) ans+=a[i][1];
for (int i=1;i<n;i++) ans+=a[n][i];
for (int i=n;i>1;i--) ans+=a[i][i];
printf("%d\n", ans);
}
return 0;
} | 19.285714 | 62 | 0.494815 | HeRaNO |
1d288eaede067c838ff8270f538f6684cb5d2af1 | 1,485 | cpp | C++ | src/hqn_lua.cpp | Bindernews/HeadlessQuickNes | 394cc533c74b079bf8b143b25d4e4f6c75232469 | [
"MIT"
] | 5 | 2016-04-19T20:45:28.000Z | 2018-11-25T03:07:30.000Z | src/hqn_lua.cpp | Bindernews/HappyQuickNes | 394cc533c74b079bf8b143b25d4e4f6c75232469 | [
"MIT"
] | null | null | null | src/hqn_lua.cpp | Bindernews/HappyQuickNes | 394cc533c74b079bf8b143b25d4e4f6c75232469 | [
"MIT"
] | null | null | null |
#include "hqn_lua.h"
#include <SDL.h>
#include <SDL_ttf.h>
#define SDL_INIT_FAILED_MSG "Failed to initialize SDL: %s"
namespace hqn_lua
{
// Yep. Global state. Shared by the whole Lua interface.
static HQNState *globalState;
/* Delcarations for all the init functions. */
int emu_init_(lua_State *L);
int gui_init_(lua_State *L);
int input_init_(lua_State *L);
int joypad_init_(lua_State *L);
int mainmemory_init_(lua_State *L);
int savestate_init_(lua_State *L);
void init_nes(lua_State *L, HQNState *state)
{
globalState = state;
// create new table to store all submodules
lua_newtable(L);
// initialize all submodules
emu_init_(L);
gui_init_(L);
input_init_(L);
joypad_init_(L);
mainmemory_init_(L);
savestate_init_(L);
// end with hqnes table on top of stack
}
Nes_Emu *hqn_get_nes()
{
HQN_STATE(state);
return state->emu();
}
HQNState *hqn_get_state()
{
return globalState;
}
void hqnL_register(lua_State *L, const char *k, const luaL_Reg *funcs)
{
lua_newtable(L);
luaL_register(L, nullptr, funcs);
lua_setfield(L, lua_gettop(L) - 1, k);
}
} // end of hqn_lua namespace
extern "C"
int luaopen_hqnes_core(lua_State *L)
{
if (SDL_Init(0) < 0)
{
return luaL_error(L, SDL_INIT_FAILED_MSG, SDL_GetError());
}
if (TTF_Init() < 0)
{
return luaL_error(L, SDL_INIT_FAILED_MSG, SDL_GetError());
}
hqn_lua::init_nes(L, new hqn::HQNState());
return 1;
}
| 20.342466 | 70 | 0.674747 | Bindernews |
1d28926caaf9e51f33d11cdb62bc7da6eb24f800 | 919 | cpp | C++ | Day 03/day3.cpp | holaguz/AdventOfCode2021 | 349b7a33ab1128264dceb7aaf604030b0df842df | [
"Unlicense"
] | null | null | null | Day 03/day3.cpp | holaguz/AdventOfCode2021 | 349b7a33ab1128264dceb7aaf604030b0df842df | [
"Unlicense"
] | null | null | null | Day 03/day3.cpp | holaguz/AdventOfCode2021 | 349b7a33ab1128264dceb7aaf604030b0df842df | [
"Unlicense"
] | null | null | null | /* https://adventofcode.com/2021/day/3 */
#include <iostream>
#include <bitset>
#include <vector>
int main(){
int n;
int gamma = 0, epsilon = 0;
std::cin >> n;
std::vector<int> count(64);
std::vector<long long> input(n);
long long max = 0;
for(auto& v: input){
std::cin >> v;
max = v > max ? v : max;
}
int msb = 0;
while(max){
std::cerr << max << std::endl;
max /= 10;
msb++;
}
std::cerr << msb << std::endl;
for (int i = 0; i < n; ++i)
for (int j = 0; j < msb; ++j)
{
count[j] += (input[i] & 1);
input[i] /= 10;
}
for (int i = 0; i < msb; ++i)
{
epsilon |= (2 * count[i] < n ? (1 << i) : 0);
}
gamma = (1 << msb) - epsilon - 1;
std::cerr << epsilon << ' ' << gamma << std::endl;
std::cout << gamma * epsilon << std::endl;
} | 21.880952 | 57 | 0.425462 | holaguz |
1d29267957a6f597adfed4a97ac3ebf22aa69d0a | 327 | hpp | C++ | demos/sequential_line_search_2d_gui/widgetpreview.hpp | yuki-koyama/sequential-line-search | 7f68ce6f3ccb63eee4e921b867bd1014e3f947ff | [
"MIT"
] | 26 | 2018-03-12T13:18:30.000Z | 2022-03-26T20:28:04.000Z | demos/sequential_line_search_2d_gui/widgetpreview.hpp | yuki-koyama/sequential-line-search | 7f68ce6f3ccb63eee4e921b867bd1014e3f947ff | [
"MIT"
] | 37 | 2018-04-05T23:42:24.000Z | 2022-02-13T03:52:42.000Z | demos/sequential_line_search_2d_gui/widgetpreview.hpp | yuki-koyama/sequential-line-search | 7f68ce6f3ccb63eee4e921b867bd1014e3f947ff | [
"MIT"
] | 5 | 2018-06-12T17:50:47.000Z | 2021-05-17T11:13:03.000Z | #ifndef WIDGETPREVIEW_H
#define WIDGETPREVIEW_H
#include <QWidget>
class WidgetPreview : public QWidget
{
Q_OBJECT
public:
explicit WidgetPreview(QWidget* parent = 0);
protected:
void paintEvent(QPaintEvent* event) Q_DECL_OVERRIDE;
private:
double m_f_min;
double m_f_max;
};
#endif // WIDGETPREVIEW_H
| 15.571429 | 56 | 0.743119 | yuki-koyama |
1d2b2781fd183efc7741f9e3b155a1647c395c0c | 6,361 | cpp | C++ | src/discovery/window.cpp | amin-amani/QtNetDiscovery | cdc09ddd4813536c45944b388772f7afc8472d80 | [
"MIT"
] | null | null | null | src/discovery/window.cpp | amin-amani/QtNetDiscovery | cdc09ddd4813536c45944b388772f7afc8472d80 | [
"MIT"
] | null | null | null | src/discovery/window.cpp | amin-amani/QtNetDiscovery | cdc09ddd4813536c45944b388772f7afc8472d80 | [
"MIT"
] | null | null | null | /**************************************************************************************************
---------------------------------------------------------------------------------------------------
Copyright (C) 2015 Jonathan Bagg
This file is part of QtZeroConf.
QtZeroConf 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 3 of the License, or
(at your option) any later version.
QtZeroConf is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with QtZeroConf. If not, see <http://www.gnu.org/licenses/>.
---------------------------------------------------------------------------------------------------
Project name : QtZeroConf Example
File name : window.cpp
Created : 3 November 2015
Author(s) : Jonathan Bagg
---------------------------------------------------------------------------------------------------
Example app to demonstrate service publishing and service discovery
---------------------------------------------------------------------------------------------------
**************************************************************************************************/
#include <QGuiApplication>
#include <QVBoxLayout>
#include <QPushButton>
#include <QTableWidgetItem>
#include <QNetworkInterface>
#include <QHeaderView>
#include <QDebug>
#include "window.h"
#ifdef Q_OS_IOS
#define OS_NAME "iOS"
#elif defined(Q_OS_MAC)
#define OS_NAME "Mac"
#elif defined(Q_OS_ANDROID)
#define OS_NAME "Android"
#elif defined(Q_OS_LINUX)
#define OS_NAME "Linux"
#elif defined(Q_OS_WIN)
#define OS_NAME "Windows"
#elif defined(Q_OS_FREEBSD)
#define OS_NAME "FreeBSD"
#else
#define OS_NAME "Some OS"
#endif
mainWindow::mainWindow()
{
publishEnabled = 0;
buildGUI();
if (!zeroConf.browserExists())
zeroConf.startBrowser("_qtzeroconf_test._tcp");
connect(&zeroConf, &QZeroConf::serviceAdded, this, &mainWindow::addService);
// connect(&zeroConf, &QZeroConf::serviceRemoved, this, &mainWindow::removeService);
// connect(&zeroConf, &QZeroConf::serviceUpdated, this, &mainWindow::updateService);
// connect(qGuiApp, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(appStateChanged(Qt::ApplicationState)));
// publishEnabled = 1;
}
void mainWindow::buildGUI()
{
QPushButton *button;
QVBoxLayout *layout = new QVBoxLayout;
button = new QPushButton(tr(" Enable Publish "));
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(button);
layout->setAlignment(button, Qt::AlignHCenter);
connect(button, &QPushButton::clicked, this, &mainWindow::startPublishClicked);
button = new QPushButton(tr(" Disable Publish "));
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(button);
layout->setAlignment(button, Qt::AlignHCenter);
connect(button, &QPushButton::clicked, this, &mainWindow::stopPublishClicked);
table.verticalHeader()->hide();
table.horizontalHeader()->hide();
table.setColumnCount(2);
layout->addWidget(&table);
//table.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QWidget *widget = new QWidget;
widget->setLayout(layout);
setCentralWidget(widget);
show();
}
QString mainWindow::buildName(void)
{
QString name;
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); // now you have interfaces list
name = list.last().hardwareAddress();
name.remove(":");
name.remove(0, 6);
name+= ')';
name.prepend("Qt ZeroConf Test - " OS_NAME " (");
return name;
}
void mainWindow::appStateChanged(Qt::ApplicationState state)
{qDebug()<<"changed"<<state;
if (state == Qt::ApplicationSuspended) {
zeroConf.stopServicePublish();
zeroConf.stopBrowser();
}
else if (state == Qt::ApplicationActive) {
if (publishEnabled && !zeroConf.publishExists())
startPublish();
if (!zeroConf.browserExists())
zeroConf.startBrowser("_qtzeroconf_test._tcp");
}
}
// ---------- Service Publish ----------
void mainWindow::startPublish()
{
zeroConf.clearServiceTxtRecords();
zeroConf.addServiceTxtRecord("Qt", "the best!");
zeroConf.addServiceTxtRecord("ZeroConf is nice too");
zeroConf.startServicePublish(buildName().toUtf8(), "_qtzeroconf_test._tcp", "local", 11437);
}
void mainWindow::startPublishClicked()
{
if (publishEnabled)
return;
publishEnabled = 1;
startPublish();
}
void mainWindow::stopPublishClicked()
{
if (!publishEnabled)
return;
publishEnabled = 0;
zeroConf.stopServicePublish();
}
// ---------- Discovery Callbacks ----------
void mainWindow::addService(QZeroConfService zcs)
{
qint32 row;
QTableWidgetItem *cell;
qDebug() << "Added service: " << zcs;
row = table.rowCount();
table.insertRow(row);
cell = new QTableWidgetItem(zcs->name());
table.setItem(row, 0, cell);
cell = new QTableWidgetItem(zcs->ip().toString());
table.setItem(row, 1, cell);
table.resizeColumnsToContents();
#if !(defined(Q_OS_IOS) || defined(Q_OS_ANDROID))
setFixedSize(table.horizontalHeader()->length() + 60, table.verticalHeader()->length() + 100);
#endif
}
void mainWindow::removeService(QZeroConfService zcs)
{
qint32 i, row;
QTableWidgetItem *nameItem, *ipItem;
qDebug() << "Removed service: " << zcs;
QList <QTableWidgetItem*> search = table.findItems(zcs->name(), Qt::MatchExactly);
for (i=0; i<search.size(); i++) {
nameItem = search.at(i);
row = nameItem->row();
ipItem = table.item(row, 1);
if (table.item(row, 1)->text() == zcs->ip().toString()) { // match ip address in case of dual homed systems
delete nameItem;
delete ipItem;
table.removeRow(row);
}
}
}
void mainWindow::updateService(QZeroConfService zcs)
{
qDebug() << "Service updated: " << zcs;
}
| 33.130208 | 130 | 0.617513 | amin-amani |
1d30a0ad65cde45076d2fd379cc9cab1a93619ae | 145 | cpp | C++ | Source/FSD/Private/SchematicSave.cpp | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 8 | 2021-07-10T20:06:05.000Z | 2022-03-04T19:03:50.000Z | Source/FSD/Private/SchematicSave.cpp | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 9 | 2022-01-13T20:49:44.000Z | 2022-03-27T22:56:48.000Z | Source/FSD/Private/SchematicSave.cpp | Dr-Turtle/DRG_ModPresetManager | abd7ff98a820969504491a1fe68cf2f9302410dc | [
"MIT"
] | 2 | 2021-07-10T20:05:42.000Z | 2022-03-14T17:05:35.000Z | #include "SchematicSave.h"
FSchematicSave::FSchematicSave() {
this->SkinFixupCounter = 0;
this->bFirstSchematicMessageShown = false;
}
| 18.125 | 46 | 0.731034 | Dr-Turtle |
1d31480315eafacec7b9f2a2c70652e55b7f128c | 544 | cpp | C++ | OGMM/gui/MenuItem.cpp | Moneyl/OGMM | 52a4bcc051fab160c55f0cc7228bd99de3ff5c47 | [
"MIT"
] | 3 | 2020-08-26T17:53:47.000Z | 2020-09-13T07:48:40.000Z | OGMM/gui/MenuItem.cpp | Moneyl/OGMM | 52a4bcc051fab160c55f0cc7228bd99de3ff5c47 | [
"MIT"
] | 2 | 2020-09-01T06:08:28.000Z | 2020-11-14T02:14:41.000Z | OGMM/gui/MenuItem.cpp | Moneyl/OGMM | 52a4bcc051fab160c55f0cc7228bd99de3ff5c47 | [
"MIT"
] | null | null | null | #include "MenuItem.h"
#include "IGuiPanel.h"
#include <string_view>
#include <imgui.h>
MenuItem* MenuItem::GetItem(std::string_view text)
{
for (auto& item : Items)
{
if (item.Text == text)
return &item;
}
return nullptr;
}
void MenuItem::Draw()
{
if (panel)
{
ImGui::MenuItem(Text.c_str(), "", &panel->Open);
return;
}
if (ImGui::BeginMenu(Text.c_str()))
{
for (auto& item : Items)
{
item.Draw();
}
ImGui::EndMenu();
}
} | 17 | 56 | 0.512868 | Moneyl |
1d31b033e30bcb077e3621fc38a330a885a47ff4 | 2,971 | cpp | C++ | test/molch-init-test.cpp | 1984not-GmbH/molch | c7f1f646c800ef3388f36e8805a3b94d33d85b12 | [
"MIT"
] | 15 | 2016-04-12T17:12:19.000Z | 2019-08-14T17:46:17.000Z | test/molch-init-test.cpp | 1984not-GmbH/molch | c7f1f646c800ef3388f36e8805a3b94d33d85b12 | [
"MIT"
] | 63 | 2016-03-22T14:35:31.000Z | 2018-07-04T22:17:07.000Z | test/molch-init-test.cpp | 1984not-GmbH/molch | c7f1f646c800ef3388f36e8805a3b94d33d85b12 | [
"MIT"
] | 1 | 2017-08-17T09:27:30.000Z | 2017-08-17T09:27:30.000Z | /*
* Molch, an implementation of the axolotl ratchet based on libsodium
*
* ISC License
*
* Copyright (C) 2015-2016 1984not Security GmbH
* Author: Max Bruckner (FSMaxB)
*
* 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 <sodium.h>
#include <cstring>
#include <iostream>
#include <string>
#include "molch.h"
#include "integration-utils.hpp"
#include "inline-utils.hpp"
int main(int argc, char *args[]) noexcept {
try {
auto recreate{false};
if (argc == 2) {
if (strcmp(args[1], "--recreate") == 0) {
recreate = true;
}
}
if (::sodium_init() != 0) {
throw ::Exception("Failed to initialize libsodium.");
}
BackupKeyArray backup_key;
if (!recreate) {
//load the backup from a file
auto backup_file{read_file("test-data/molch-init.backup")};
//load the backup key from a file
auto backup_key_file{read_file("test-data/molch-init-backup.key")};
if (backup_key_file.size() not_eq backup_key.size()) {
throw ::Exception("Backup key from file has an incorrect length.");
}
//try to import the backup
{
auto status{molch_import(
backup_key.data(),
backup_key.size(),
backup_file.data(),
backup_file.size(),
backup_key_file.data(),
backup_key_file.size())};
if (status.status != status_type::SUCCESS) {
throw ::Exception("Failed to import backup.");
}
}
//destroy again
molch_destroy_all_users();
}
//create a new user
AutoFreeBuffer backup;
AutoFreeBuffer prekey_list;
PublicIdentity user_id;
{
auto status{molch_create_user(
user_id.data(),
user_id.size(),
&prekey_list.pointer,
&prekey_list.length,
backup_key.data(),
backup_key.size(),
&backup.pointer,
&backup.length,
char_to_uchar("random"),
sizeof("random"))};
if (status.status != status_type::SUCCESS) {
throw ::Exception("Failed to create user.");
}
}
if (backup.pointer == nullptr) {
throw ::Exception("Failed to export backup.");
}
//print the backup to a file
write_to_file(backup, "molch-init.backup");
write_to_file(backup_key, "molch-init-backup.key");
} catch (const std::exception& exception) {
std::cerr << exception.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 27.509259 | 75 | 0.682262 | 1984not-GmbH |
1d321dc32fb7fb470efb650e339472732cce7e5e | 6,421 | hpp | C++ | include/ext.hpp | PENGUINLIONG/OptixLab | 541b8767d6a4626ee08f8367264ea69a494f644e | [
"Apache-2.0",
"MIT"
] | 2 | 2020-09-04T08:35:43.000Z | 2020-12-14T16:27:34.000Z | include/ext.hpp | PENGUINLIONG/OptixLab | 541b8767d6a4626ee08f8367264ea69a494f644e | [
"Apache-2.0",
"MIT"
] | null | null | null | include/ext.hpp | PENGUINLIONG/OptixLab | 541b8767d6a4626ee08f8367264ea69a494f644e | [
"Apache-2.0",
"MIT"
] | 1 | 2020-03-10T14:38:56.000Z | 2020-03-10T14:38:56.000Z | #pragma once
// Extensions to core functionalities.
// @PENGUINLIONG
#include <functional>
#ifdef L_USE_ASSIMP
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#endif // L_USE_ASSIMP
#include "core.hpp"
namespace liong {
namespace ext {
// Read PTX representation from a single file specified in `pipe_cfg`.
std::vector<char> read_ptx(const char* ptx_path);
// Create a naive pipeline that is enough to do simple ray tracing tasks. A
// naive pipline is a predefined cofiguration with `lauch_param_name` defaulted
// to `cfg`, `npayload_wd` and `nattr_wd` defaulted to 2 (to carry a pointer).
Pipeline create_naive_pipe(
const Context& ctxt,
const NaivePipelineConfig& naive_pipe_cfg
);
inline DeviceMemorySlice slice_naive_pipe_ray_prop(
const Pipeline& pipe,
const PipelineData& pipe_data
) {
return slice_pipe_data(pipe, pipe_data, OPTIX_PROGRAM_GROUP_KIND_RAYGEN, 0);
}
inline DeviceMemorySlice slice_naive_pipe_mat(
const Pipeline& pipe,
const PipelineData& pipe_data,
uint32_t idx
) {
return slice_pipe_data(pipe, pipe_data, OPTIX_PROGRAM_GROUP_KIND_HITGROUP,
idx);
}
inline DeviceMemorySlice slice_naive_pipe_env(
const Pipeline& pipe,
const PipelineData& pipe_data
) {
return slice_pipe_data(pipe, pipe_data, OPTIX_PROGRAM_GROUP_KIND_MISS, 0);
}
inline std::vector<Mesh> create_meshes(
const std::vector<MeshConfig>& mesh_cfgs
) {
std::vector<Mesh> rv;
rv.resize(mesh_cfgs.size());
for (const auto& mesh : mesh_cfgs) {
create_mesh(mesh);
}
return rv;
}
inline void destroy_meshes(std::vector<Mesh>& meshes) {
for (auto& mesh : meshes) {
destroy_mesh(mesh);
}
meshes.clear();
}
std::vector<Mesh> import_meshes_from_file(const char* path);
inline std::vector<SceneObject> create_sobjs(size_t nsobj) {
std::vector<SceneObject> rv;
rv.resize(nsobj);
for (auto i = 0; i < nsobj; ++i) {
rv[i] = create_sobj();
}
return std::move(rv);
}
inline void destroy_sobjs(std::vector<SceneObject>& sobjs) {
for (auto& sobj : sobjs) {
destroy_sobj(sobj);
}
sobjs.clear();
}
inline void cmd_build_sobjs(
Transaction& transact,
const Context& ctxt,
const std::vector<Mesh>& meshes,
std::vector<SceneObject>& sobjs,
bool can_compact = true
) {
const auto n = meshes.size();
ASSERT << (n == sobjs.size())
<< "mesh count and scene object count mismatched";
for (auto i = 0; i < n; ++i) {
cmd_build_sobj(transact, ctxt, meshes[i], sobjs[i], can_compact);
}
}
struct SnapshotCommonHeader {
// Snapshot magic number, MUST be set to `0x894C4A33` (`.LJ3` in big endian,
// note that the fist character is not a char but a non-textual character).
// The magic number can also be used to identify endian. Please ensure you
// initialized the header with `init_snapshot_common_header`, so this field is
// correctly filled.
uint32_t magic = 0x894C4A33;
// Common header version.
uint32_t version = 0x0000001;
// Type code of snapshot content. If a snapshot type has multiple versions,
// version number or other semantical constructs should be encoded here.
uint32_t type;
// Optional size of data element in bytes. If `stride` is not zero, the import
// procedure will enforce to consume at least and no more than this amount of
// data; otherwise, it will exhaust the file and it will be the application's
// work to infer the correct amount of data.
uint32_t stride = 0;
// Dimensions of homogeneous data element in `data`.
uint4 dim = { 1, 1, 1, 1 };
};
// Take a snapshot of host memory content and writei it to a binary file. The
// binary data will follow a header section.
//
// WARNING: Be aware of endianess.
extern void snapshot_hostmem(
const void* hostmem,
size_t hostmem_size,
const void* head,
size_t head_size,
const char* path
);
// Take a snapshot of device memory content and write it to a binary file. The
// binary data will follow a header section.
//
// WARNING: Be aware of endianess.
extern void snapshot_devmem(
const DeviceMemorySlice& devmem,
const void* head,
size_t head_size,
const char* path
);
// Buffer snapshots with a `SnapshotCommonHeader` header is a `CommonSnapshot`.
struct CommonSnapshot {
// Dynamically allocated data buffer.
void* data;
// Type code of snapshot content.
uint32_t type;
// Size of data element in bytes. The import procedure will enforce to consume
// at least and no more than this amount of data.
uint32_t stride;
// Number of homogeneous data element in `data`. Tensors should be filled in
// column major order.
uint4 dim;
// Whether the buffer producer is an little endian machine.
bool is_le;
constexpr size_t nelem() const {
return dim.x * dim.y * dim.z * dim.w;
}
constexpr size_t size() const {
return nelem() * stride;
}
};
// Import buffer snapshot from local storage.
extern CommonSnapshot import_common_snapshot(const char* path);
// Release the resources allocated for the imported snapshot.
extern void destroy_common_snapshot(CommonSnapshot& snapshot);
enum FramebufferSnapshotFormat {
L_EXT_FRAMEBUFFER_SNAPSHOT_FORMAT_AUTO,
L_EXT_FRAMEBUFFER_SNAPSHOT_FORMAT_BMP,
L_EXT_FRAMEBUFFER_SNAPSHOT_FORMAT_EXR,
};
// Take a snapshot of the framebuffer content and write it to a image file.
// Currently Lighar support 2 image file types. The output format is decided by
// `path` extension if `snapshot_fmt` is L_EXT_SNAPSHOT_FMT_AUTO.
//
// WARNING: This only works properly on little-endian platforms.
// WARNING: Snapshot format inferrence only works for lower-case extension
// names.
extern void snapshot_framebuf(
const Framebuffer& framebuf,
const char* path,
FramebufferSnapshotFormat framebuf_snapshot_fmt
);
inline void snapshot_framebuf(
const Framebuffer& framebuf,
const char* path
) {
snapshot_framebuf(framebuf, path, L_EXT_FRAMEBUFFER_SNAPSHOT_FORMAT_AUTO);
}
extern void snapshot_host_framebuf(
const void* framebuf,
const uint32_t w,
const uint32_t h,
PixelFormat fmt,
const char* path,
FramebufferSnapshotFormat framebuf_snapshot_fmt
);
inline void snapshot_host_framebuf(
const void* framebuf,
const uint32_t w,
const uint32_t h,
PixelFormat fmt,
const char* path
) {
snapshot_host_framebuf(framebuf, w, h, fmt, path,
L_EXT_FRAMEBUFFER_SNAPSHOT_FORMAT_AUTO);
}
extern Image import_image_exr(const char* path);
} // namespace ext
} // namespace liong
| 29.186364 | 80 | 0.73867 | PENGUINLIONG |
1d3395e3d9d641245b8029878dc07a1013fc5aae | 3,215 | hpp | C++ | hpx/performance_counters/stubs/performance_counter.hpp | bremerm31/hpx | a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa | [
"BSL-1.0"
] | 1 | 2019-07-04T10:18:01.000Z | 2019-07-04T10:18:01.000Z | hpx/performance_counters/stubs/performance_counter.hpp | bremerm31/hpx | a9d22b8eb2e443d2e95991da9b1a621f94d4ebaa | [
"BSL-1.0"
] | 1 | 2017-07-24T07:16:26.000Z | 2017-07-24T08:03:33.000Z | hpx/performance_counters/stubs/performance_counter.hpp | biddisco/hpx | 2d244e1e27c6e014189a6cd59c474643b31fad4b | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2018 Hartmut Kaiser
//
// 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)
#if !defined(HPX_PERFORMANCE_COUNTERS_STUBS_COUNTER_MAR_03_2009_0745M)
#define HPX_PERFORMANCE_COUNTERS_STUBS_COUNTER_MAR_03_2009_0745M
#include <hpx/config.hpp>
#include <hpx/performance_counters/server/base_performance_counter.hpp>
#include <hpx/runtime/components/stubs/stub_base.hpp>
#include <hpx/runtime/launch_policy.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace performance_counters { namespace stubs
{
///////////////////////////////////////////////////////////////////////////
struct HPX_EXPORT performance_counter
: components::stub_base<
performance_counters::server::base_performance_counter>
{
///////////////////////////////////////////////////////////////////////
static counter_info get_info(launch::sync_policy,
naming::id_type const& targetid, error_code& ec = throws);
static counter_value get_value(launch::sync_policy,
naming::id_type const& targetid, bool reset = false,
error_code& ec = throws);
static counter_values_array get_values_array(launch::sync_policy,
naming::id_type const& targetid,
bool reset = false, error_code& ec = throws);
static lcos::future<counter_info> get_info(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<counter_value> get_value(launch::async_policy,
naming::id_type const& targetid, bool reset = false);
static lcos::future<counter_values_array> get_values_array(
launch::async_policy, naming::id_type const& targetid,
bool reset = false);
///////////////////////////////////////////////////////////////////////
static lcos::future<bool> start(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<bool> stop(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<void> reset(launch::async_policy,
naming::id_type const& targetid);
static lcos::future<void> reinit(launch::async_policy,
naming::id_type const& targetid, bool reset);
static bool start(launch::sync_policy, naming::id_type const& targetid,
error_code& ec = throws);
static bool stop(launch::sync_policy, naming::id_type const& targetid,
error_code& ec = throws);
static void reset(launch::sync_policy, naming::id_type const& targetid,
error_code& ec = throws);
static void reinit(launch::sync_policy, naming::id_type const& targetid,
bool reset, error_code& ec = throws);
template <typename T>
static T
get_typed_value(naming::id_type const& targetid, bool reset = false,
error_code& ec = throws)
{
counter_value value = get_value(launch::sync, targetid, reset);
return value.get_value<T>(ec);
}
};
}}}
#endif
| 45.28169 | 80 | 0.609642 | bremerm31 |
1d36e90b89b62099851d1cb7c07dbf2a0fbb5f7b | 5,555 | cpp | C++ | src/network/ChannelSocketClient.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/network/ChannelSocketClient.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/network/ChannelSocketClient.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | #include "ChannelSocketClient.h"
#include "network/TcpSocketThreadable.h"
#include "util/MemoryUtils.h"
#include "util/NetworkUtils.h"
#include "util/TimeUtils.h"
ChannelSocketClient::ChannelSocketClient(QObject *parent)
: QObject(parent)
, bKeepRetrying(false)
, nPort(0)
, mySocket(new TcpSocketThreadable(parent))
{
setupSignalsAndSlots();
mySocket->moveToThread(&myWorkerThread);
QObject::connect(&myWorkerThread, SIGNAL(finished()), this, SLOT(deleteLater()));
myWorkerThread.start();
}
ChannelSocketClient::~ChannelSocketClient()
{
bKeepRetrying = false;
disconnectSocket();
MemoryUtils::deletePointer(mySocket);
myWorkerThread.quit();
myWorkerThread.wait(200);
}
bool ChannelSocketClient::connect(const QString &szIpAddress, const QString &szPort)
{
qDebug() << "Connecting to" << szIpAddress << ":" << szPort;
if (NetworkUtils::isIpV4Address(szIpAddress) == false
|| NetworkUtils::isValidPort(szPort) == false) {
return false;
} else {
this->szIpAddress = NetworkUtils::cleanupIpV4Address(szIpAddress);
this->nPort = szPort.toUShort();
emit connectSocket(this->szIpAddress, this->nPort);
return true;
}
}
void ChannelSocketClient::setNeverDies(bool bNeverDies)
{
this->bKeepRetrying = bNeverDies;
}
void ChannelSocketClient::disconnectAndStopRetries()
{
bKeepRetrying = false;
clearIpAndPort(true);
emit disconnectSocket();
}
void ChannelSocketClient::clearIpAndPort(bool bForce)
{
if (bForce == true
|| bKeepRetrying == false) {
szIpAddress.clear();
nPort = 0;
}
}
void ChannelSocketClient::setupSignalsAndSlots()
{
QObject::connect(mySocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
QObject::connect(mySocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)));
QObject::connect(mySocket, SIGNAL(newMessage(QString)),
this, SLOT(newMessageOnSocket(QString)));
QObject::connect(this, SIGNAL(connectSocket(QString, quint16)),
mySocket, SLOT(connectSocket(QString, quint16)));
QObject::connect(this, SIGNAL(disconnectSocket()),
mySocket, SLOT(disconnectSocket()));
}
void ChannelSocketClient::reconnectSocket()
{
if (bKeepRetrying == true) {
emit connectSocket(this->szIpAddress, this->nPort);
}
}
void ChannelSocketClient::newMessageOnSocket(const QString &szMessage)
{
//check if there was a disconnect requested, ignore message
if (nPort == 0) {
return;
}
emit newMessageReceived(szMessage);
}
void ChannelSocketClient::socketStateChanged(QAbstractSocket::SocketState eSocketState)
{
if (nPort == 0) {
//socket was trying to connect when a disconnect was requested
if (eSocketState == QAbstractSocket::ConnectedState) {
emit disconnectSocket();
}
return;
}
#ifdef DEBUG_STUFF
QMetaEnum myMetaEnum = QMetaEnum::fromType<QAbstractSocket::SocketState>();
qDebug() << "socketStateChanged" << myMetaEnum.valueToKey(eSocketState);
#endif
switch (eSocketState) {
case QAbstractSocket::UnconnectedState:
reconnectSocket();
break;
case QAbstractSocket::HostLookupState:
break;
case QAbstractSocket::ConnectingState:
emit connectionInProgress();
break;
case QAbstractSocket::ConnectedState:
emit connectionSuccess();
break;
case QAbstractSocket::BoundState:
break;
case QAbstractSocket::ListeningState:
break;
case QAbstractSocket::ClosingState:
reconnectSocket();
break;
}
}
void ChannelSocketClient::socketError(QAbstractSocket::SocketError eSocketError)
{
if (nPort == 0) {
return;
}
emit connectionError(mySocket->error(), mySocket->errorString());
switch (eSocketError) {
case QAbstractSocket::ConnectionRefusedError:
case QAbstractSocket::RemoteHostClosedError:
case QAbstractSocket::HostNotFoundError:
case QAbstractSocket::SocketAccessError:
case QAbstractSocket::SocketResourceError:
case QAbstractSocket::SocketTimeoutError:
case QAbstractSocket::DatagramTooLargeError:
case QAbstractSocket::NetworkError:
case QAbstractSocket::AddressInUseError:
case QAbstractSocket::SocketAddressNotAvailableError:
case QAbstractSocket::UnsupportedSocketOperationError:
case QAbstractSocket::UnfinishedSocketOperationError:
case QAbstractSocket::ProxyAuthenticationRequiredError:
case QAbstractSocket::SslHandshakeFailedError:
case QAbstractSocket::ProxyConnectionRefusedError:
case QAbstractSocket::ProxyConnectionClosedError:
case QAbstractSocket::ProxyConnectionTimeoutError:
case QAbstractSocket::ProxyNotFoundError:
case QAbstractSocket::ProxyProtocolError:
case QAbstractSocket::OperationError:
case QAbstractSocket::SslInternalError:
case QAbstractSocket::SslInvalidUserDataError:
case QAbstractSocket::TemporaryError:
case QAbstractSocket::UnknownSocketError:
reconnectSocket();
break;
}
}
| 29.08377 | 92 | 0.672367 | vitorjna |
1d384e0091b3dbbc6d71ea5629b8e16111aff5e9 | 1,359 | hpp | C++ | include/Taus88.hpp | michaeldzjap/MDAudio | 70f9b75eeb39062fe9483fa4240274dcbfce68e3 | [
"MIT"
] | null | null | null | include/Taus88.hpp | michaeldzjap/MDAudio | 70f9b75eeb39062fe9483fa4240274dcbfce68e3 | [
"MIT"
] | null | null | null | include/Taus88.hpp | michaeldzjap/MDAudio | 70f9b75eeb39062fe9483fa4240274dcbfce68e3 | [
"MIT"
] | null | null | null | #ifndef MD_AUDIO_TAUS_88_HPP
#define MD_AUDIO_TAUS_88_HPP
#include <cstdint>
namespace md_audio {
// Original source: https://github.com/supercollider/supercollider/blob/develop/include/plugin_interface/SC_RGen.h
class Taus88 {
public:
explicit Taus88();
explicit Taus88(std::int32_t);
void initialise(std::int32_t) noexcept;
double generate() noexcept;
private:
std::uint32_t m_s1;
std::uint32_t m_s2;
std::uint32_t m_s3;
static constexpr std::int32_t Hash(std::int32_t in_key) noexcept {
auto hash = static_cast<std::uint32_t>(in_key);
hash += ~(hash << 15);
hash ^= hash >> 10;
hash += hash << 3;
hash ^= hash >> 6;
hash += ~(hash << 11);
hash ^= hash >> 16;
return static_cast<std::int32_t>(hash);
}
std::uint32_t trand(std::uint32_t& s1, std::uint32_t& s2, std::uint32_t& s3) noexcept {
s1 = ((s1 & static_cast<std::uint32_t>(-2)) << 12) ^ (((s1 << 13) ^ s1) >> 19);
s2 = ((s2 & static_cast<std::uint32_t>(-8)) << 4) ^ (((s2 << 2) ^ s2) >> 25);
s3 = ((s3 & static_cast<std::uint32_t>(-16)) << 17) ^ (((s3 << 3) ^ s3) >> 11);
return s1 ^ s2 ^ s3;
}
};
}
#endif /* MD_AUDIO_TAUS_88_HPP */
| 27.18 | 118 | 0.534952 | michaeldzjap |
1d397eb4ef4a40bdd8b4a0e6be9b4e5e17edf6d5 | 6,725 | hxx | C++ | Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx | ltmakela/ITK | 21f48c6d98e21ecece09be16a747221d7094d8a9 | [
"Apache-2.0"
] | 4 | 2015-05-22T03:47:43.000Z | 2016-06-16T20:57:21.000Z | Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx | GEHC-Surgery/ITK | f5df62749e56c9036e5888cfed904032ba5fdfb7 | [
"Apache-2.0"
] | null | null | null | Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx | GEHC-Surgery/ITK | f5df62749e56c9036e5888cfed904032ba5fdfb7 | [
"Apache-2.0"
] | 9 | 2016-06-23T16:03:12.000Z | 2022-03-31T09:25:08.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkShiSparseLevelSetImage_hxx
#define __itkShiSparseLevelSetImage_hxx
#include "itkShiSparseLevelSetImage.h"
namespace itk
{
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
ShiSparseLevelSetImage< VDimension >
::ShiSparseLevelSetImage()
{
this->InitializeLayers();
this->InitializeInternalLabelList();
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
ShiSparseLevelSetImage< VDimension >
::~ShiSparseLevelSetImage()
{
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
typename ShiSparseLevelSetImage< VDimension >::OutputType
ShiSparseLevelSetImage< VDimension >
::Evaluate( const InputType& iP ) const
{
LayerMapConstIterator layerIt = this->m_Layers.begin();
while( layerIt != this->m_Layers.end() )
{
LayerConstIterator it = ( layerIt->second ).find( iP );
if( it != ( layerIt->second ).end() )
{
return it->second;
}
++layerIt;
}
if( this->m_LabelMap->GetLabelObject( this->MinusThreeLayer() )->HasIndex( iP ) )
{
return static_cast<OutputType>( this->MinusThreeLayer() );
}
else
{
const LayerIdType status = this->m_LabelMap->GetPixel( iP );
if( status == this->PlusThreeLayer() )
{
return static_cast<OutputType>( this->PlusThreeLayer() );
}
else
{
itkGenericExceptionMacro( <<"status "
<< static_cast< int >( status )
<< " should be 3 or -3" );
return static_cast<OutputType>( this->PlusThreeLayer() );
}
}
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
typename ShiSparseLevelSetImage< VDimension >::HessianType
ShiSparseLevelSetImage< VDimension >
::EvaluateHessian( const InputType& itkNotUsed( iP ) ) const
{
itkGenericExceptionMacro( <<"The approximation of the hessian in the Shi's"
<<" representation is poor, and far to be representative."
<<" If it was required for regularization purpose, "
<<" you better check recommended regularization methods"
<<" for Shi's representation" );
HessianType oHessian;
oHessian.Fill( NumericTraits< OutputRealType >::Zero );
return oHessian;
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
typename ShiSparseLevelSetImage< VDimension >::OutputRealType
ShiSparseLevelSetImage< VDimension >
::EvaluateLaplacian( const InputType& itkNotUsed( iP ) ) const
{
itkGenericExceptionMacro( <<"The approximation of the hessian in the Shi's"
<<" representation is poor, and far to be representative."
<<" If it was required for regularization purpose, "
<<" you better check recommended regularization methods"
<<" for Shi's representation" );
OutputRealType oLaplacian = NumericTraits< OutputRealType >::Zero;
return oLaplacian;
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
typename ShiSparseLevelSetImage< VDimension >::OutputRealType
ShiSparseLevelSetImage< VDimension >
::EvaluateMeanCurvature( const InputType& itkNotUsed( iP ) ) const
{
itkGenericExceptionMacro( <<"The approximation of the hessian in the Shi's"
<<" representation is poor, and far to be representative."
<<" If it was required for regularization purpose, "
<<" you better check recommended regularization methods"
<<" for Shi's representation" );
OutputRealType oMeanCurvature = NumericTraits< OutputRealType >::Zero;
return oMeanCurvature;
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
void
ShiSparseLevelSetImage< VDimension >
::EvaluateHessian( const InputType& iP, LevelSetDataType& ioData ) const
{
if( ioData.Hessian.m_Computed )
{
return;
}
ioData.Hessian.m_Value = this->EvaluateHessian( iP );
ioData.Hessian.m_Computed = true;
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
void
ShiSparseLevelSetImage< VDimension >
::EvaluateLaplacian( const InputType& iP, LevelSetDataType& ioData ) const
{
if( ioData.Laplacian.m_Computed )
{
return;
}
ioData.Laplacian.m_Value = this->EvaluateLaplacian( iP );
ioData.Laplacian.m_Computed = true;
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
void
ShiSparseLevelSetImage< VDimension >
::EvaluateMeanCurvature( const InputType& iP, LevelSetDataType& ioData ) const
{
if( ioData.MeanCurvature.m_Computed )
{
return;
}
ioData.MeanCurvature.m_Value = this->EvaluateMeanCurvature( iP );
ioData.MeanCurvature.m_Computed = true;
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
void
ShiSparseLevelSetImage< VDimension >::InitializeLayers()
{
this->m_Layers.clear();
this->m_Layers[ MinusOneLayer() ] = LayerType();
this->m_Layers[ PlusOneLayer() ] = LayerType();
}
// ----------------------------------------------------------------------------
template< unsigned int VDimension >
void
ShiSparseLevelSetImage< VDimension >::InitializeInternalLabelList()
{
this->m_InternalLabelList.clear();
this->m_InternalLabelList.push_back( MinusThreeLayer() );
this->m_InternalLabelList.push_back( MinusOneLayer() );
}
}
#endif // __itkShiSparseLevelSetImage_h
| 33.625 | 86 | 0.577249 | ltmakela |