hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
5a63d37b4f09e2cc098e90c17ad9318dc2243d39
2,226
cpp
C++
src/arcstorage-ui/moc_draggableqtreewidget.cpp
Teemperor/arc-gui-clients
f9fa8396ac03eae3090f597d77766e3b00a44b31
[ "Apache-2.0" ]
null
null
null
src/arcstorage-ui/moc_draggableqtreewidget.cpp
Teemperor/arc-gui-clients
f9fa8396ac03eae3090f597d77766e3b00a44b31
[ "Apache-2.0" ]
null
null
null
src/arcstorage-ui/moc_draggableqtreewidget.cpp
Teemperor/arc-gui-clients
f9fa8396ac03eae3090f597d77766e3b00a44b31
[ "Apache-2.0" ]
1
2022-03-24T10:11:37.000Z
2022-03-24T10:11:37.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'draggableqtreewidget.h' ** ** Created: Mon May 9 11:49:25 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "draggableqtreewidget.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'draggableqtreewidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_DraggableQTreeWidget[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_DraggableQTreeWidget[] = { "DraggableQTreeWidget\0" }; const QMetaObject DraggableQTreeWidget::staticMetaObject = { { &QTreeWidgetItem::staticMetaObject, qt_meta_stringdata_DraggableQTreeWidget, qt_meta_data_DraggableQTreeWidget, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &DraggableQTreeWidget::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *DraggableQTreeWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *DraggableQTreeWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_DraggableQTreeWidget)) return static_cast<void*>(const_cast< DraggableQTreeWidget*>(this)); return QTreeWidgetItem::qt_metacast(_clname); } int DraggableQTreeWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QTreeWidgetItem::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
31.8
91
0.6469
[ "object" ]
5a714ef24725383c650c7e158ff322755611cc3c
725
cpp
C++
EU4toV2/Source/Mappers/ColonialFlags/ColonialFlag.cpp
GregB76/EU4toVic2
0a8822101a36a16036fdc315e706d113d9231101
[ "MIT" ]
1
2020-10-03T16:01:28.000Z
2020-10-03T16:01:28.000Z
EU4toV2/Source/Mappers/ColonialFlags/ColonialFlag.cpp
P4blo7/EU4toVic2
3f6d354a1f5e529f3d96b3616fe5109bc23f2972
[ "MIT" ]
null
null
null
EU4toV2/Source/Mappers/ColonialFlags/ColonialFlag.cpp
P4blo7/EU4toVic2
3f6d354a1f5e529f3d96b3616fe5109bc23f2972
[ "MIT" ]
null
null
null
#include "ColonialFlag.h" #include "Log.h" #include "ParserHelpers.h" #include "OSCompatibilityLayer.h" mappers::ColonialFlag::ColonialFlag(std::istream& theStream, const std::string& region) { registerKeyword("name", [this](const std::string& unused, std::istream& theStream) { const commonItems::singleString nameStr(theStream); name = nameStr.getString(); std::transform(name.begin(), name.end(), name.begin(), ::tolower); }); registerKeyword("unique", [this](const std::string& unused, std::istream& theStream) { commonItems::ignoreItem(unused, theStream); unique = true; }); registerRegex("[a-zA-Z0-9\\_.:]+", commonItems::ignoreItem); parseStream(theStream); clearRegisteredKeywords(); }
29
87
0.708966
[ "transform" ]
5a75529b17d6883a224be9955bf35ed5a810d788
2,118
cpp
C++
devmand/gateway/src/devmand/devices/cli/translation/GrpcListReader.cpp
gurrapualt/magma
13e05788fa6c40293a58b6e03cfb394bb79fa98f
[ "BSD-3-Clause" ]
2
2020-12-09T11:42:30.000Z
2021-09-26T03:28:33.000Z
devmand/gateway/src/devmand/devices/cli/translation/GrpcListReader.cpp
gurrapualt/magma
13e05788fa6c40293a58b6e03cfb394bb79fa98f
[ "BSD-3-Clause" ]
124
2020-08-21T06:11:21.000Z
2022-03-21T05:25:26.000Z
devmand/gateway/src/devmand/devices/cli/translation/GrpcListReader.cpp
yogi8091/magma
edc3b249068ad871047e898c912f3228ee9f2c88
[ "BSD-3-Clause" ]
1
2020-09-21T04:25:06.000Z
2020-09-21T04:25:06.000Z
/* Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. 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 <devmand/devices/cli/translation/GrpcListReader.h> namespace devmand { namespace devices { namespace cli { using namespace folly; using namespace std; using namespace grpc; using namespace devmand::channels::cli::plugin; using namespace devmand::channels::cli; GrpcListReader::GrpcListReader( shared_ptr<grpc::Channel> channel, const string _id, shared_ptr<Executor> _executor) : GrpcCliHandler(_id, _executor), stub_(devmand::channels::cli::plugin::ReaderPlugin::NewStub(channel)) {} Future<vector<dynamic>> GrpcListReader::readKeys( const Path& path, const DeviceAccess& device) const { MLOG(MDEBUG) << "[" << id << "] readKeys " << path; ActualReadRequest* actualRequest = new ActualReadRequest(); actualRequest->set_path(path.str()); ReadRequest request; request.set_allocated_actualreadrequest(actualRequest); return finish<ReadRequest, ReadResponse, vector<dynamic>>( request, device, [this](auto context) { return stub_->Read(context); }, [this](auto response) -> vector<dynamic> { dynamic result = parseJson(response.actualreadresponse().json()); if (not result.isArray()) { MLOG(MERROR) << "[" << id << "] Response is not json array:" << response.actualreadresponse().json(); throw runtime_error("Response is not json array"); } vector<dynamic> values; for (auto& k : result) { MLOG(MDEBUG) << "pushing " << toJson(k); values.push_back(k); } return values; }); } } // namespace cli } // namespace devices } // namespace devmand
32.584615
78
0.689802
[ "vector" ]
5a7f184632d2776207f1cf84114140dceb054900
2,781
cc
C++
RecoTracker/MkFitCore/src/radix_sort.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
null
null
null
RecoTracker/MkFitCore/src/radix_sort.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
null
null
null
RecoTracker/MkFitCore/src/radix_sort.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
null
null
null
#include "RecoTracker/MkFitCore/interface/radix_sort.h" #include <array> #include <numeric> namespace mkfit { // --- Driver function template <typename V, typename R> void radix_sort<V, R>::sort(const std::vector<V>& values, std::vector<R>& ranks) { if (values.empty()) { ranks.clear(); return; } rank_t histos[c_NBytes * 256] = {0}; histo_loop(values, histos); radix_loop(values, histos, ranks); } // --- Histogramming template <typename V, typename R> void radix_sort<V, R>::histo_loop(const std::vector<V>& values, rank_t* histos) { // Create histograms (counters). Counters for all passes are created in one run. ubyte_t* p = (ubyte_t*)values.data(); ubyte_t* pe = p + (values.size() * c_NBytes); std::array<rank_t*, c_NBytes> ha; for (rank_t j = 0; j < c_NBytes; ++j) ha[j] = &histos[j << 8]; while (p != pe) { for (rank_t j = 0; j < c_NBytes; ++j) ha[j][*p++]++; } } // --- Radix template <typename V, typename R> void radix_sort<V, R>::radix_loop(const std::vector<V>& values, rank_t* histos, std::vector<R>& ranks) { const rank_t nb = values.size(); rank_t* link[256]; ranks.resize(nb); std::vector<rank_t> ranks2(nb); bool ranks_are_invalid = true; // Radix sort, j is the pass number (0=LSB, 3=MSB) for (rank_t j = 0; j < c_NBytes; j++) { // Shortcut to current counters rank_t* cur_count = &histos[j << 8]; // Get first byte - if that byte's counter equals nb, all values are the same. ubyte_t first_entry_val = *(((ubyte_t*)values.data()) + j); if (cur_count[first_entry_val] != nb) { // Create offsets link[0] = ranks2.data(); for (rank_t i = 1; i < 256; i++) link[i] = link[i - 1] + cur_count[i - 1]; // Perform Radix Sort ubyte_t* input_bytes = (ubyte_t*)values.data(); input_bytes += j; if (ranks_are_invalid) { for (rank_t i = 0; i < nb; i++) *link[input_bytes[i << 2]]++ = i; ranks_are_invalid = false; } else { rank_t* indices = ranks.data(); rank_t* indices_end = indices + nb; while (indices != indices_end) { rank_t id = *indices++; *link[input_bytes[id << 2]]++ = id; } } // Swap ranks - valid indices are in ranks after the swap. ranks.swap(ranks2); } } // If all values are equal, fill ranks with sequential integers. if (ranks_are_invalid) std::iota(ranks.begin(), ranks.end(), 0); } // Instantiate supported sort types. template class radix_sort<unsigned int, unsigned int>; template class radix_sort<unsigned int, unsigned short>; } // namespace mkfit
30.9
106
0.581446
[ "vector" ]
5a82033851910f74b39cc863cc9165ea72e88718
12,398
cpp
C++
src/test_application/activescenes/scenarios_enginetest.cpp
larrymason01/osp-magnum
2a408428799d32b54901015a7f142104070d1cbb
[ "MIT" ]
null
null
null
src/test_application/activescenes/scenarios_enginetest.cpp
larrymason01/osp-magnum
2a408428799d32b54901015a7f142104070d1cbb
[ "MIT" ]
null
null
null
src/test_application/activescenes/scenarios_enginetest.cpp
larrymason01/osp-magnum
2a408428799d32b54901015a7f142104070d1cbb
[ "MIT" ]
null
null
null
/** * Open Space Program * Copyright © 2019-2021 Open Space Program Project * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "scenarios.h" #include "CameraController.h" #include "../ActiveApplication.h" #include <osp/Active/basic.h> #include <osp/Active/drawing.h> #include <osp/Active/SysHierarchy.h> #include <osp/Active/SysRender.h> #include <osp/Active/opengl/SysRenderGL.h> #include <osp/Shaders/Phong.h> #include <osp/Resource/resources.h> #include <longeron/id_management/registry.hpp> #include <Magnum/Trade/MeshData.h> #include <Magnum/Trade/ImageData.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Corrade/Containers/ArrayViewStl.h> using osp::active::ActiveEnt; using Magnum::Trade::MeshData; using Magnum::Trade::ImageData2D; // for the 0xrrggbb_rgbf and angle literals using namespace Magnum::Math::Literals; namespace testapp::enginetest { // Materials used by the test scene. A more general application may want to // generate IDs at runtime, and map them to named identifiers. constexpr int const gc_mat_common = 0; constexpr int const gc_mat_visualizer = 1; constexpr int const gc_maxMaterials = 2; /** * @brief State of the entire engine test scene */ struct EngineTestScene { ~EngineTestScene() { osp::active::SysRender::clear_owners(m_drawing); osp::active::SysRender::clear_resource_owners(m_drawingRes, *m_pResources); m_drawing.m_meshRefCounts.ref_release(m_meshCube); } osp::Resources *m_pResources; // ID registry generates entity IDs, and keeps track of which ones exist lgrn::IdRegistry<ActiveEnt> m_activeIds; // Components and supporting data structures osp::active::ACtxBasic m_basic; osp::active::ACtxDrawing m_drawing; osp::active::ACtxDrawingRes m_drawingRes; // Hierarchy root, needs to exist so all hierarchy entities are connected ActiveEnt m_hierRoot{lgrn::id_null<ActiveEnt>()}; // The rotating cube ActiveEnt m_cube{lgrn::id_null<ActiveEnt>()}; osp::active::MeshIdOwner_t m_meshCube; }; entt::any setup_scene(osp::Resources& rResources, osp::PkgId pkg) { using namespace osp::active; entt::any sceneAny = entt::make_any<EngineTestScene>(); EngineTestScene &rScene = entt::any_cast<EngineTestScene&>(sceneAny); rScene.m_pResources = &rResources; // Take ownership of cube mesh osp::ResId const resCube = rResources.find(osp::restypes::gc_mesh, pkg, "cube"); assert(resCube != lgrn::id_null<osp::ResId>()); MeshId const meshCube = SysRender::own_mesh_resource(rScene.m_drawing, rScene.m_drawingRes, rResources, resCube); rScene.m_meshCube = rScene.m_drawing.m_meshRefCounts.ref_add(meshCube); // Allocate space to fit all materials rScene.m_drawing.m_materials.resize(gc_maxMaterials); // Create hierarchy root entity rScene.m_hierRoot = rScene.m_activeIds.create(); rScene.m_basic.m_hierarchy.emplace(rScene.m_hierRoot); // Create camera entity ActiveEnt camEnt = rScene.m_activeIds.create(); // Create camera transform and draw transform ACompTransform &rCamTf = rScene.m_basic.m_transform.emplace(camEnt); rCamTf.m_transform.translation().z() = 25; // Create camera component ACompCamera &rCamComp = rScene.m_basic.m_camera.emplace(camEnt); rCamComp.m_far = 1u << 24; rCamComp.m_near = 1.0f; rCamComp.m_fov = 45.0_degf; // Add camera to hierarchy SysHierarchy::add_child( rScene.m_basic.m_hierarchy, rScene.m_hierRoot, camEnt); // Make a cube rScene.m_cube = rScene.m_activeIds.create(); // Add cube mesh to cube rScene.m_drawing.m_mesh.emplace( rScene.m_cube, rScene.m_drawing.m_meshRefCounts.ref_add(rScene.m_meshCube)); rScene.m_drawing.m_meshDirty.push_back(rScene.m_cube); // Add common material to cube MaterialData &rMatCommon = rScene.m_drawing.m_materials[gc_mat_common]; rMatCommon.m_comp.emplace(rScene.m_cube); rMatCommon.m_added.push_back(rScene.m_cube); // Add transform and draw transform rScene.m_basic.m_transform.emplace(rScene.m_cube); // Add opaque and visible component rScene.m_drawing.m_opaque.emplace(rScene.m_cube); rScene.m_drawing.m_visible.emplace(rScene.m_cube); // Add cube to hierarchy, parented to root SysHierarchy::add_child( rScene.m_basic.m_hierarchy, rScene.m_hierRoot, rScene.m_cube); return std::move(sceneAny); } /** * @brief Update an EngineTestScene, this just rotates the cube * * @param rScene [ref] scene to update */ void update_test_scene(EngineTestScene& rScene, float delta) { // Rotate the cube osp::Matrix4 &rCubeTf = rScene.m_basic.m_transform.get(rScene.m_cube).m_transform; rCubeTf = Magnum::Matrix4::rotationY(90.0_degf * delta) * rCubeTf; // Sort hierarchy, required by renderer osp::active::SysHierarchy::sort(rScene.m_basic.m_hierarchy); } //----------------------------------------------------------------------------- // Everything below is for rendering /** * @brief Data needed to render the EngineTestScene */ struct EngineTestRenderer { EngineTestRenderer(ActiveApplication &rApp) : m_camCtrl(rApp.get_input_handler()) { } osp::active::ACtxRenderGroups m_renderGroups{}; osp::active::ACtxSceneRenderGL m_renderGl{}; ActiveEnt m_camera{lgrn::id_null<ActiveEnt>()}; ACtxCameraController m_camCtrl; osp::shader::ACtxDrawPhong m_phong{}; }; /** * @brief Render an EngineTestScene * * @param rApp [ref] Application with GL context and resources * @param rScene [ref] Test scene to render * @param rRenderer [ref] Renderer data for test scene */ void render_test_scene( ActiveApplication& rApp, EngineTestScene const& rScene, EngineTestRenderer& rRenderer) { using namespace osp::active; using namespace osp::shader; using Magnum::GL::Framebuffer; using Magnum::GL::FramebufferClear; using Magnum::GL::Texture2D; // Assign Phong shader to entities with the gc_mat_common material, and put // results into the fwd_opaque render group RenderGroup &rGroupFwdOpaque = rRenderer.m_renderGroups.m_groups["fwd_opaque"]; MaterialData const &rMatCommon = rScene.m_drawing.m_materials[gc_mat_common]; assign_phong( rMatCommon.m_added, &rGroupFwdOpaque.m_entities, nullptr, rScene.m_drawing.m_opaque, rRenderer.m_renderGl.m_diffuseTexId, rRenderer.m_phong); SysRender::assure_draw_transforms( rScene.m_basic.m_hierarchy, rRenderer.m_renderGl.m_drawTransform, std::cbegin(rMatCommon.m_added), std::cend(rMatCommon.m_added)); // Load required meshes and textures into OpenGL SysRenderGL::sync_scene_resources(rScene.m_drawingRes, *rScene.m_pResources, rApp.get_render_gl()); // Assign GL meshes to entities with a mesh component SysRenderGL::assign_meshes( rScene.m_drawing.m_mesh, rScene.m_drawingRes.m_meshToRes, rScene.m_drawing.m_meshDirty, rRenderer.m_renderGl.m_meshId, rApp.get_render_gl()); // Assign GL textures to entities with a texture component SysRenderGL::assign_textures( rScene.m_drawing.m_diffuseTex, rScene.m_drawingRes.m_texToRes, rScene.m_drawing.m_diffuseDirty, rRenderer.m_renderGl.m_diffuseTexId, rApp.get_render_gl()); // Calculate hierarchy transforms SysRender::update_draw_transforms( rScene.m_basic.m_hierarchy, rScene.m_basic.m_transform, rRenderer.m_renderGl.m_drawTransform); // Get camera to calculate view and projection matrix ACompCamera const &rCamera = rScene.m_basic.m_camera.get(rRenderer.m_camera); ACompDrawTransform const &cameraDrawTf = rRenderer.m_renderGl.m_drawTransform.get(rRenderer.m_camera); ViewProjMatrix viewProj{ cameraDrawTf.m_transformWorld.inverted(), rCamera.calculate_projection()}; // Bind offscreen FBO Framebuffer &rFbo = rApp.get_render_gl().m_fbo; rFbo.bind(); // Clear it rFbo.clear( FramebufferClear::Color | FramebufferClear::Depth | FramebufferClear::Stencil); // Forward Render fwd_opaque group to FBO SysRenderGL::render_opaque( rRenderer.m_renderGroups.m_groups.at("fwd_opaque"), rScene.m_drawing.m_visible, viewProj); // Display FBO Texture2D &rFboColor = rApp.get_render_gl().m_texGl.get(rApp.get_render_gl().m_fboColor); SysRenderGL::display_texture(rApp.get_render_gl(), rFboColor); } on_draw_t generate_draw_func(EngineTestScene& rScene, ActiveApplication& rApp) { using namespace osp::active; using namespace osp::shader; // Create renderer data. This uses a shared_ptr to allow being stored // inside an std::function, which require copyable types std::shared_ptr<EngineTestRenderer> pRenderer = std::make_shared<EngineTestRenderer>(rApp); // Create Phong shaders auto const texturedFlags = Phong::Flag::DiffuseTexture | Phong::Flag::AlphaMask | Phong::Flag::AmbientTexture; pRenderer->m_phong.m_shaderDiffuse = Phong{texturedFlags, 2}; pRenderer->m_phong.m_shaderUntextured = Phong{{}, 2}; pRenderer->m_phong.assign_pointers( pRenderer->m_renderGl, rApp.get_render_gl()); // Select first camera for rendering ActiveEnt const camEnt = rScene.m_basic.m_camera.at(0); pRenderer->m_camera = camEnt; rScene.m_basic.m_camera.get(camEnt).set_aspect_ratio( osp::Vector2(Magnum::GL::defaultFramebuffer.viewport().size())); SysRender::add_draw_transforms_recurse( rScene.m_basic.m_hierarchy, pRenderer->m_renderGl.m_drawTransform, camEnt); // Create render group for forward opaque pass pRenderer->m_renderGroups.m_groups.emplace("fwd_opaque", RenderGroup{}); // Set all materials dirty for (MaterialData &rMat : rScene.m_drawing.m_materials) { rMat.m_added.assign(std::begin(rMat.m_comp), std::end(rMat.m_comp)); } // Set all meshs dirty auto &rMeshSet = static_cast<active_sparse_set_t&>(rScene.m_drawing.m_mesh); rScene.m_drawing.m_meshDirty.assign(std::begin(rMeshSet), std::end(rMeshSet)); // Set all textures dirty auto &rDiffSet = static_cast<active_sparse_set_t&>(rScene.m_drawing.m_diffuseTex); rScene.m_drawing.m_diffuseDirty.assign(std::begin(rMeshSet), std::end(rMeshSet)); return [&rScene, pRenderer = std::move(pRenderer)] ( ActiveApplication& rApp, float delta) { update_test_scene(rScene, delta); // Rotate and move the camera based on user inputs SysCameraController::update_view( pRenderer->m_camCtrl, rScene.m_basic.m_transform.get(pRenderer->m_camera), delta); SysCameraController::update_move( pRenderer->m_camCtrl, rScene.m_basic.m_transform.get(pRenderer->m_camera), delta, true); render_test_scene(rApp, rScene, *pRenderer); SysRender::clear_dirty_materials(rScene.m_drawing.m_materials); }; } } // namespace testapp::enginetest
35.422857
117
0.703743
[ "mesh", "render", "transform" ]
5a86f7848a2dfdd4182dbb136ce4cd1b50ced6a0
2,175
cc
C++
src/attributes/YDateCoordinateWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/YDateCoordinateWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/YDateCoordinateWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 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. ******************************* LICENSE *******************************/ /*! \\file YDateCoordinateAttributes.h \\brief Definition of YDateCoordinate Attributes class. This file is automatically generated. Do Not Edit! */ #include "MagRequest.h" #include "YDateCoordinateWrapper.h" #include "MagicsParameter.h" #include "Factory.h" #include "MagTranslator.h" #include "MagicsGlobal.h" using namespace magics; YDateCoordinateWrapper::YDateCoordinateWrapper(): ydatecoordinate_(new YDateCoordinate()) { YCoordinateWrapper::object(ydatecoordinate_); } YDateCoordinateWrapper::YDateCoordinateWrapper(YDateCoordinate* ydatecoordinate): ydatecoordinate_(ydatecoordinate) { YCoordinateWrapper::object(ydatecoordinate_); } YDateCoordinateWrapper::~YDateCoordinateWrapper() { } void YDateCoordinateWrapper::set(const MagRequest& request) { YCoordinateWrapper::set(request); if (request.countValues("Y_DATE_MIN") ) { string date_min_value = request("Y_DATE_MIN"); ydatecoordinate_->date_min_ = date_min_value; } if (request.countValues("Y_DATE_MAX") ) { string date_max_value = request("Y_DATE_MAX"); ydatecoordinate_->date_max_ = date_max_value; } if (request.countValues("Y_AUTOMATIC_REVERSE") ) { string reverse_value = request("Y_AUTOMATIC_REVERSE"); ydatecoordinate_->reverse_ = MagTranslator<string, bool>()(reverse_value); } if (request.countValues("Y_AUTOMATIC") ) { string automatic_value = request("Y_AUTOMATIC"); ydatecoordinate_->automatic_ = MagTranslator<string, AxisAutomaticSetting>()(automatic_value); } } void YDateCoordinateWrapper::print(ostream& out) const { out << "YDateCoordinateWrapper[]"; }
22.65625
115
0.707586
[ "object" ]
5a92e0e8e500c8876429ddd6dd3d0b6e1820b3eb
3,555
hpp
C++
tools/Vitis-AI-Library/centerpoint/src/preprocess.hpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tools/Vitis-AI-Library/centerpoint/src/preprocess.hpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tools/Vitis-AI-Library/centerpoint/src/preprocess.hpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* * Copyright 2019 Xilinx 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. */ #pragma once #include <string> #include <vector> #include <utility> #include <cassert> #include <initializer_list> #include <vitis/ai/profiling.hpp> using namespace std; namespace vitis { namespace ai { namespace centerpoint{ constexpr uint32_t MAX_POINTS_NUM = 40; constexpr uint32_t MAX_VOXELS_NUM = 20000; template<typename T> struct DataContainer { std::vector<uint32_t> shape; std::vector<T> data; std::vector<uint64_t> stride; explicit DataContainer(const std::vector<uint32_t>& data_shape, const T& val) : shape{data_shape}, stride(data_shape.size()) { long long size = 1; // e.g data_shape = {3, 4, 5} // stride = {20, 5, 1} for (auto i = 0u; i < data_shape.size(); ++i) { stride[data_shape.size() - 1 - i] = size; size *= data_shape[data_shape.size() - 1 - i]; } data.assign(size, val); } DataContainer(const DataContainer& other) = default; DataContainer(DataContainer&& other) = default; DataContainer& operator = (const DataContainer& other){ this->shape = other.shape; this->data = other.data; this->stride = other.stride; return *this; } DataContainer& operator = (DataContainer&& other){ this->shape = std::move(other.shape); this->data = std::move(other.data); this->stride = std::move(other.stride); return *this; } virtual ~DataContainer() = default; T& at(std::initializer_list<int32_t> l) { assert(l.size() == shape.size()); auto pos = 0llu; auto it = l.begin(); for (uint32_t i = 0u; i < stride.size(); ++i, ++it) { pos += stride[i] * (*it); } assert(pos < data.size()); return data[pos]; } const T& at(std::initializer_list<int32_t> l) const { assert(l.size() == shape.size()); auto pos = 0llu; auto it = l.begin(); for (uint32_t i = 0u; i < stride.size(); ++i, ++it) { pos += stride[i] * (*it); } assert(pos < data.size()); return data[pos]; } }; typedef struct { int voxel_num; DataContainer<float> voxels; DataContainer<int> num_points; // points number of every voxel DataContainer<int> coors; } VoxelizeResult; typedef struct { int voxel_num; vector<float> voxels; vector<int> num_points; // points number of every voxel vector<int> coors; } VoxelizeResult2; // note: need input tensor size std::vector<int> preprocess(const DataContainer<float> &points, int8_t *input_tensor_ptr, float input_tensor_scale); std::vector<int> preprocess2(const vector<float> &points, int8_t *input_tensor_ptr, float input_tensor_scale); //std::vector<int> preprocess3(const vector<float> &points, int8_t *input_tensor_ptr, float input_tensor_scale); std::vector<int> preprocess3(const vector<float> &points, int dim, const std::vector<float> &input_mean, const std::vector<float> &input_scale, int8_t *input_tensor_ptr); } // end of pointpillars_nuscenes }}
30.127119
116
0.663291
[ "shape", "vector" ]
5aa052acfd7f8d69b079ebee34ea878ecccf0db0
1,601
cpp
C++
JammaLib/src/utils/ImageUtils.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
JammaLib/src/utils/ImageUtils.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
JammaLib/src/utils/ImageUtils.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
#include "ImageUtils.h" using namespace utils; std::optional<std::tuple<std::vector<unsigned char>, unsigned int, unsigned int>> ImageUtils::LoadTga(const std::string& fileName) { FILE* file; auto res = fopen_s(&file, fileName.c_str(), "rb"); if (!file) return std::nullopt; // Read the header of the TGA, compare it with the known headers for compressed and uncompressed TGAs unsigned char header[18]; fread(header, sizeof(unsigned char) * 18, 1, file); while (header[0] > 0) { --header[0]; unsigned char temp; fread(&temp, sizeof(unsigned char), 1, file); } unsigned int width = header[13] * 256 + header[12]; unsigned int height = header[15] * 256 + header[14]; unsigned int bpp = header[16] / 8; // Check if parameters are valid if ((width <= 0) || (height <= 0) || ((bpp != 1) && (bpp != 3) && (bpp != 4))) { fclose(file); return std::nullopt; } auto pixels = std::vector<unsigned char>(width * height * 4); if (header[2] == 2) { unsigned char pixel[4] = { 255, 255, 255, 255 }; const unsigned int numPixels = width * height; for (unsigned int i = 0; i < numPixels; ++i) { fread(pixel, sizeof(unsigned char) * bpp, 1, file); if (bpp == 1) { pixel[1] = pixel[0]; pixel[2] = pixel[0]; pixel[3] = pixel[0]; } pixels[(i * 4) + 0] = pixel[0]; pixels[(i * 4) + 1] = pixel[1]; pixels[(i * 4) + 2] = pixel[2]; pixels[(i * 4) + 3] = pixel[3]; } } else { fclose(file); return std::nullopt; } fclose(file); return std::tuple<std::vector<unsigned char>, unsigned int, unsigned int>(pixels, width, height); }
23.544118
130
0.609619
[ "vector" ]
5aacb68fd2240a2ee80429088e64d1c6c19c8059
12,842
cpp
C++
development/C++/samples/server/DemoServer/Function.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
19
2021-05-19T11:03:57.000Z
2022-03-18T06:53:48.000Z
development/C++/samples/server/DemoServer/Function.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
8
2021-04-26T10:47:20.000Z
2022-03-15T11:25:07.000Z
development/C++/samples/server/DemoServer/Function.cpp
Movares/OPC-Classic-SDK
65e022dd4ccf20bbdacdfc49cac23bd99d773b98
[ "MIT" ]
11
2021-05-28T06:35:20.000Z
2022-03-31T14:07:25.000Z
#include "stdafx.h" #include "Function.h" #include "OpcServer.h" #include "EUEngineeringUnits.h" #include <math.h> extern unsigned long CAT_ID_DA_WRITE_SIMPLE; extern unsigned long CAT_ID_DA_WRITE_TRACKING; void VariableProperty::createAngle(DemoDaAddressSpaceElement* pElement, tstring name, tstring description, tstring itemId, tagEnumAccessRights accessRights) { if (pElement) { DaProperty* angleProperty = new DaProperty(); angleProperty->setId(6020); angleProperty->setName(name); angleProperty->setDescription(description); angleProperty->setItemId(itemId); angleProperty->setDatatype(VT_I2); angleProperty->setAccessRights(accessRights); pElement->addProperty(angleProperty); } } void VariableProperty::setAnalogEngineeringUnits(DemoDaAddressSpaceElement* pElement, double lowLimit, double highLimit, tagEnumAccessRights accessRights) { if (pElement) { DateTime now; now.now(); tstring typeStr = _T("EUType"); tstring typeItemId = _T("7"); Variant aVariant((long)EnumEUType_ANALOG); ValueQT aValueQT(aVariant, EnumQuality_GOOD, now); DaConstantProperty* euType = new DaConstantProperty( 7, typeStr, typeItemId, aValueQT); pElement->addProperty(euType); tstring highStr = _T("High EU"); tstring highDescriptionStr = _T("High EU Description"); tstring highItemId = _T("102"); DaProperty* euHigh = new DaProperty(); euHigh->setId(102); euHigh->setName(highStr); euHigh->setDescription(highDescriptionStr); euHigh->setItemId(highItemId); euHigh->setDatatype(VT_R8); euHigh->setAccessRights(accessRights); pElement->addProperty(euHigh); tstring lowStr = _T("Low EU"); tstring lowDescriptionStr = _T("Low EU Description"); tstring lowItemId = _T("103"); DaProperty* euLow = new DaProperty(); euLow->setId(103); euLow->setName(lowStr); euLow->setDescription(lowDescriptionStr); euLow->setItemId(lowItemId); euLow->setDatatype(VT_R8); euLow->setAccessRights(accessRights); pElement->addProperty(euLow); } } double VariableProperty::convertToRadian(double angle) { double radianAngle = 0.0; // calc radian angle static double pi = 3.1415926535; radianAngle = (2 * pi) * ((double)angle / 360.0); return radianAngle; } SimulationVariable::SimulationVariable() { tstring name = _T("automatic change"); setName(name); setIoMode(EnumIoMode_REPORT); setDatatype(VT_BOOL); setAccessRights(EnumAccessRights_READWRITEABLE); } void SimulationVariable::handleReadRequest(DaRequest* pRequest) { if (pRequest == NULL) { return; } SimulationVariable* pElement = NULL; pElement = dynamic_cast<SimulationVariable*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT cacheValue; pElement->getCacheValue(cacheValue); pRequest->setValue(cacheValue); pRequest->setResult(S_OK); } else { //should never get here pRequest->setResult(E_FAIL); } } void SimulationVariable::handleWriteRequest(DaRequest* pRequest) { if (pRequest == NULL) { return; } SimulationVariable* pElement = NULL; pElement = dynamic_cast<SimulationVariable*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT* pValue = pRequest->getValue(); pRequest->setResult(pElement->valueChanged(*pValue)); g_simulationEnabled = pValue->getData().boolVal; #ifdef TBC_OS_WINDOWS if (g_simulationChanged) { SetEvent(g_simulationChanged); } #endif #ifdef TBC_OS_LINUX g_events.signal(1); #endif } else { //should never get here pRequest->setResult(E_FAIL); } } void SimulationVariable::init() { DateTime now; now.now(); Variant aVariant(true); ValueQT val(aVariant, EnumQuality_GOOD, now); valueChanged(val); } SleepIntervalVariable::SleepIntervalVariable() { tstring name = _T("automatic change period"); setName(name); setIoMode(EnumIoMode_REPORT); setDatatype(VT_UI4); setAccessRights(EnumAccessRights_READWRITEABLE); } void SleepIntervalVariable::init() { DateTime now; now.now(); unsigned int defaultValue = 1000; Variant aVariant(defaultValue); ValueQT val(aVariant, EnumQuality_GOOD, now); valueChanged(val); } void SleepIntervalVariable::handleReadRequest(DaRequest* pRequest) { if (pRequest == NULL) { return; } SleepIntervalVariable* pElement = NULL; pElement = dynamic_cast<SleepIntervalVariable*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT cacheValue; pElement->getCacheValue(cacheValue); pRequest->setValue(cacheValue); pRequest->setResult(S_OK); } else { //should never get here pRequest->setResult(E_FAIL); } } void SleepIntervalVariable::handleWriteRequest(DaRequest* pRequest) { if (pRequest == NULL) { return; } SleepIntervalVariable* pElement = NULL; pElement = dynamic_cast<SleepIntervalVariable*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT* pValue = pRequest->getValue(); pRequest->setResult(pElement->valueChanged(*pValue)); g_simulationThreadSleepInterval = pValue->getData().intVal; #ifdef TBC_OS_WINDOWS if (g_simulationChanged) { SetEvent(g_simulationChanged); } #endif #ifdef TBC_OS_LINUX g_events.signal(1); #endif } else { //should never get here pRequest->setResult(E_FAIL); } } Function::Function(IN tstring tagName) { m_angle = 0; setName(tagName); setIoMode(EnumIoMode_REPORT); setAccessRights(EnumAccessRights_READABLE); setDatatype(VT_R8); // create angle property VariableProperty::createAngle(this, tstring(_T("Angle")), tstring(_T("Angle Description")), tstring(_T("Angle")), EnumAccessRights_READWRITEABLE); //create High Eu, Low EU, VariableProperty::setAnalogEngineeringUnits(this, -1.0, 1.0, EnumAccessRights_READABLE); } void Function::handleReadRequest(IN DaRequest* pRequest) { if (pRequest == NULL) { return; } Function* pElement = NULL; pElement = dynamic_cast<Function*>(pRequest->getAddressSpaceElement()); if (pElement) { if (pRequest->getPropertyId() == 0) { // get address space element value take the Toolkit cache value ValueQT cacheValue; pElement->getCacheValue(cacheValue); pRequest->setValue(cacheValue); pRequest->setResult(S_OK); } else { // the element's property will handle this request pElement->getPropertyValue(pRequest); } // end if ... else } else { // should never get here pRequest->setResult(E_FAIL); } } // handleRequest void Function::handleWriteRequest(DaRequest* pRequest) { if (pRequest == NULL) { return; } Function* pElement = NULL; pElement = dynamic_cast<Function*>(pRequest->getAddressSpaceElement()); if (pElement) { if (pRequest->getPropertyId() == 0) { ValueQT* pValue = pRequest->getValue(); pRequest->setResult(pElement->valueChanged(*pValue)); } else if ((pRequest->getPropertyId() == 6020)) { ValueQT* writeValue = pRequest->getValue(); pElement->setValue(writeValue); pRequest->setResult(S_OK); } else { //should not get here for the moment pRequest->setResult(E_FAIL); } } else { //should never get here pRequest->setResult(E_FAIL); } } void Function::simulation(void) { } void Function::setValue(ValueQT* pValue) { } SinFunction::SinFunction() : Function(_T("sin")) { } void SinFunction::simulation(void) { m_angle++; if (m_angle >= 360) { m_angle = 0; } double value = ::sin(VariableProperty::convertToRadian((double)m_angle)); DateTime now; now.now(); Variant aVariant(value); ValueQT val(aVariant, EnumQuality_GOOD, now); this->valueChanged(val); } void SinFunction::setValue(ValueQT* pValue) { if (pValue) { m_angle = pValue->getData().iVal; double value = ::sin(VariableProperty::convertToRadian((double)m_angle)); DateTime now; now.now(); Variant aVariant(value); ValueQT val(aVariant, EnumQuality_GOOD, now); this->valueChanged(val); } } CosFunction::CosFunction() : Function(_T("cos")) { } void CosFunction::simulation(void) { m_angle++; if (m_angle >= 360) { m_angle = 0; } double value = ::cos(VariableProperty::convertToRadian((double)m_angle)); DateTime now; now.now(); Variant aVariant(value); ValueQT val(aVariant, EnumQuality_GOOD, now); this->valueChanged(val); } void CosFunction::setValue(ValueQT* pValue) { if (pValue) { m_angle = pValue->getData().iVal; double value = ::cos(VariableProperty::convertToRadian((double)m_angle)); DateTime now; now.now(); Variant aVariant(value); ValueQT val(aVariant, EnumQuality_GOOD, now); this->valueChanged(val); } } TanFunction::TanFunction() : Function(_T("tan")) { } void TanFunction::simulation(void) { m_angle++; if (m_angle >= 360) { m_angle = 0; } double value = ::tan(VariableProperty::convertToRadian((double)m_angle)); DateTime now; now.now(); Variant aVariant(value); ValueQT val(aVariant, EnumQuality_GOOD, now); this->valueChanged(val); } void TanFunction::setValue(ValueQT* pValue) { if (pValue) { m_angle = pValue->getData().iVal; double value = ::tan(VariableProperty::convertToRadian((double)m_angle)); DateTime now; now.now(); Variant aVariant(value); ValueQT val(aVariant, EnumQuality_GOOD, now); this->valueChanged(val); } } AlarmSimulation::AlarmSimulation(tstring name , enum AlarmType alarmType) { setName(name); setAccessRights(EnumAccessRights_READWRITEABLE); m_alarmType = alarmType; setDatatype(VT_BOOL); setIoMode(EnumIoMode_POLL); } void AlarmSimulation::init() { DateTime time; time.now(); Variant theValue; theValue.setBOOL(FALSE); ValueQT aValueQT(theValue, EnumQuality_GOOD, time); valueChanged(aValueQT); } void AlarmSimulation::handleReadRequest(IN DaRequest* pRequest) { if (pRequest == NULL) { return; } AlarmSimulation* pElement = NULL; pElement = dynamic_cast<AlarmSimulation*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT cacheValue; pElement->getCacheValue(cacheValue); pRequest->setValue(cacheValue); pRequest->setResult(S_OK); } else { //should never get here pRequest->setResult(E_FAIL); } } void AlarmSimulation::handleWriteRequest(IN DaRequest* pRequest) { #ifdef TBC_OS_WINDOWS if (pRequest == NULL) { return; } AlarmSimulation* pElement = NULL; pElement = dynamic_cast<AlarmSimulation*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT* pValue = pRequest->getValue(); pRequest->setResult(pElement->valueChanged(*pValue)); //now generate the event std::vector<Variant> attributeValues(1); attributeValues[0] = pValue->getData(); tstring anActorID(_T("alarm.simulation")); tstring message(_T("Boolean value: ")); if (attributeValues[0].boolVal == 0) { message += _T("FALSE"); } else { message += _T("TRUE"); } switch (pElement->m_alarmType) { case simple: { tstring name = _T("alarm simulation.fire simple event"); AeEvent fireSimpleEvent(EnumEventType_SIMPLE, name, CAT_ID_DA_WRITE_SIMPLE); fireSimpleEvent.setSeverity(700); fireSimpleEvent.setActorId(anActorID); fireSimpleEvent.setMessage(message); fireSimpleEvent.setAttributeValueList(attributeValues); fireSimpleEvent.fire(); } break; case tracking: { tstring name = _T("alarm simulation.fire tracking event"); AeEvent fireTrackingEvent(EnumEventType_TRACKING, name, CAT_ID_DA_WRITE_TRACKING); fireTrackingEvent.setSeverity(750); fireTrackingEvent.setActorId(anActorID); fireTrackingEvent.setMessage(message); fireTrackingEvent.setAttributeValueList(attributeValues); fireTrackingEvent.fire(); } break; } } else { //should never get here pRequest->setResult(E_FAIL); } #endif } void AlarmSimulation::simulation() { } KeyVariable::KeyVariable() { tstring name = _T("key"); setName(name); setAccessRights(EnumAccessRights_READABLE); setDatatype(VT_UI1); setIoMode(EnumIoMode_POLL); } void KeyVariable::init() { DateTime time; time.now(); Variant theValue; theValue.setUI1(0); ValueQT aValueQT(theValue, EnumQuality_GOOD, time); valueChanged(aValueQT); } void KeyVariable::handleReadRequest(IN DaRequest* pRequest) { if (pRequest == NULL) { return; } KeyVariable* pElement = NULL; pElement = dynamic_cast<KeyVariable*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT cacheValue; pElement->getCacheValue(cacheValue); pRequest->setValue(cacheValue); pRequest->setResult(S_OK); } else { //should never get here pRequest->setResult(E_FAIL); } } void KeyVariable::handleWriteRequest(IN DaRequest* pRequest) { if (pRequest == NULL) { return; } KeyVariable* pElement = NULL; pElement = dynamic_cast<KeyVariable*>(pRequest->getAddressSpaceElement()); if (pElement) { ValueQT* pValue = pRequest->getValue(); pRequest->setResult(pElement->valueChanged(*pValue)); } else { //should never get here pRequest->setResult(E_FAIL); } }
20.915309
89
0.719826
[ "vector" ]
5aae9690e7ff5502edb110d5445011434b62f0a4
1,615
cpp
C++
ThreadPool.cpp
xinan/ParallelWebCrawler
0c582b3bff1f22f7d05889e4723f3814a4099a39
[ "MIT" ]
7
2016-10-05T04:37:58.000Z
2021-11-29T10:35:52.000Z
ThreadPool.cpp
xinan/ParallelWebCrawler
0c582b3bff1f22f7d05889e4723f3814a4099a39
[ "MIT" ]
null
null
null
ThreadPool.cpp
xinan/ParallelWebCrawler
0c582b3bff1f22f7d05889e4723f3814a4099a39
[ "MIT" ]
null
null
null
// // Created by Liu Xinan on 24/9/16. // // Modified from https://github.com/progschj/ThreadPool/ // #include "ThreadPool.h" ThreadPool::ThreadPool(size_t number_of_threads) { auto worker_thread = [this] { std::function<void()> task; while (true) { { // Acquire lock. std::unique_lock<std::mutex> lock(lock_); // Wait until we should stop, or task queue is not empty. condition_.wait(lock, [this]() { return this->should_stop_ || !this->tasks_.empty(); }); // If we should stop, we abandon the rest of the task queue and just return. if (should_stop_) { break; } task = std::move(tasks_.front()); tasks_.pop(); } // Release lock. // Execute the task. task(); } condition_.notify_all(); }; // Create a vector of worker threads. for (size_t i = 0; i < number_of_threads; ++i) { workers_.emplace_back(worker_thread); } } void ThreadPool::stop() { { // Acquire lock. std::unique_lock<std::mutex> lock(lock_); should_stop_ = true; } // Release lock. condition_.notify_all(); for (auto& worker : workers_) { worker.join(); } workers_.clear(); } ThreadPool::~ThreadPool() { { // Acquire lock. std::unique_lock<std::mutex> lock(lock_); should_stop_ = true; } // Release lock. condition_.notify_all(); for (auto& worker : workers_) { worker.join(); } }
23.405797
104
0.531889
[ "vector" ]
5ab9ce1950001cb319c888bdfa14df946de43039
2,233
cpp
C++
Protocol/Tests/ImportParserScenarios.cpp
takeupcode/TUCUT
17ef8064792b6b74e311d6438f43970cc97dba77
[ "MIT" ]
8
2018-10-29T02:42:52.000Z
2021-02-04T17:37:14.000Z
Protocol/Tests/ImportParserScenarios.cpp
takeupcode/TUCUT
17ef8064792b6b74e311d6438f43970cc97dba77
[ "MIT" ]
null
null
null
Protocol/Tests/ImportParserScenarios.cpp
takeupcode/TUCUT
17ef8064792b6b74e311d6438f43970cc97dba77
[ "MIT" ]
1
2019-11-07T02:18:23.000Z
2019-11-07T02:18:23.000Z
// // ImportParserScenarios.cpp // TUCUT // // Created by Wahid Tanner on 10/12/14. // Copyright © 2018 Take Up Code. All rights reserved. // #include <string> #include "../../Test/Test.h" #include "../ProtoParser.h" #include "../ImportParser.h" using namespace std; using namespace TUCUT; SCENARIO( ImportParser, "Construction/Normal", "unit,protocol", "ImportParser can be constructed." ) { Protocol::ImportParser parser; } SCENARIO( ImportParser, "Parsing/Normal", "unit,protocol", "ImportParser can parse no imports." ) { shared_ptr<Protocol::ProtoModel> model; Protocol::ProtoParser parser("Messages/ImportNone.proto"); model = parser.parse(); unsigned long expectedSize = 1; VERIFY_EQUAL(expectedSize, model->publicEnumTypes()->size()); VERIFY_EQUAL(expectedSize, model->publicMessageTypes()->size()); expectedSize = 0; VERIFY_EQUAL(expectedSize, model->privateEnumTypes()->size()); VERIFY_EQUAL(expectedSize, model->privateMessageTypes()->size()); } SCENARIO( ImportParser, "Parsing/Normal", "unit,protocol", "ImportParser can parse private import." ) { shared_ptr<Protocol::ProtoModel> model; Protocol::ProtoParser parser("Messages/ImportPrivate.proto"); model = parser.parse(); unsigned long expectedSize = 1; VERIFY_EQUAL(expectedSize, model->publicEnumTypes()->size()); VERIFY_EQUAL(expectedSize, model->publicMessageTypes()->size()); expectedSize = 4; VERIFY_EQUAL(expectedSize, model->privateEnumTypes()->size()); expectedSize = 3; VERIFY_EQUAL(expectedSize, model->privateMessageTypes()->size()); } SCENARIO( ImportParser, "Parsing/Normal", "unit,protocol", "ImportParser can parse public import." ) { shared_ptr<Protocol::ProtoModel> model; Protocol::ProtoParser parser("Messages/ImportPublic.proto"); model = parser.parse(); unsigned long expectedSize = 5; VERIFY_EQUAL(expectedSize, model->publicEnumTypes()->size()); expectedSize = 3; VERIFY_EQUAL(expectedSize, model->publicMessageTypes()->size()); expectedSize = 0; VERIFY_EQUAL(expectedSize, model->privateEnumTypes()->size()); expectedSize = 1; VERIFY_EQUAL(expectedSize, model->privateMessageTypes()->size()); }
29
101
0.708912
[ "model" ]
5abb41064e4dccd2e414afe0780e461ed9f4450b
673
cpp
C++
usaco/2020/december/silver/cowntagion.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
usaco/2020/december/silver/cowntagion.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
null
null
null
usaco/2020/december/silver/cowntagion.cpp
pi-guy-in-the-sky/competitive-programming
e079f6caf07b5de061ea4f56218f9b577e49a965
[ "MIT" ]
1
2020-10-25T05:46:57.000Z
2020-10-25T05:46:57.000Z
// solved #include <iostream> #include <vector> #include <math.h> using namespace std; const int MAXN = 1e5 + 5; vector<int> adj[MAXN]; bool vis[MAXN]; int deg[MAXN]; int total_dist = 0; void dfs(int u) { vis[u] = 1; if (deg[u] == 1) return; total_dist += ceil(log2(deg[u])); for (int v : adj[u]) { if (!vis[v]) { total_dist += 1; dfs(v); } } } int main() { int N; cin >> N; for (int i = 0; i < N - 1; ++i) { int a, b; cin >> a >> b; adj[a].push_back(b); adj[b].push_back(a); deg[a]++; deg[b]++; } deg[1]++; // hack dfs(1); // num splits cout << total_dist << '\n'; return 0; }
12.017857
35
0.488856
[ "vector" ]
5aca83c9470494b7b401133fd0a08cefae3e92b5
6,551
cpp
C++
Cpp/add_label/src/main.cpp
dtczhl/Slimmer
c93dac6a59828016484d8bef1c71e9ccceabab9c
[ "MIT" ]
null
null
null
Cpp/add_label/src/main.cpp
dtczhl/Slimmer
c93dac6a59828016484d8bef1c71e9ccceabab9c
[ "MIT" ]
null
null
null
Cpp/add_label/src/main.cpp
dtczhl/Slimmer
c93dac6a59828016484d8bef1c71e9ccceabab9c
[ "MIT" ]
null
null
null
/* using nearest point to add missing labels */ #include <iostream> #define PCL_NO_PRECOMPILE #include <pcl/pcl_macros.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include "DtcMainHelper.hpp" struct MyPointType{ PCL_ADD_POINT4D; int r; int g; int b; int label_orig; int label_pred; EIGEN_MAKE_ALIGNED_OPERATOR_NEW } EIGEN_ALIGN16; POINT_CLOUD_REGISTER_POINT_STRUCT (MyPointType, // here we assume a XYZ + "test" (as fields) (float, x, x) (float, y, y) (float, z, z) (int, r, r) (int, g, g) (int, b, b) (int, label_orig, label_orig) (int, label_pred, label_pred) ) void myReadPly(const std::string &file_name, pcl::PointCloud<MyPointType> &cloud) { int nSkipLine = 11; std::ifstream infile(file_name.c_str()); std::string line; for (int i = 0; i < nSkipLine; i++) { std::getline(infile, line); } float x, y, z; int r, g, b, label; while (std::getline(infile, line)){ std::istringstream iss(line); iss >> x >> y >> z >> r >> g >> b >> label; MyPointType point; point.x = x; point.y = y; point.z = z; point.r = r; point.g = g; point.b = b; point.label_orig = label; point.label_pred = -100; cloud.push_back(point); } } void add_miss_label(std::string orig_file, std::string pred_file, std::string save_file, int k_KNN){ uint64_t time_tot = 0, time_start, time_end; // int K = 1; std::vector<int> pointSearchIndex(k_KNN); std::vector<float> pointSearchDist(k_KNN); int *pVote = NULL; pcl::PointCloud<MyPointType> cloud_orig, cloud_pred, cloud_removed; myReadPly(orig_file, cloud_orig); myReadPly(pred_file, cloud_pred); time_start = DtcMainHelper::getTimestamp(); pcl::KdTreeFLANN<MyPointType> predKdTree; pcl::PointCloud<MyPointType>::Ptr ptrCloud(cloud_pred.makeShared()); predKdTree.setInputCloud(ptrCloud); time_end = DtcMainHelper::getTimestamp(); DtcMainHelper::dataToFile() << time_end - time_start << " "; time_tot += time_end - time_start; for (int i = 0; i < cloud_orig.size(); i++) { if (predKdTree.nearestKSearch(cloud_orig[i], k_KNN, pointSearchIndex, pointSearchDist) < k_KNN) { std::cerr << "Found Less Search" << std::endl; } if (pointSearchDist[0] != 0) { // point is not in simplified point cloud // hard voting int N_labels = 20; // [0, 19] pVote = new int[N_labels]{0}; for (int k = 0; k < k_KNN; k++) { pVote[cloud_pred[pointSearchIndex[k]].label_orig]++; } int maxValue = 0, maxIndex = 0; for (int j = 0; j < N_labels; j++) { if (pVote[j] > maxValue) { maxValue = pVote[j]; maxIndex = j; } } // cloud_orig[i].label_pred = cloud_pred[pointSearchIndex[0]].label_orig; cloud_orig[i].label_pred = maxIndex; // remove set MyPointType point; point.x = cloud_orig[i].x; point.y = cloud_orig[i].y; point.z = cloud_orig[i].z; point.r = cloud_orig[i].r; point.g = cloud_orig[i].g; point.b = cloud_orig[i].b; cloud_removed.push_back(point); } else { // point is in simplified point cloud cloud_orig[i].label_pred = cloud_pred[pointSearchIndex[0]].label_orig; } } time_start = DtcMainHelper::getTimestamp(); // for time calculating only // std::cout << "Full Size " << cloud_orig.size() << " Simplified: " << cloud_pred.size() << " Cloud removed points # = " << cloud_removed.size() << std::endl; for (int i = 0; i < cloud_removed.size(); i++) { if (predKdTree.nearestKSearch(cloud_removed[i], k_KNN, pointSearchIndex, pointSearchDist) < k_KNN) { std::cerr << "Found Less Search" << std::endl; } int N_labels = 20; // [0, 19] pVote = new int[N_labels]{0}; for (int k = 0; k < k_KNN; k++) { pVote[cloud_pred[pointSearchIndex[k]].label_orig]++; } int maxValue = 0, maxIndex = 0; for (int j = 0; j < N_labels; j++) { if (pVote[j] > maxValue) { maxValue = pVote[j]; maxIndex = j; } } // cloud_orig[i].label_pred = cloud_pred[pointSearchIndex[0]].label_orig; cloud_removed[i].label_pred = maxIndex; } time_end = DtcMainHelper::getTimestamp(); DtcMainHelper::dataToFile() << time_end - time_start << " "; time_tot += time_end - time_start; DtcMainHelper::dataToFile() << time_tot << std::endl; std::ofstream out(save_file); for (int i = 0; i < cloud_orig.size(); i++) { out << cloud_orig[i].x << " " << cloud_orig[i].y << " " << cloud_orig[i].z << " " << (int) cloud_orig[i].r << " " << (int) cloud_orig[i].g << " " << (int) cloud_orig[i].b << " " << (int) cloud_orig[i].label_orig << " " << (int) cloud_orig[i].label_pred << std::endl; } out.close(); } int main(int argc, char* argv[]) { /* Input: argv[0]: this program argv[1]: original_ply_file argv[2]: pred_ply_file argv[3]: save to file argv[4]: number of neighbors for missing label */ if (argc != 5) { std::cerr << "[add_label] requires argc: 5, input argc: " << argc << std::endl; std::cerr << "Format: program orig_file pred_file save_file k_in_KNN" << std::endl; exit(-1); } std::string orig_file(argv[1]); std::string pred_file(argv[2]); std::string save_file(argv[3]); int K_KNN = atoi(argv[4]); add_miss_label(orig_file, pred_file, save_file, K_KNN); // plot memory std::string process_name; process_name = "/proc/self/statm"; std::ifstream buffer(process_name.c_str()); int tSize = 0, resident = 0, share = 0; buffer >> tSize >> resident >> share; buffer.close(); long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages std::cout << "Memory (MB) " << resident * page_size_kb / 1000 << std::endl; return 0; }
34.298429
163
0.557777
[ "vector" ]
62c3714806796d650a575e086ffaa0d64fcb42bc
34,054
cxx
C++
SimVascular-master/Code/Source/sv4gui/Modules/Segmentation/sv4gui_ContourGroupDataInteractor.cxx
mccsssk2/SimVascularPM3_March2020
3cce6cc7be66545bea5dc3915a2db50a3892bf04
[ "BSD-3-Clause" ]
null
null
null
SimVascular-master/Code/Source/sv4gui/Modules/Segmentation/sv4gui_ContourGroupDataInteractor.cxx
mccsssk2/SimVascularPM3_March2020
3cce6cc7be66545bea5dc3915a2db50a3892bf04
[ "BSD-3-Clause" ]
null
null
null
SimVascular-master/Code/Source/sv4gui/Modules/Segmentation/sv4gui_ContourGroupDataInteractor.cxx
mccsssk2/SimVascularPM3_March2020
3cce6cc7be66545bea5dc3915a2db50a3892bf04
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) Stanford University, The Regents of the University of * California, and others. * * All Rights Reserved. * * See Copyright-SimVascular.txt for additional details. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define SVCONTOURGROUPDATAINTERACTOR_DBG MITK_DEBUG("sv4guiContourGroupDataInteractor") << __LINE__ << ": " #include "sv4gui_ContourGroupDataInteractor.h" #include "sv4gui_ContourOperation.h" #include "sv4gui_ContourCircle.h" #include "sv4gui_ContourEllipse.h" #include "sv4gui_ContourPolygon.h" #include "sv4gui_ContourSplinePolygon.h" #include "mitkInteractionPositionEvent.h" #include "mitkInternalEvent.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include "mitkPlaneGeometry.h" #include "mitkInternalEvent.h" #include "mitkDispatcher.h" #include "mitkBaseRenderer.h" #include "mitkUndoController.h" sv4guiContourGroupDataInteractor::sv4guiContourGroupDataInteractor() : mitk::DataInteractor() , m_SelectionAccuracy(0.1) , m_MinimumPointDistance( 25.0 ) , m_IsHovering( false ) , m_LastPointWasValid( false ) , m_ContourIndex(sv4guiContour::INVALID_INDEX) , m_Contour(NULL) , m_TimeStep(0) , m_Interaction3D(false) , m_Method("") , m_SubdivisionSpacing(0.1) , m_SelectedContourIndex(-2) { } sv4guiContourGroupDataInteractor::~sv4guiContourGroupDataInteractor() { } void sv4guiContourGroupDataInteractor::ConnectActionsAndFunctions() { CONNECT_CONDITION("contour_exists_on_current_slice", ContourExistsOnCurrentSlice); CONNECT_CONDITION("contour_has_control_points", CurrentContourHasControlPoints); CONNECT_CONDITION("group_has_unplaced_contour", GroupHasUnplacedContour); CONNECT_CONDITION("on_contour_plane", OnCurrentContourPlane); CONNECT_CONDITION("point_is_valid", PointIsValid); CONNECT_CONDITION("contour_is_finished", ContourIsFinished); CONNECT_CONDITION("minimal_contour_is_finished", MinimalContourIsFinished); CONNECT_CONDITION("is_over_contour", IsOverContour); CONNECT_CONDITION("is_over_contour2", IsOverContour2); CONNECT_CONDITION("is_over_point", IsOverPoint); CONNECT_CONDITION("method_is_specified", IsMethodSpecified); CONNECT_FUNCTION( "add_initial_point", AddInitialPoint); CONNECT_FUNCTION( "move_current_point", MoveCurrentPoint); CONNECT_FUNCTION( "finalize_contour", FinalizeContour); CONNECT_FUNCTION( "append_point", AppendPoint); CONNECT_FUNCTION( "select_point", SelectPoint ); CONNECT_FUNCTION( "deselect_point", DeselectPoint ); CONNECT_FUNCTION( "delete_contour", DeleteContour ); CONNECT_FUNCTION( "remove_selected_point", RemoveSelectedPoint); CONNECT_FUNCTION( "init_move", InitMove); CONNECT_FUNCTION( "finish_move", FinishMove); CONNECT_FUNCTION( "hide_preview_point", HidePreviewPoint ); CONNECT_FUNCTION( "set_preview_point", SetPreviewPoint ); CONNECT_FUNCTION( "insert_point", InsertPoint); } // ==========Conditions========= bool sv4guiContourGroupDataInteractor::ContourExistsOnCurrentSlice( const mitk::InteractionEvent* interactionEvent ) { m_ContourIndex=-2; m_Contour=NULL; mitk::BaseRenderer *renderer = interactionEvent->GetSender(); m_TimeStep = renderer->GetTimeStep(); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup*>( GetDataNode()->GetData() ); if(group==NULL) return false; if(IsOn2DView(interactionEvent)) { const mitk::PlaneGeometry *rendererPlaneGeometry = renderer->GetCurrentWorldPlaneGeometry(); m_ContourIndex=group->SearchContourByPlane(rendererPlaneGeometry,1.0,m_TimeStep); m_Contour=group->GetContour(m_ContourIndex,m_TimeStep); }else if(m_Interaction3D){ m_ContourIndex=group->GetCurrentIndexOn2DView(); m_Contour=group->GetContour(m_ContourIndex,m_TimeStep); } return m_Contour!=NULL; } bool sv4guiContourGroupDataInteractor::CurrentContourHasControlPoints( const mitk::InteractionEvent* interactionEvent ) { if(m_Contour&&m_Contour->GetControlPointNumber()>0) return true; else return false; } bool sv4guiContourGroupDataInteractor::GroupHasUnplacedContour( const mitk::InteractionEvent* /*interactionEvent*/ ) { sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group&&group->GetUnplacedContour(m_TimeStep)) return true; else return false; } bool sv4guiContourGroupDataInteractor::OnCurrentContourPlane( const mitk::InteractionEvent* interactionEvent ) { mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(m_Contour==NULL) return false; if(IsOn2DView(interactionEvent)) { return m_Contour->IsOnPlane(renderer->GetCurrentWorldPlaneGeometry(),0.1); } else { if(m_Interaction3D){ sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup*>( GetDataNode()->GetData() ); if(group==NULL) return false; return group->GetCurrentIndexOn2DView()!=-2; } else return false; } } bool sv4guiContourGroupDataInteractor::PointIsValid( const mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return false; if(m_Contour==NULL) return false; bool tooClose=false; mitk::Point3D point = positionEvent->GetPositionInWorld(); mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(IsOn2DView(interactionEvent)) { const mitk::PlaneGeometry *renderingPlaneGeometry = renderer->GetCurrentWorldPlaneGeometry(); mitk::Point2D newDisplayPosition; renderer->WorldToDisplay( point, newDisplayPosition ); for( int i=0; i < m_Contour->GetControlPointNumber(); i++ ) { if ( i != m_Contour->GetControlPointSelectedIndex() ) { mitk::Point3D previousPoint=m_Contour->GetControlPoint(i); if ( renderingPlaneGeometry->Distance( previousPoint ) < 0.1 ) { mitk::Point2D previousDisplayPosition; renderer->WorldToDisplay( previousPoint, previousDisplayPosition ); double a = newDisplayPosition[0] - previousDisplayPosition[0]; double b = newDisplayPosition[1] - previousDisplayPosition[1]; tooClose = (a * a + b * b < m_MinimumPointDistance ); } if ( tooClose ) return false; } } } else { if(m_Interaction3D) { for( int i=0; i < m_Contour->GetControlPointNumber(); i++ ) { if ( i != m_Contour->GetControlPointSelectedIndex() ) { mitk::Point3D previousPoint=m_Contour->GetControlPoint(i); double dis=point.EuclideanDistanceTo(previousPoint); tooClose=dis<GetSelectionAccuracy(); if ( tooClose ) return false; } } } else tooClose=true; } return !tooClose; } bool sv4guiContourGroupDataInteractor::ContourIsFinished( const mitk::InteractionEvent* /*interactionEvent*/ ) { if(m_Contour==NULL) return false; else return ( m_Contour->GetControlPointNumber() >= m_Contour->GetMaxControlPointNumber() ); } bool sv4guiContourGroupDataInteractor::MinimalContourIsFinished( const mitk::InteractionEvent* /*interactionEvent*/ ) { if(m_Contour==NULL) { return false; } else{ return ( m_Contour->GetControlPointNumber() >= m_Contour->GetMinControlPointNumber() ); } } bool sv4guiContourGroupDataInteractor::IsOverContour( const mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(m_Contour==NULL) return false; int nextContourPointIndex = SearchCoutourPoint(positionEvent , m_Contour , renderer ); int controlPointIndex = SearchControlPoint(positionEvent, m_Contour, renderer ); return nextContourPointIndex!=-2 && controlPointIndex==-2; } bool sv4guiContourGroupDataInteractor::IsOverContour2( const mitk::InteractionEvent* interactionEvent ) { m_SelectedContourIndex=-2; const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(renderer->GetMapperID()==mitk::BaseRenderer::Standard2D) return false; int timeStep = renderer->GetTimeStep(); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup*>( GetDataNode()->GetData() ); if(group==NULL) return false; for(int i=0;i<group->GetSize(timeStep);++i) { sv4guiContour* contour=group->GetContour(i,timeStep); if(contour) { int nextContourPointIndex = SearchCoutourPoint3D(positionEvent , contour ); if(nextContourPointIndex!=-2) { m_SelectedContourIndex=i; group->InvokeEvent( SelectContourEvent() ); return true; } } } return false; } bool sv4guiContourGroupDataInteractor::IsPointNearLine( const mitk::Point2D& point, const mitk::Point2D& startPoint, const mitk::Point2D& endPoint, double selectionDistance ) const { mitk::Vector2D n1 = endPoint - startPoint; n1.Normalize(); // Determine dot products between line vector and startpoint-point / endpoint-point vectors double l1 = n1 * (point - startPoint); double l2 = -n1 * (point - endPoint); // Determine projection of specified point onto line defined by start / end point mitk::Point2D crossPoint = startPoint + n1 * l1; double dist1 = crossPoint.EuclideanDistanceTo(point); double dist2 = endPoint.EuclideanDistanceTo(point); double dist3 = startPoint.EuclideanDistanceTo(point); if (((dist1 < selectionDistance) && (l1 > 0.0) && (l2 > 0.0)) || dist2 < selectionDistance || dist3 < selectionDistance) { return true; } return false; } bool sv4guiContourGroupDataInteractor::IsPoint3DNearLine( const mitk::Point3D& point, const mitk::Point3D& startPoint, const mitk::Point3D& endPoint, double selectionDistance ) const { mitk::Vector3D n1 = endPoint - startPoint; n1.Normalize(); double l1 = n1 * (point - startPoint); double l2 = -n1 * (point - endPoint); mitk::Point3D crossPoint = startPoint + n1 * l1; double dist1 = crossPoint.EuclideanDistanceTo(point); double dist2 = endPoint.EuclideanDistanceTo(point); double dist3 = startPoint.EuclideanDistanceTo(point); if (((dist1 < selectionDistance) && (l1 > 0.0) && (l2 > 0.0)) || dist2 < selectionDistance || dist3 < selectionDistance) { return true; } return false; } int sv4guiContourGroupDataInteractor::SearchCoutourPoint3D( const mitk::InteractionPositionEvent *positionEvent , sv4guiContour *contour ) const { mitk::Point3D point3d = positionEvent->GetPositionInWorld(); mitk::Point3D contourPoint; mitk::Point3D firstContourPoint; mitk::Point3D previousContourPoint; double selectionDistance=2*GetSelectionAccuracy(); bool firstPoint=true; for(int i=0;i<contour->GetContourPointNumber();i++) { contourPoint=contour->GetContourPoint(i); if ( firstPoint ) { firstContourPoint = contourPoint; firstPoint = false; } else if (IsPoint3DNearLine( point3d, previousContourPoint, contourPoint, selectionDistance ) ) { return i; } previousContourPoint = contourPoint; } if(IsPoint3DNearLine( point3d, contourPoint, firstContourPoint, selectionDistance ) ) return 0; return -2; } int sv4guiContourGroupDataInteractor::SearchCoutourPoint( const mitk::InteractionPositionEvent *positionEvent , sv4guiContour *contour , mitk::BaseRenderer *renderer ) const { if(IsOn2DView(positionEvent)) { mitk::Point2D displayPosition = positionEvent->GetPointerPositionOnScreen(); mitk::Point2D contourPoint; mitk::Point2D firstContourPoint; mitk::Point2D previousContourPoint; double selectionDistance=5.0; bool firstPoint=true; for(int i=0;i<contour->GetContourPointNumber();i++) { mitk::Point3D point=contour->GetContourPoint(i); renderer->WorldToDisplay( point, contourPoint ); if ( firstPoint ) { firstContourPoint = contourPoint; firstPoint = false; } else if (IsPointNearLine( displayPosition, previousContourPoint, contourPoint, selectionDistance ) ) { return i; } previousContourPoint = contourPoint; } if(IsPointNearLine( displayPosition, contourPoint, firstContourPoint, selectionDistance ) ) { return 0; } } else if(m_Interaction3D) { return SearchCoutourPoint3D(positionEvent,contour); } return -2; } bool sv4guiContourGroupDataInteractor::IsOverPoint( const mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return false; mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(m_Contour==NULL) return false; int pointIndex = -2; pointIndex = SearchControlPoint( positionEvent, m_Contour, renderer ); if ( pointIndex !=-2 ) { return true; } else { return false; } } int sv4guiContourGroupDataInteractor::SearchControlPoint( const mitk::InteractionPositionEvent* positionEvent, sv4guiContour* contour, mitk::BaseRenderer *renderer ) const { if(IsOn2DView(positionEvent)) { mitk::Point2D displayPosition = positionEvent->GetPointerPositionOnScreen(); mitk::Point2D displayControlPoint; for ( int i=contour->GetControlPointNumber()-1; i>=0; i-- ) { mitk::Point3D point=contour->GetControlPoint(i); renderer->WorldToDisplay( point, displayControlPoint ); if ( displayPosition.EuclideanDistanceTo( displayControlPoint ) < 5.0 ) { return i; } } } else if(m_Interaction3D) { mitk::Point3D point3d = positionEvent->GetPositionInWorld(); for ( int i=contour->GetControlPointNumber()-1; i>=0; i-- ) { mitk::Point3D point=contour->GetControlPoint(i); if ( point3d.EuclideanDistanceTo( point ) < GetSelectionAccuracy() ) { return i; } } } return -2; } void sv4guiContourGroupDataInteractor::InsertContour(sv4guiContourGroup* group, sv4guiContour* contour, int contourIndex, int timeStep) { if(group&&contour&&contourIndex>-2){ group->DeselectContours(); contour->SetSelected(true); sv4guiContourOperation* doOp = new sv4guiContourOperation(sv4guiContourOperation::OpINSERTCONTOUR,timeStep,contour,contourIndex); sv4guiContourOperation *undoOp = new sv4guiContourOperation(sv4guiContourOperation::OpREMOVECONTOUR,timeStep, contour, contourIndex); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(group, doOp, undoOp, "Insert Contour"); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent( operationEvent ); group->ExecuteOperation(doOp); // mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void sv4guiContourGroupDataInteractor::SetContour(sv4guiContourGroup* group, int contourIndex, sv4guiContour* newContour, int timeStep) { if(group&&contourIndex>-2) { sv4guiContour* originalContour=group->GetContour(contourIndex); sv4guiContourOperation* doOp = new sv4guiContourOperation(sv4guiContourOperation::OpSETCONTOUR,timeStep,newContour,contourIndex); sv4guiContourOperation *undoOp = new sv4guiContourOperation(sv4guiContourOperation::OpSETCONTOUR,timeStep, originalContour, contourIndex); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(group, doOp, undoOp, "Set Contour"); mitk::UndoController::GetCurrentUndoModel()->SetOperationEvent( operationEvent ); group->ExecuteOperation(doOp); // mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } bool sv4guiContourGroupDataInteractor::IsMethodSpecified( const mitk::InteractionEvent* interactionEvent ) { mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if (renderer && renderer->GetMapperID()==mitk::BaseRenderer::Standard2D) return m_Method=="Circle" || m_Method=="Ellipse" || m_Method=="SplinePolygon" || m_Method=="Polygon"; else return false; } // ==========Actions============= void sv4guiContourGroupDataInteractor::AddInitialPoint(mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; mitk::BaseRenderer *renderer = interactionEvent->GetSender(); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; if(m_Method=="Circle") m_Contour=new sv4guiContourCircle(); else if(m_Method=="Ellipse") m_Contour=new sv4guiContourEllipse(); else if(m_Method=="SplinePolygon") m_Contour=new sv4guiContourSplinePolygon(); else if(m_Method=="Polygon") m_Contour=new sv4guiContourPolygon(); else return; m_Contour->SetPathPoint(m_PathPoint); m_Contour->SetSubdivisionType(sv4guiContour::CONSTANT_SPACING); m_Contour->SetSubdivisionSpacing(m_SubdivisionSpacing); mitk::OperationEvent::IncCurrObjectEventId(); // Invoke event to notify listeners that placement of this PF starts now group->InvokeEvent( StartChangingContourEvent() ); int index=group->GetContourIndexByPathPosPoint(m_Contour->GetPathPosPoint()); if(index!=-2) { SetContour(group, index, m_Contour, renderer->GetTimeStep()); } else { for(int i=0;i<m_PathPoints.size();i++) { if(m_PathPoints[i].pos==m_Contour->GetPathPosPoint()) m_Contour->SetTagIndex(i); } index=group->GetInsertingContourIndexByTagIndex(m_Contour->GetTagIndex()); InsertContour(group, m_Contour,index, renderer->GetTimeStep()); } m_Contour->SetFinished(false);//hide center/scaling points if applicable m_ContourIndex=index; mitk::Point3D point = positionEvent->GetPositionInWorld(); m_LastPoint=point; m_Contour->PlaceContour(point); renderer->GetRenderingManager()->RequestUpdateAll(); } void sv4guiContourGroupDataInteractor::MoveCurrentPoint(mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; if(m_Contour==NULL) return; mitk::Point3D point = positionEvent->GetPositionInWorld(); int selectedIndex=m_Contour->GetControlPointSelectedIndex(); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; // group->InvokeEvent( StartInteractionContoureEvent() ); mitk::Vector3D dirVector = point - m_LastPoint; // m_SumVec = m_SumVec + dirVector; mitk::Point3D resultPoint=m_Contour->GetControlPoint(selectedIndex); resultPoint=resultPoint+dirVector; group->SetControlPoint(m_ContourIndex, selectedIndex, point, m_TimeStep); m_LastPoint = point; interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } void sv4guiContourGroupDataInteractor::FinalizeContour( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { // group->Modified(); m_Contour->DeselectControlPoint(); if(m_Contour->GetControlPointNumber()>m_Contour->GetMinControlPointNumber()) { m_Contour->RemoveControlPoint(-1); } m_Contour->SetFinished();//show center/scaling points if applicable m_Contour->SetClosed(); // planarFigure->SetProperty( "initiallyplaced", mitk::BoolProperty::New( true ) ); GetDataNode()->Modified(); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; group->InvokeEvent( EndChangingContourEvent() ); // group->InvokeEvent( StartLoftContourGroupEvent() ); group->InvokeEvent( sv4guiContourChangeEvent() ); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } void sv4guiContourGroupDataInteractor::AppendPoint( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; if(m_Contour==NULL) return; mitk::Point3D point = positionEvent->GetPositionInWorld(); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; // group->InvokeEvent( StartInteractionContoureEvent() ); group->InsertControlPoint(m_ContourIndex, -1, point, m_TimeStep); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } void sv4guiContourGroupDataInteractor::SelectPoint( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(m_Contour==NULL) return; int pointIndex = -2; pointIndex = SearchControlPoint( positionEvent, m_Contour, renderer ); if ( pointIndex !=-2 ) { m_Contour->SetControlPointSelectedIndex(pointIndex); renderer->GetRenderingManager()->RequestUpdateAll(); return; } } void sv4guiContourGroupDataInteractor::DeselectPoint( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; if(m_Contour==NULL) return; m_Contour->DeselectControlPoint(); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } void sv4guiContourGroupDataInteractor::DeleteContour( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(m_Contour){ sv4guiContourOperation* doOp = new sv4guiContourOperation(sv4guiContourOperation::OpREMOVECONTOUR,m_TimeStep, m_Contour,m_ContourIndex); if (m_UndoEnabled) { sv4guiContourOperation *undoOp = new sv4guiContourOperation(sv4guiContourOperation::OpINSERTCONTOUR,m_TimeStep, m_Contour, m_ContourIndex); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(group, doOp, undoOp, "Remove Contour"); m_UndoController->SetOperationEvent(operationEvent); } group->ExecuteOperation(doOp); if ( !m_UndoEnabled ) delete doOp; interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } } void sv4guiContourGroupDataInteractor::RemoveSelectedPoint( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; if(m_Contour==NULL) return; int selectedIndex=m_Contour->GetControlPointSelectedIndex(); if(selectedIndex>-2 &&m_Contour->GetControlPointNumber()>m_Contour->GetMinControlPointNumber() &&m_Contour->IsControlPointRemovable(selectedIndex)) { mitk::OperationEvent::IncCurrObjectEventId(); mitk::Point3D point=m_Contour->GetControlPoint(selectedIndex); sv4guiContourOperation* doOp = new sv4guiContourOperation(sv4guiContourOperation::OpREMOVECONTROLPOINT,m_TimeStep,point,m_ContourIndex,selectedIndex); if (m_UndoEnabled) { sv4guiContourOperation *undoOp = new sv4guiContourOperation(sv4guiContourOperation::OpINSERTCONTROLPOINT,m_TimeStep,point,m_ContourIndex,selectedIndex); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(group, doOp, undoOp, "Remove Control Point"); m_UndoController->SetOperationEvent(operationEvent); } group->ExecuteOperation(doOp); if ( !m_UndoEnabled ) delete doOp; interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } } void sv4guiContourGroupDataInteractor::InitMove(mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>(interactionEvent); if (positionEvent == NULL) return; if (m_Contour==NULL) return; mitk::OperationEvent::IncCurrObjectEventId(); m_LastPoint = positionEvent->GetPositionInWorld(); int selectedIndex=m_Contour->GetControlPointSelectedIndex(); m_PreviousLocation=m_Contour->GetControlPoint(selectedIndex); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group!=NULL) group->InvokeEvent( StartChangingContourEvent() ); } void sv4guiContourGroupDataInteractor::FinishMove(mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>(interactionEvent); if ( positionEvent == NULL ) return; if(m_Contour==NULL) return; int selectedIndex=m_Contour->GetControlPointSelectedIndex(); mitk::Point3D point = m_Contour->GetControlPoint(selectedIndex); sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; group->InvokeEvent(EndChangingContourEvent()); sv4guiContourOperation* doOp = new sv4guiContourOperation(sv4guiContourOperation::OpMOVECONTROLPOINT,m_TimeStep,point,m_ContourIndex,selectedIndex); if (m_UndoEnabled) { sv4guiContourOperation *undoOp = new sv4guiContourOperation(sv4guiContourOperation::OpMOVECONTROLPOINT,m_TimeStep,m_PreviousLocation,m_ContourIndex,selectedIndex); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(group, doOp, undoOp, "Move Control Point"); m_UndoController->SetOperationEvent(operationEvent); } group->ExecuteOperation(doOp); if ( !m_UndoEnabled ) delete doOp; interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); mitk::OperationEvent::IncCurrGroupEventId(); this->NotifyResultReady(); } void sv4guiContourGroupDataInteractor::HidePreviewPoint( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { if(m_Contour==NULL) return; if(m_Contour->IsExtendable()){ m_Contour->HidePreviewControlPoint(); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } } void sv4guiContourGroupDataInteractor::SetPreviewPoint( mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent ) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; if(m_Contour==NULL) return; mitk::Point3D point=positionEvent->GetPositionInWorld(); if(m_Contour->IsExtendable()) { m_Contour->SetPreviewControlPoint(point); interactionEvent->GetSender()->GetRenderingManager()->RequestUpdateAll(); } } void sv4guiContourGroupDataInteractor::InsertPoint(mitk::StateMachineAction*, mitk::InteractionEvent* interactionEvent) { const mitk::InteractionPositionEvent* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>( interactionEvent ); if ( positionEvent == NULL ) return; if(m_Contour==NULL) return; sv4guiContourGroup* group = dynamic_cast<sv4guiContourGroup *>( GetDataNode()->GetData() ); if(group==NULL) return; if(m_Contour->IsExtendable()&&m_Contour->IsPreviewControlPointVisible()) { mitk::BaseRenderer *renderer = interactionEvent->GetSender(); int nextContourPointIndex = SearchCoutourPoint(positionEvent , m_Contour , renderer ); mitk::Point3D point = m_Contour->GetPreviewControlPoint(); int index=m_Contour->SearchControlPointByContourPoint(nextContourPointIndex); if(index<-1) return; mitk::OperationEvent::IncCurrObjectEventId(); sv4guiContourOperation* doOp = new sv4guiContourOperation(sv4guiContourOperation::OpINSERTCONTROLPOINT,m_TimeStep,point,m_ContourIndex,index); if (m_UndoEnabled) { sv4guiContourOperation *undoOp = new sv4guiContourOperation(sv4guiContourOperation::OpREMOVECONTROLPOINT,m_TimeStep,point,m_ContourIndex,index); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(group, doOp, undoOp, "Insert Control Point"); m_UndoController->SetOperationEvent(operationEvent); } group->ExecuteOperation(doOp); if ( !m_UndoEnabled ) delete doOp; renderer->GetRenderingManager()->RequestUpdateAll(); m_LastPoint = positionEvent->GetPositionInWorld(); int selectedIndex=m_Contour->GetControlPointSelectedIndex(); m_PreviousLocation=m_Contour->GetControlPoint(selectedIndex); } } void sv4guiContourGroupDataInteractor::SetSelectionAccuracy( mitk::ScalarType accuracy ) { m_SelectionAccuracy = accuracy; } mitk::ScalarType sv4guiContourGroupDataInteractor::GetSelectionAccuracy() const { float pointsize=(float)(2*m_SelectionAccuracy); if (GetDataNode()!=NULL) { GetDataNode()->GetFloatProperty("point.3dsize", pointsize); } double accuracy=(double)(pointsize); return accuracy; } void sv4guiContourGroupDataInteractor::SetMinimumPointDistance( mitk::ScalarType minimumDistance ) { m_MinimumPointDistance = minimumDistance; } bool sv4guiContourGroupDataInteractor::IsOn2DView(const mitk::InteractionEvent* interactionEvent) const { mitk::BaseRenderer *renderer = interactionEvent->GetSender(); if(renderer) return renderer->GetMapperID()==mitk::BaseRenderer::Standard2D; else return false; } void sv4guiContourGroupDataInteractor::SetInteraction3D(bool use3D) { m_Interaction3D=use3D; }
33.386275
171
0.68638
[ "vector" ]
62cffe01aeb114edccc4f3d58b7aec4136283535
24,799
cpp
C++
source/lowlevel/brsimplearray.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
115
2015-01-18T17:29:30.000Z
2022-01-30T04:31:48.000Z
source/lowlevel/brsimplearray.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-22T04:53:38.000Z
2015-01-31T13:52:40.000Z
source/lowlevel/brsimplearray.cpp
Olde-Skuul/burgerlib
80848a4dfa17c5c05095ecea14a9bd87f86dfb9d
[ "Zlib" ]
9
2015-01-23T20:06:46.000Z
2020-05-20T16:06:00.000Z
/*************************************** intrinsic<T> compatible array template Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com> It is released under an MIT Open Source license. Please see LICENSE for license details. Yes, you can use it in a commercial title without paying anything, just give me a credit. Please? It's not like I'm asking you for money! ***************************************/ #include "brsimplearray.h" #include "brmemoryfunctions.h" #include "brdebug.h" /*! ************************************ \class Burger::SimpleArrayBase \brief Base class for SimpleArray This class will perform most work for the SimpleArray template class \sa SimpleArray or ClassArray ***************************************/ /*! ************************************ \fn Burger::SimpleArrayBase::SimpleArrayBase(uintptr_t uChunkSize) \brief Default constructor. Initializes the array to contain no data and have no members and set to a specific chunk size. \param uChunkSize Size in bytes of each element in the array \sa SimpleArrayBase(uintptr_t,uintptr_t) or SimpleArrayBase(const SimpleArrayBase&) ***************************************/ /*! ************************************ \brief Default constructor with a starting array and chunk size Initializes the array to contain uDefault number of uninitialized members. \note If the initial buffer allocation fails, the array size will be set to zero. \param uChunkSize Size of each data chunk \param uDefault Number of members to create the array with. Zero will generate an empty array. \sa SimpleArrayBase(uintptr_t) or SimpleArrayBase(const SimpleArrayBase&) ***************************************/ Burger::SimpleArrayBase::SimpleArrayBase(uintptr_t uChunkSize,uintptr_t uDefault) : m_uSize(uDefault), m_uBufferSize(uDefault) { // Minimum chunk size of 1 byte per entry if (!uChunkSize) { uChunkSize = 1; } m_uChunkSize = uChunkSize; // Anything? void *pData = NULL; if (uDefault) { // Get the default buffer and die if failed in debug pData = Alloc(uChunkSize * uDefault); if (!pData) { // Set the size to empty uDefault = 0; } } m_uBufferSize = uDefault; m_uSize = uDefault; m_pData = pData; } /*! ************************************ \brief Default constructor for making a copy of another SimpleArrayBase Initializes the array to contain a copy of another SimpleArrayBase. \param rData Reference to a matching SimpleArrayBase type \sa SimpleArrayBase(uintptr_t) or SimpleArrayBase(uintptr_t,uintptr_t) ***************************************/ Burger::SimpleArrayBase::SimpleArrayBase(const SimpleArrayBase &rData) : m_pData(NULL) { uintptr_t uCount = rData.m_uSize; m_uSize = uCount; m_uBufferSize = uCount; uintptr_t uChunkSize = rData.m_uChunkSize; m_uChunkSize = uChunkSize; if (uCount) { m_pData = AllocCopy(rData.m_pData,uChunkSize * uCount); if (!m_pData) { m_uBufferSize = 0; m_uSize = 0; Debug::Fatal("SimpleArrayBase(const SimpleArrayBase &) allocation failure"); } } } /*! ************************************ \fn Burger::SimpleArrayBase::~SimpleArrayBase() \brief Standard destructor Releases the memory buffer with a call to Free(const void *) \sa SimpleArrayBase(uintptr_t), SimpleArrayBase(uintptr_t,uintptr_t) or SimpleArrayBase(const SimpleArrayBase&) ***************************************/ Burger::SimpleArrayBase::~SimpleArrayBase(void) { clear(); } /*! ************************************ \brief Copy an array into this one If the copy is not itself, call clear() to erase the contents of this class and make a duplicate of every entry in the rData class into this one. \param rData Reference to a matching SimpleArray type \return *this \sa resize(uintptr_t) or reserve(uintptr_t) ***************************************/ Burger::SimpleArrayBase & Burger::SimpleArrayBase::operator=(const SimpleArrayBase &rData) { // Copying over itself? if (&rData!=this) { // Dispose of the contents clear(); // Get the size to copy uintptr_t uCount = rData.m_uSize; uintptr_t uChunkSize = rData.m_uChunkSize; // Chunk size COULD change, bad idea, however, support // it to prevent subtle bugs m_uChunkSize = uChunkSize; if (uCount) { // Set the new size m_uSize = uCount; m_uBufferSize = uCount; m_pData = AllocCopy(rData.m_pData,uChunkSize * uCount); if (!m_pData) { m_uSize = 0; m_uBufferSize = 0; Debug::Fatal("SimpleArrayBase::operator=(const SimpleArrayBase &) allocation failure"); } } } return *this; } /*! ************************************ \brief Remove all objects from the array. Dispose of the array and set the size to zero. \sa resize(uintptr_t) or reserve(uintptr_t) ***************************************/ void BURGER_API Burger::SimpleArrayBase::clear(void) { Free(m_pData); m_pData = NULL; m_uBufferSize = 0; m_uSize = 0; } /*! ************************************ \brief Remove an object from the array. Call the destructor on the specific object in the array and then compact the array if needed. \param uIndex Index into the array of the object to remove. \return Zero on success, or non zero on failure \sa resize(uintptr_t) or reserve(uintptr_t) ***************************************/ Burger::eError BURGER_API Burger::SimpleArrayBase::remove_at(uintptr_t uIndex) { eError uResult = kErrorInvalidParameter; uintptr_t uSize = m_uSize; if (uIndex < uSize) { if (uSize == 1) { // Nuke it clear(); } else { --uSize; m_uSize = uSize; uintptr_t uChunkSize = m_uChunkSize; // Calculate the base pointer to the array uint8_t *pMark = static_cast<uint8_t *>(m_pData) + (uIndex*uChunkSize); // Copy over the single entry MemoryMove(pMark,pMark+uChunkSize,uChunkSize * (uSize - uIndex)); } uResult = kErrorNone; } return uResult; } /*! ************************************ \brief Resize the valid entry count of the array. If uNewSize is zero, erase all data. If uNewSize increases the size of the array, increase the buffer size if necessary. If the size is smaller than the existing array, truncate the array. In some cases, the buffer size will be reduced if the new size is substantially smaller. \param uNewSize Number of valid objects the new array will contain. \return Zero on success, or non zero on failure \sa clear(void) or reserve(uintptr_t) ***************************************/ Burger::eError BURGER_API Burger::SimpleArrayBase::resize(uintptr_t uNewSize) { eError uResult; if (!uNewSize) { clear(); uResult = kErrorNone; } else { uResult = reserve(uNewSize); if (uResult== kErrorNone) { // If no error, set the new size m_uSize = uNewSize; } } return uResult; } /*! ************************************ \brief Resize the memory used by the array. This function sets the size of the master buffer which can exceed the number of valid entries in the array. This is a performance function in that if it's known at runtime what is the maximum memory requirements for this array, it can be pre-allocated and all functions can use this buffer until the class is disposed of without any intermediate memory allocation calls. If the reservation size is zero, the array is released. The array size will be adjusted to the match the buffer size. \param uNewBufferSize Size in elements of the memory buffer. \return Zero on success, or non zero on failure \sa clear(void) or resize(uintptr_t) ***************************************/ Burger::eError BURGER_API Burger::SimpleArrayBase::reserve(uintptr_t uNewBufferSize) { eError uResult = kErrorNone; // Resize the buffer. if (!uNewBufferSize) { clear(); } else { // If the reservation size truncates the buffer, update the size if (m_uSize>uNewBufferSize) { m_uSize = uNewBufferSize; } void *pData = Realloc(m_pData,m_uChunkSize * uNewBufferSize); // If a bad pointer, return the error if (!pData) { uResult = kErrorOutOfMemory; uNewBufferSize = 0; m_uSize = 0; } m_uBufferSize = uNewBufferSize; m_pData = pData; } return uResult; } /*! ************************************ \brief Append an array of object to this array. Given a base pointer and an object count, iterate over the objects and copy them to the end of this array. This function will increase the size of the buffer if needed. \param pData Pointer to the first element in an array of objects \param uCount Number of elements in the array \return Zero on success, or non zero on failure \sa resize(uintptr_t) or reserve(uintptr_t) ***************************************/ Burger::eError BURGER_API Burger::SimpleArrayBase::append(const void *pData,uintptr_t uCount) { eError uResult = kErrorNone; // No new entries? if (uCount) { // Expand the buffer by the entry count uintptr_t uSize = m_uSize; uResult = resize(uSize + uCount); // Success? if (uResult== kErrorNone) { // Copy in the new entries uintptr_t uChunkSize = m_uChunkSize; MemoryCopy(static_cast<uint8_t*>(m_pData)+(uSize*uChunkSize),pData,uCount*uChunkSize); } } return uResult; } /*! ************************************ \class Burger::SimpleArray \brief Template for creating arrays of intrinsic objects This template class will dynamically allocate memory as needed. Since it's assuming the data is of intrinsic values, no initialization or shutdown is performed on the elements. If this behavior is desired, use the ClassArray template instead. While it uses function names that match the class vector<T>, this is a lightweight version which doesn't match 100% due to implementation for performance. \sa ClassArray ***************************************/ /*! ************************************ \fn Burger::SimpleArray::SimpleArray() \brief Default constructor. Initializes the array to contain no data and have no members. \sa SimpleArray(uintptr_t) or SimpleArray(const SimpleArray& rData) ***************************************/ /*! ************************************ \fn Burger::SimpleArray::SimpleArray() \brief Default constructor. Initializes the array to contain no data and have no members. \sa SimpleArray(uintptr_t) or SimpleArray(const SimpleArray&) ***************************************/ /*! ************************************ \fn Burger::SimpleArray::SimpleArray(uintptr_t uDefault) \brief Default constructor with a starting array Initializes the array to contain uDefault number of uninitialized members. \param uDefault Number of members to create the array with. Zero will generate an empty array. \sa SimpleArray() or SimpleArray(const SimpleArray&) ***************************************/ /*! ************************************ \fn T * Burger::SimpleArray::GetPtr(void) \brief Obtain a pointer to the array. Allow direct access to the base pointer to the array. This can be \ref NULL if the array is empty. \return A pointer to the array. \sa GetPtr(void) const or front(void) ***************************************/ /*! ************************************ \fn const T * Burger::SimpleArray::GetPtr(void) const \brief Obtain a constant pointer to the array. Allow direct access to the base pointer to the array. This can be \ref NULL if the array is empty. \return A constant pointer to the array. \sa GetPtr(void) or front(void) const ***************************************/ /*! ************************************ \fn T & Burger::SimpleArray::operator[](uintptr_t uIndex) \brief Obtain a reference to an item in the array. Index into the array and return a reference to the object. \note In \ref _DEBUG builds, this will \ref BURGER_ASSERT() if the uIndex value exceeds the size of the number of valid entries in the array. \param uIndex Object number in the array to retrieve a reference to. \return A reference of the object indexed. \sa operator[](uintptr_t) const or GetIndexedItem(uintptr_t) ***************************************/ /*! ************************************ \fn const T & Burger::SimpleArray::operator[](uintptr_t uIndex) const \brief Obtain a constant reference to an item in the array. Index into the array and return a constant reference to the object. \note In \ref _DEBUG builds, this will \ref BURGER_ASSERT() if the uIndex value exceeds the size of the number of valid entries in the array. \param uIndex Object number in the array to retrieve a constant reference to. \return A constant reference of the object indexed. \sa operator[](uintptr_t) or GetIndexedItem(uintptr_t) const ***************************************/ /*! ************************************ \fn T & Burger::SimpleArray::GetIndexedItem(uintptr_t uIndex) \brief Obtain a reference to an item in the array. Index into the array and return a reference to the object. \note In \ref _DEBUG builds, this will \ref BURGER_ASSERT() if the uIndex value exceeds the size of the number of valid entries in the array. \param uIndex Object number in the array to retrieve a reference to. \return A reference of the object indexed. \sa operator[](uintptr_t) or GetIndexedItem(uintptr_t) const ***************************************/ /*! ************************************ \fn const T & Burger::SimpleArray::GetIndexedItem(uintptr_t uIndex) const \brief Obtain a constant reference to an item in the array. Index into the array and return a constant reference to the object. \note In \ref _DEBUG builds, this will \ref BURGER_ASSERT() if the uIndex value exceeds the size of the number of valid entries in the array. \param uIndex Object number in the array to retrieve a constant reference to. \return A constant reference of the object indexed. \sa operator[](uintptr_t) const or GetIndexedItem(uintptr_t) ***************************************/ /*! ************************************ \fn uintptr_t Burger::SimpleArray::capacity(void) const \brief Return the number of objects the current buffer could hold. The buffer size may exceed the number of valid objects, so that if the array grew, memory allocations won't be needed. This function will return the size of the true buffer. \return Number of objects the currently allocated buffer can hold. \sa size(void) const ***************************************/ /*! ************************************ \fn uintptr_t Burger::SimpleArray::max_size(void) \brief Return the maximum number of objects the buffer could ever hold. Given the maximum possible size of memory in the machine, return the theoretical maximum number of objects the buffer could hold. \return Number of objects the buffer could possibly hold. \sa capacity(void) const ***************************************/ /*! ************************************ \fn uintptr_t Burger::SimpleArray::size(void) const \brief Return the valid number of objects in the array. This value is less than or equal to the buffer size. \return Number of valid objects in the array. \sa max_size(void) const or empty(void) const ***************************************/ /*! ************************************ \fn uint_t Burger::SimpleArray::empty(void) const \brief Return \ref TRUE if the array is empty. If there is no valid data in the array, return \ref TRUE. \return \ref TRUE if the valid object count is zero, \ref FALSE if there are valid objects \sa size(void) const ***************************************/ /*! ************************************ \fn T & Burger::SimpleArray::front(void) \brief Obtain a reference to first item in the array. Return a reference to the first object. \return A reference to the first object in the array \sa back(void) or front(void) const ***************************************/ /*! ************************************ \fn const T & Burger::SimpleArray::front(void) const \brief Obtain a constant reference to first item in the array. Return a constant reference to the first object. \return A constant reference to the first object in the array \sa back(void) const or front(void) ***************************************/ /*! ************************************ \fn T & Burger::SimpleArray::back(void) \brief Obtain a reference to last item in the array. Return a reference to the last object. \return A reference to the last object in the array \sa front(void) or back(void) const ***************************************/ /*! ************************************ \fn const T & Burger::SimpleArray::back(void) const \brief Obtain a constant reference to last item in the array. Return a constant reference to the last object. \return A constant reference to the last object in the array \sa front(void) const or back(void) ***************************************/ /*! ************************************ \fn Burger::eError Burger::SimpleArray::push_back(T rData) \brief Append an object to the end of the array. Make a copy of the object at the end of the array. If there is no room for the new object, increase the size of the buffer to make room. Buffer size increases are made in groups to reduce memory allocation calls to improve performance. \param rData An instance of the object to copy at the end of the array \return Zero on success, or non zero on failure \sa pop_back(void), insert_at(uintptr_t,T), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn Burger::eError Burger::SimpleArray::pop_back(void) \brief Remove an object from the end of the array. Call the destructor on the last object in the array and reduce the array size by one. \return Zero on success, or non zero on failure \sa push_back(T), remove_at(uintptr_t), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn SimpleArray & Burger::SimpleArray::operator=(const SimpleArray &rData) \brief Copy an array into this one If the copy is not itself, call clear() to erase the contents of this class and make a duplicate of every entry in the rData class into this one. \param rData Reference to a matching SimpleArray type \return *this \sa resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn Burger::eError Burger::SimpleArray::insert_at(uintptr_t uIndex,T rData) \brief Insert an object into the array. Expand the buffer if needed and make a copy of the rData object into the array at the index uIndex. \param uIndex Index into the array for the location of the object to insert. \param rData Reference to the object to copy into the array \return Zero on success, or non zero on failure \sa remove_at(uintptr_t), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn uint_t Burger::SimpleArray::remove(T rData) \brief Find an item and remove it from the array. Given an item, scan the array for the first element found and then remove the item. \note If there are multiple copies of the item in the array, this function only removes the first occurrence, not all copies. \param rData Copy of the item to remove \return \ref TRUE if an item was removed, \ref FALSE if not \sa append(const SimpleArray&), insert_at(uintptr_t,T), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn uint_t Burger::SimpleArray::contains(T rData) const \brief Find an item in the array. Given an item, scan the array for an element that matches the value. \param rData Copy of the item to search for \return \ref TRUE if an item was found, \ref FALSE if not \sa append(const SimpleArray&), insert_at(uintptr_t,T), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn void Burger::SimpleArray::append(const T *pSourceData,uintptr_t uCount) \brief Append an array of object to this array. Given a base pointer and an object count, iterate over the objects and copy them to the end of this array. This function will increase the size of the buffer if needed. \param pSourceData Pointer to the first element in an array of objects \param uCount Number of elements in the array \return Zero on success, or non zero on failure \sa append(const SimpleArray&), insert_at(uintptr_t,T), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \fn void Burger::SimpleArray::append(const SimpleArray& rData) \brief Append an array to this array. Given another array, iterate over the objects contained within and copy them to the end of this array. This function will increase the size of the buffer if needed. \param rData Reference to a like typed SimpleArray to copy from. \return Zero on success, or non zero on failure \sa append(const T *,uintptr_t), resize(uintptr_t) or reserve(uintptr_t) ***************************************/ /*! ************************************ \typedef Burger::SimpleArray::iterator \brief STL compatible iterator Iterator object for using functions in &lt;algorithm&gt; \sa const_iterator, value_type, begin(void) or end(void) ***************************************/ /*! ************************************ \typedef Burger::SimpleArray::const_iterator \brief STL compatible iterator Constant iterator object for using functions in &lt;algorithm&gt; \sa iterator, value_type, begin(void) const or end(void) const ***************************************/ /*! ************************************ \typedef Burger::SimpleArray::value_type \brief STL compatible type declaration Type declarator to use in functions in &lt;algorithm&gt;. It's used to create variables of T by using this typedef in the class. \sa iterator or const_iterator ***************************************/ /*! ************************************ \fn Burger::SimpleArray::iterator Burger::SimpleArray::begin(void) \brief Iterator for the start of the array. STL compatible iterator for the start of the array. \return Iterator for starting a traversal of the array. \sa end(void) or begin(void) const ***************************************/ /*! ************************************ \fn Burger::SimpleArray::iterator Burger::SimpleArray::end(void) \brief Iterator for the end of the array. STL compatible iterator for the end of the array. \return Iterator for ending a traversal of the array. \sa begin(void) or end(void) const ***************************************/ /*! ************************************ \fn Burger::SimpleArray::const_iterator Burger::SimpleArray::begin(void) const \brief Constant iterator for the start of the array. STL compatible constant iterator for the start of the array. \return Constant iterator for starting a traversal of the array. \sa end(void) const or begin(void) ***************************************/ /*! ************************************ \fn Burger::SimpleArray::const_iterator Burger::SimpleArray::end(void) const \brief Constant iterator for the end of the array. STL compatible constant iterator for the end of the array. \return Constant iterator for ending a traversal of the array. \sa begin(void) const or end(void) ***************************************/ /*! ************************************ \fn Burger::SimpleArray::const_iterator Burger::SimpleArray::cbegin(void) const \brief Constant iterator for the start of the array. STL compatible constant iterator for the start of the array. \return Constant iterator for starting a traversal of the array. \sa end(void) const or begin(void) ***************************************/ /*! ************************************ \fn Burger::SimpleArray::const_iterator Burger::SimpleArray::cend(void) const \brief Constant iterator for the end of the array. STL compatible constant iterator for the end of the array. \return Constant iterator for ending a traversal of the array. \sa begin(void) const or end(void) ***************************************/ /*! ************************************ \fn Burger::eError Burger::SimpleArray::erase(const_iterator it) \brief Remove an entry from the array using an iterator as the index Using an iterator index, delete an entry in the array. Note, this will change the end() value in an index \param it Iterator index into an array \return Zero on success, or non zero on failure \sa remove_at(uintptr_t) ***************************************/
28.735805
112
0.631356
[ "object", "vector" ]
62d19f2c994f9f61e36e5609567a50ed0c92eb3a
14,718
cpp
C++
src/stringtrie.cpp
lcsfrey/Data_Structures
2fd97e1d93cb7fe61a761b032a06b9828c84e394
[ "MIT" ]
null
null
null
src/stringtrie.cpp
lcsfrey/Data_Structures
2fd97e1d93cb7fe61a761b032a06b9828c84e394
[ "MIT" ]
null
null
null
src/stringtrie.cpp
lcsfrey/Data_Structures
2fd97e1d93cb7fe61a761b032a06b9828c84e394
[ "MIT" ]
null
null
null
/************************************************************************************ ** ** ** MIT License ** ** ** ** Copyright (c) 2017 Lucas Frey ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining ** ** a copy of this software and associated documentation files (the "Software"), ** ** to deal in the Software without restriction, including without limitation ** ** the rights to use, copy, modify, merge, publish, distribute, sublicense, ** ** and/or sell copies of the Software, and to permit persons to whom the ** ** Software is furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included ** ** in all copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ** ** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ** ** ************************************************************************************/ #include "../include/stringtrie.h" #include <vector> #include <queue> #include <map> #include <utility> #include <string> #include <algorithm> #include <fstream> #include <chrono> #include <iomanip> StringTrieNode::StringTrieNode(const char &input_char) : data(input_char), is_a_word(false), parent(nullptr), m_paths() {} StringTrieNode::~StringTrieNode() {} void StringTrie::removeSubTrie(StringTrieNode* current) { for (std::pair<const char, StringTrieNode*> &pair : current->m_paths) removeSubTrie(pair.second); if (current->is_a_word) { number_of_total_words -= m_record->getNumberOccurences(current); number_of_unique_words--; m_record->removeWord(current); } if (current != head) current->parent->m_paths.erase(current->data); delete current; } StringTrie::StringTrie() { head = new StringTrieNode('\0'); m_record = new StringRecord(); } StringTrie::~StringTrie() { removeSubTrie(head); } void StringTrie::resetTrie() { removeSubTrie(head); delete m_record; head = new StringTrieNode('\0'); m_record = new StringRecord(); number_of_total_words = 0; number_of_unique_words = 0; } void StringTrie::addWord(const std::string &word) { if (word == "" || word == " ") return; StringTrieNode* current_node = head; const char* c_string_word = word.c_str(); for (int i = 0, length = word.length(); i < length; i++) { char key_char = tolower(c_string_word[i]); if (!current_node->hasSuffixNode(key_char)) { current_node->m_paths[key_char] = new StringTrieNode(key_char); current_node->m_paths[key_char]->parent = current_node; } current_node = current_node->m_paths[key_char]; } if (!current_node->is_a_word) number_of_unique_words +=1; current_node->is_a_word = true; number_of_total_words += 1; m_record->addWord(current_node); } bool StringTrie::contains(const std::string &word) { if (word.length() == 0 || this->getNumberTotalWords() == 0) return false; StringTrieNode* current_node = head; const char* c_string_word = word.c_str(); for (int i = 0, length = word.length(); i < length; i++) { char key_char = tolower(c_string_word[i]); current_node = current_node->getSuffixNode(key_char); if (current_node == nullptr) return false; } if (current_node->is_a_word) return true; else return false; } // void StringTrie::remove(const std::string &word) { StringTrieNode* current_node = head; const char* c_string_word = word.c_str(); // find node containing final character of string for (int i = 0, length = word.length(); i < length; i++) { char key_char = tolower(c_string_word[i]); current_node = current_node->getSuffixNode(key_char); if (current_node == nullptr) { printf("%s is not a word in the trie\n", c_string_word); return; } } current_node->is_a_word = false; // delete current node and any parent nodes that have no other child nodes while (current_node != head) { StringTrieNode* parent = current_node->parent; if (current_node->m_paths.size() != 0) return; parent->m_paths.erase(current_node->data); delete current_node; current_node = parent; } } void StringTrie::removeAllWithPrefix(const std::string &prefix) { StringTrieNode* current_node = head; const char* c_string_prefix = prefix.c_str(); for (int i = 0, length = prefix.length(); i < length; i++) { char key_char = tolower(c_string_prefix[i]); current_node = current_node->getSuffixNode(key_char); if (current_node == nullptr) { std::cerr << "ERROR: No words with prefix: " << prefix << std::endl; return; } } removeSubTrie(current_node); } void StringTrie::printAll() const { printAllHelper(head, ""); } // prints all words with a given prefix // input: prefix of words to print void StringTrie::printAllWithPrefix(const std::string &prefix) const { StringTrieNode* current_node = head; const char* c_string_prefix = prefix.c_str(); char key_char = '\0'; for (int i = 0, length = prefix.length(); i < length; i++) { key_char = tolower(c_string_prefix[i]); current_node = current_node->getSuffixNode(key_char); if (current_node == nullptr) { std::cerr << "ERROR: No words with prefix: " << prefix << std::endl; return; } } printAllHelper(current_node, prefix); } void StringTrie::printAllByOccurences() const { printOccurencesInRange(); } void StringTrie::printOccurencesInRange(int upper_limit, int lower_limit) const { std::vector<std::pair<std::string, int>> pairs = m_record->getOrderedWords(this, upper_limit, lower_limit); std::cout << "Rank | Frequency | String" << std::endl << "------|-----------|-------" << std::endl; int i = 1; for (std::pair<std::string, int> &pair : pairs) std::cout << std::setw(5) << i++ << std::setw(2) << "|" << std::setw(10) << pair.second << std::setw(2) << "|" << pair.first << std::endl; } void StringTrie::printTopOccurences(int limit) { std::vector<std::pair<std::string, int>> pairs = m_record->getOrderedWords(this); std::cout << "Rank | Frequency | String" << std::endl << "------|-----------|-------" << std::endl; for (int i = 0; i < limit && i < (int)pairs.size(); i++) std::cout << std::setw(5) << i+1 << std::setw(2) << "|" << std::setw(10) << pairs[i].second << std::setw(2) << "|" << pairs[i].first << std::endl; } void StringTrie::writeToFile(std::string filename) const { std::ofstream outfile(filename); if (!outfile.is_open()) { std::cerr << "ERROR: " << filename << " could not be opened.\n"; return; } outfile << head->m_paths.size() << " " << this->number_of_unique_words << " " << this->number_of_total_words << " "; for (const std::pair<char, StringTrieNode*> &pair : head->m_paths) writeToFileHelper(outfile, pair.second); } void StringTrie::writeToFileHelper(std::ofstream &outfile, const StringTrieNode *current_node) const { outfile << current_node->data << " " << (current_node->is_a_word ? m_record->getNumberOccurences(current_node) : 0) << " " << current_node->m_paths.size() << " "; for (const std::pair<char, StringTrieNode*> &pair : current_node->m_paths) writeToFileHelper(outfile, pair.second); } void StringTrie::readFromFile(std::string filename) { std::ifstream infile(filename); if (!infile.is_open()) { std::cerr << "ERROR: " << filename << " could not be opened.\n"; return; } int current_size = 0; infile >> current_size >> this->number_of_unique_words >> this->number_of_total_words; for (int i = 0; i < current_size; i++) readFromFileHelper(infile, head); } void StringTrie::readFromFileHelper(std::ifstream &infile, StringTrieNode *current_node) const { char current_char, current_frequency, current_size; infile >> current_char >> current_frequency >> current_size; if (!current_node->hasSuffixNode(current_char)) { current_node->m_paths[current_char] = new StringTrieNode(current_char); current_node->m_paths[current_char]->parent = current_node; } if (current_frequency > 0) { current_node->m_paths[current_char]->is_a_word = true; m_record->addWord(current_node->m_paths[current_char], current_frequency); } for (int i = 0; i < current_size; i++) readFromFileHelper(infile, current_node->m_paths[current_char]); } // prints all words in subtree, // word is built up one character at a time with each rescursive call void StringTrie::printAllHelper(StringTrieNode* current, std::string word) const { if (current->is_a_word) printf("%s\n", word); for (const auto& t_pair : current->m_paths) printAllHelper(t_pair.second, word + t_pair.first); } int StringTrie::getNumberTotalWords() const { return number_of_total_words; } int StringTrie::getNumberUniqueWords() const { return number_of_unique_words; } int StringTrie::getNumberOccurences(const std::string &word) { StringTrieNode* word_node = getNode(word); if (word_node != nullptr) return m_record->getNumberOccurences(word_node); else return 0; } std::string StringTrie::getLongestWord() const { int length = 0; StringTrieNode* final_node = head; findLongestWord(head, 0, length, final_node); return buildStringFromFinalNode(final_node); } // performs breadth first search through the trie // returns the length of the shortest word in trie int StringTrie::getLengthOfShortestWord() const { std::queue<StringTrieNode*> possible_words; StringTrieNode* current_node; int min_length = 1; int current_level_paths_left = 1; int next_level_paths = 0; possible_words.push(head); while (possible_words.size() > 0) { current_node = possible_words.front(); possible_words.pop(); for (auto iter : current_node->m_paths) { if (iter.second->is_a_word) return min_length; next_level_paths++; possible_words.push(iter.second); } current_level_paths_left--; if (current_level_paths_left == 0) { min_length++; current_level_paths_left = next_level_paths; next_level_paths = 0; } } return 0; } // constructs string character by character std::string StringTrie::buildStringFromFinalNode(const StringTrieNode* current_node) const { if (current_node->data != '\0') return buildStringFromFinalNode(current_node->parent) + current_node->data; else return ""; } // returns a pointer to the StringTrieNode corresponding with the last character // of the string word. If word is not in the trie, a nullptr is returned StringTrieNode *StringTrie::getNode(const std::string &word) { StringTrieNode* current_node = head; const char* c_string_word = word.c_str(); char key_char = '\0'; for (int i = 0, length = word.length(); i < length; i++) { key_char = tolower(c_string_word[i]); current_node = current_node->getSuffixNode(key_char); if (current_node == nullptr) return nullptr; } if (current_node->is_a_word) return current_node; else return nullptr; } // returns longest word in trie // void StringTrie::findLongestWord(StringTrieNode* current_node, int current_length, int &longest_length, StringTrieNode *&longest) const { for (const auto& next_node : current_node->m_paths) findLongestWord(next_node.second, current_length+1, longest_length, longest); if (current_node->is_a_word && current_length > longest_length) { longest_length = current_length; longest = current_node; } } int StringTrie::getLengthOfLongestWord() const { int max_length = 0; StringTrieNode* final_node = head; findLongestWord(head, 0, max_length, final_node); std::string word = buildStringFromFinalNode(final_node); std::cout << word << std::endl; return max_length; } void StringRecord::addWord(const StringTrieNode *current_node, int occurences) { if (m_record.find(current_node) == m_record.end()) m_record[current_node] = occurences; else m_record[current_node] += occurences; } void StringRecord::removeWord(const StringTrieNode *current_node) { m_record.erase(current_node); } int StringRecord::getNumberOccurences(const StringTrieNode *current_node) const { // checks if node is in hash table and returns value if it exists, zero otherwise return m_record.find(current_node) != m_record.end() ? m_record.find(current_node)->second : 0; } std::vector<std::pair<std::string, int>> StringRecord::getOrderedWords( const StringTrie *trie, const int upper_limit, const int lower_limit) { std::vector<std::pair<std::string, int>> words; int word_occurences = 0; std::string word = ""; // add pair to vector if seen more than 40 times for (const std::pair<const StringTrieNode*, int> &pair : m_record) { if (pair.second < lower_limit || pair.second > upper_limit) continue; word = trie->buildStringFromFinalNode(pair.first); word_occurences = pair.second; words.push_back(std::pair<std::string, int>(std::move(word), word_occurences)); } // sort vector by the second value in pair std::sort(words.begin(), words.end(), [](const std::pair<std::string, int> &left, const std::pair<std::string, int> &right) { return left.second > right.second; }); return words; } std::vector<int> StringRecord::getOrderedOccurences() const { std::vector<int> occurences; for (const auto &pair : m_record) occurences.push_back(pair.second); std::sort(occurences.begin(), occurences.end(), std::greater<int>()); return occurences; }
35.810219
109
0.642547
[ "vector" ]
62d58db31175aec84e31d8a23b2f91111e36201a
1,838
hpp
C++
modules/viewer/src/Viewer/gmSubListManager.hpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/viewer/src/Viewer/gmSubListManager.hpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/viewer/src/Viewer/gmSubListManager.hpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#pragma once #include "gmViewItemBase.hpp" #include "gmViewerExport.hpp" #include <mitkDataStorage.h> #include <QQuickItem> namespace gm { namespace ViewItem { class DataStorageListModel; class GM_VIEWER_EXPORT SubListManager: public ViewItemBase { Q_OBJECT Q_PROPERTY(int index READ getIndex WRITE setIndex NOTIFY indexChanged); Q_PROPERTY(gm::ViewItem::DataStorageListModel* model READ getModel NOTIFY modelChanged); Q_PROPERTY(SubListType type READ getType WRITE setType NOTIFY typeChanged); public: enum SubListType { POINTSET, MEASUREMENT, MASKING, IMAGE }; Q_ENUMS(SubListType) private: int m_index; DataStorageListModel* m_dataModel; mitk::DataNode::Pointer m_ParentNode; SubListType m_Type; bool m_Initialized; public: SubListManager(); ~SubListManager(); auto getIndex() -> int; auto setIndex(int index) -> void; auto setType(SubListType type) -> void; auto getType() -> SubListType; auto getModel() -> DataStorageListModel*; public slots: void toggleVisibility(bool checked); void reinitNode(); void globalReinit(); void init(int index); void addNode(); void deleteNode(); void changeNodeName(int index, QString name); signals: void indexChanged(); void modelChanged(); void typeChanged(); void selectionChanged(mitk::DataNode::Pointer node); }; } }
30.131148
100
0.54407
[ "model" ]
62dead32c0cfe53d716343c7bf6723a0c6a0f8a9
749
cpp
C++
gamelib/src/renderdevice.cpp
mateun/game_engine_glfw
2e1b6e7cda7f8aa161d9ebbc8a8a0c6e6560f1c1
[ "MIT" ]
null
null
null
gamelib/src/renderdevice.cpp
mateun/game_engine_glfw
2e1b6e7cda7f8aa161d9ebbc8a8a0c6e6560f1c1
[ "MIT" ]
null
null
null
gamelib/src/renderdevice.cpp
mateun/game_engine_glfw
2e1b6e7cda7f8aa161d9ebbc8a8a0c6e6560f1c1
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "renderdevice.h" #include "rendercommand.h" #include "GL/glew.h" RenderDevice::RenderDevice() { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } void RenderDevice::addRenderCommand(std::shared_ptr<RenderCommand> renderCommand) { _renderCommands.push_back(std::move(renderCommand)); } void RenderDevice::deleteCommandBuffer() { _renderCommands.clear(); } void RenderDevice::clearBackBuffer() { // TODO remove these one-time-startup thingies... const GLfloat bgcol[] = { 0, 0, .0, 1 }; const GLfloat dval = 1; glClearBufferfv(GL_COLOR, 0, bgcol); glClearBufferfv(GL_DEPTH, 0, &dval); } void RenderDevice::render() { clearBackBuffer(); for (const auto& rc : _renderCommands) { rc->execute(); } }
20.243243
83
0.723632
[ "render" ]
62e02d1c25823055d606e19881c40ee1358bdd6b
859
hpp
C++
source/SdlManager.hpp
MatthewScholefield/sentempa
d4b7376e73cbe9e2127d3ba6b61bfbb861ea32b1
[ "MIT" ]
null
null
null
source/SdlManager.hpp
MatthewScholefield/sentempa
d4b7376e73cbe9e2127d3ba6b61bfbb861ea32b1
[ "MIT" ]
null
null
null
source/SdlManager.hpp
MatthewScholefield/sentempa
d4b7376e73cbe9e2127d3ba6b61bfbb861ea32b1
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <functional> #include <SDL2/SDL.h> #include "Vec.hpp" #include "types.hpp" class SdlManager { public: SdlManager() = delete; using KeyChangeFunc = std::function<void(const SDL_Keycode, cbool keyDown)>; using ResizeFunc = std::function<void(cint, cint)>; static void init(); static void destroy(); static Vec2i getSize(); static SDL_Renderer *getSdlRenderer(); static void update(); static bool shouldQuit(); static void onKeyChange(KeyChangeFunc func); static void onResize(ResizeFunc func); private: static cint screenWidth = 640; static cint screenHeight = 480; static bool mustQuit; static std::vector<KeyChangeFunc> keyChangeFuncs; static std::vector<ResizeFunc> resizeFuncs; static SDL_Window *window; static SDL_Renderer *renderer; };
24.542857
80
0.705471
[ "vector" ]
62ea5115f1b0d1d580f1b5ae2c8d1c55892f4dec
11,153
cpp
C++
SightPlusPlus_CMake/src/ml_lib/inference_controller.cpp
patryk-wloch/RealSense-OpenVINO-ObjectRecognition-Tracking
a7b3f21a36f080e447c7ffa7f253dd05810f37ea
[ "Apache-2.0" ]
2
2021-08-20T18:32:32.000Z
2022-03-19T12:01:35.000Z
SightPlusPlus_CMake/src/ml_lib/inference_controller.cpp
patryk-wloch/SightPlusPlus-ComputerVision
a7b3f21a36f080e447c7ffa7f253dd05810f37ea
[ "Apache-2.0" ]
null
null
null
SightPlusPlus_CMake/src/ml_lib/inference_controller.cpp
patryk-wloch/SightPlusPlus-ComputerVision
a7b3f21a36f080e447c7ffa7f253dd05810f37ea
[ "Apache-2.0" ]
null
null
null
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2021 Sight++. All Rights Reserved. // The OpenVINO interface in this file has been loosely inspired by some of the public OpenVINO code samples, // e.g., https://github.com/IntelRealSense/librealsense/tree/master/wrappers/openvino // or https://github.com/openvinotoolkit/openvino/blob/master/inference-engine/samples/hello_classification/main.cpp // and https://github.com/openvinotoolkit/openvino/blob/master/inference-engine/samples/object_detection_sample_ssd/main.cpp // but has been rewritten to account for integration with object tracking and depth measurements, support of // various types of neural networks, utilisation of, and safety with respect to, concurrency, and other crucial aspects. // As such, the final result bears little resemblance to any pre-existent publicly available code. #include "inference_controller.hpp" InferenceController::InferenceController(const std::string& path_to_model,const std::string& config) : path_to_model(path_to_model), config(config) {}; bool InferenceController::start() { try { prepare_queue(); //Initialise OpenVINO Inference Engine InferenceEngine::Core core; //Option for deploying computation on both GPU and CPU if (config == "MULTI") { core.SetConfig({ {"MULTI_DEVICE_PRIORITIES","GPU,CPU"} }, "MULTI"); } SPDLOG_INFO("Loaded Inference Engine Core"); //Read layout of the CNN Network InferenceEngine::CNNNetwork network_main; network_main = core.ReadNetwork(path_to_model); //Get basic info about the network's input input_info = network_main.getInputsInfo(); for (auto& item : input_info) { if (item.second->getInputData()->getTensorDesc().getDims().size() == 4) { input_layer = item.first; auto input_data = item.second; //Set input precision - unsigned 8-bit is chosen as it's compatible with all different architectures input_data->setPrecision(InferenceEngine::Precision::U8); } // Added suppport for hybrid networks with R-FCN/R-CNN input format else if (item.second->getInputData()->getTensorDesc().getDims().size() == 2) { input_info_layer = item.first; item.second->setPrecision(InferenceEngine::Precision::FP32); } } //Get basic info about the network's output InferenceEngine::OutputsDataMap output_info = network_main.getOutputsInfo(); auto output_data = output_info.begin()->second; //Set output precision - 32-bit floating point is chosen as it's supported on all architectures output_data->setPrecision(InferenceEngine::Precision::FP32); output_layer = output_info.begin()->first; //Find a post-processing DetectionOutput layer if exists, from: //https://github.com/openvinotoolkit/openvino/blob/master/inference-engine/samples/object_detection_sample_ssd/main.cpp if (auto ngraph_function = network_main.getFunction()) { for (const auto& out : output_info) { for (const auto& op : ngraph_function->get_ops()) { if (op->get_type_info() == ngraph::op::DetectionOutput::type_info && op->get_friendly_name() == out.second->getName()) { output_layer = out.first; output_data = out.second; } } } } //Create Executable Network instance and load the specified CNN Network exec_network_main = core.LoadNetwork(network_main, config); SPDLOG_INFO("Loaded network {} into Inference Engine", path_to_model); //Create test Inference Request instance; InferenceEngine::InferRequest infer_request = exec_network_main.CreateInferRequest(); //Get information about the inference request input and output auto input_dimensions = infer_request.GetBlob(input_layer)->getTensorDesc().getDims(); auto output_dimensions = infer_request.GetBlob(output_layer)->getTensorDesc().getDims(); channels_count = input_dimensions.at(1); input_height = input_dimensions.at(2); input_width = input_dimensions.at(3); max_proposals = output_dimensions.at(2); object_size = output_dimensions.at(3); SPDLOG_INFO("Prepared test instance of Inference Request"); return true; } catch (const std::exception& e) { SPDLOG_ERROR(e.what()); } } void InferenceController::prepare_queue() { for (unsigned int i = 0; i < MAX_OBJECT_COUNT; i++) { free_ids.push(i); } } void InferenceController::process_frames(const cv::UMat& color_matrix, const cv::UMat& depth_matrix) { try { //Check if live objects overlap, if yes then lock them to prevent restarting tracking information for (auto& object1 : objects) { for (auto& object2 : objects) { if (calculate_overlap(object1.second, object2.second) > 0.2 && object1.second.id != object2.second.id) { object1.second.lock = true; object2.second.lock = true; } } } //Resize input matrix to match network specification cv::Mat img_input; cv::resize(color_matrix, img_input, cv::Size(input_height, input_width)); size_t image_size = (size_t)input_height * (size_t)input_width; infer_request = exec_network_main.CreateInferRequest(); const auto input_blob = infer_request.GetBlob(input_layer); input_buffer = InferenceEngine::as<InferenceEngine::MemoryBlob>(input_blob); //Prepare output BLOB and corresponding buffer space in memory const auto output_blob = infer_request.GetBlob(output_layer); output_buffer = InferenceEngine::as<InferenceEngine::MemoryBlob>(output_blob); //Get write access to input buffer auto input_access_holder = input_buffer->wmap(); unsigned char* input_data = input_access_holder.as<unsigned char*>(); //Fill input buffer with image data for (size_t pixel = 0; pixel < image_size; ++pixel) { for (size_t ch = 0; ch < channels_count; ++ch) { input_data[ch * image_size + pixel] = img_input.at<cv::Vec3b>(pixel)[ch]; } } // Adaptation for R-CNN and R-FCN networks, inspired by // https://github.com/openvinotoolkit/openvino/blob/master/inference-engine/samples/object_detection_sample_ssd/main.cpp if (input_info_layer != "") { const auto input_info_blob = infer_request.GetBlob(input_info_layer); input_info_buffer = InferenceEngine::as<InferenceEngine::MemoryBlob>(input_info_blob); auto input_info_dimensions = input_info_blob->getTensorDesc().getDims().at(1); auto input_info_access_holder = input_info_buffer->wmap(); float* data_info = input_info_access_holder.as<InferenceEngine::PrecisionTrait<InferenceEngine::Precision::FP32>::value_type*>(); data_info[input_info_dimensions + 0] = static_cast<float>(input_info[input_layer]->getTensorDesc().getDims()[2]); data_info[input_info_dimensions + 1] = static_cast<float>(input_info[input_layer]->getTensorDesc().getDims()[3]); for (unsigned int k = 2; k < input_info_dimensions; k++) { data_info[input_info_dimensions + k] = 1.0f; } } //Infer! infer_request.Infer(); // Get read access to output buffer auto output_access_holder = output_buffer->rmap(); const float* detections = output_access_holder.as<InferenceEngine::PrecisionTrait<InferenceEngine::Precision::FP32>::value_type*>(); tbb::concurrent_vector<DetectionResult> candidate_objects; SPDLOG_INFO("PROCESSING OUTPUTS FROM IE"); // Process possible detections concurrently tbb::parallel_for(tbb::blocked_range<int>(0, max_proposals), [&](tbb::blocked_range<int> r) { for (unsigned int detection_index = r.begin(); detection_index < r.end(); detection_index++) { float image_id = detections[detection_index * object_size + 0]; if (image_id < 0) break; int object_label = detections[detection_index * object_size + 1]; float confidence = detections[detection_index * object_size + 2]; int xmin = (int)(detections[detection_index * object_size + 3] * color_matrix.cols); int ymin = (int)(detections[detection_index * object_size + 4] * color_matrix.rows); int xmax = (int)(detections[detection_index * object_size + 5] * color_matrix.cols); int ymax = (int)(detections[detection_index * object_size + 6] * color_matrix.rows); // Currently set to only detect objects with label 1 - human, can be changed as required if (confidence > 0.5 && object_label == 1) { xmin = std::max(0, xmin); ymin = std::max(0, ymin); xmax = std::min(color_matrix.cols, xmax); ymax = std::min(color_matrix.rows, ymax); cv::Rect2d object(xmin, ymin, xmax - xmin, ymax - ymin); cv::UMat object_depth = depth_matrix(object); double distance = DEPTH ? get_distance(object_depth) : 0; DetectionResult current_detection = { object_label, distance, distance, 0, object }; // Add provisional object to the candidate objects vector candidate_objects.push_back(current_detection); } } }); //SPDLOG_INFO("PROCESSED OUTPUTS FROM IE"); std::vector<tracked_object> new_objects; // Check all candidate objects against existent live objects to remove duplicates for (auto & candidate_object : candidate_objects) { bool check_tracking = false; for (auto& tracked_object : objects) { float overlap = calculate_overlap(tracked_object.second, candidate_object); if (overlap > 0.25) { check_tracking = true; // If overlap between 0.35 and 0.7 assume it's the same object, but restart tracker if (tracked_object.second.lock == false && overlap < 0.7) { tracked_object.first = ObjectTracker::create_tracker(); tracked_object.first->init(color_matrix, candidate_object.bounding_box); } tracked_object.second.no_rc_counter = 0; break; } } // If no existent live object found, create a new object if (!check_tracking) { candidate_object.color = get_random_color(); free_ids.try_pop(candidate_object.id); auto tracker = ObjectTracker::create_tracker(); tracker->init(color_matrix, candidate_object.bounding_box); candidate_object.first_bounding_box = candidate_object.bounding_box; new_objects.push_back(tracked_object(tracker, candidate_object)); } } for (auto &object : new_objects) { objects.push_back(object); } //SPDLOG_INFO("PROCESSED CANDIDATE OBJECTS"); } catch (const std::exception& e) { SPDLOG_ERROR(e.what()); abort(); } } float InferenceController::calculate_overlap(DetectionResult& object_tracked, DetectionResult& object_detected) { float intersection_area = (object_tracked.bounding_box & object_detected.bounding_box).area(); float reference_area = object_tracked.bounding_box.area() + object_detected.bounding_box.area() - intersection_area; float overlap1 = ((object_tracked.bounding_box & object_detected.bounding_box) & object_tracked.bounding_box).area() / object_tracked.bounding_box.area(); float overlap2 = ((object_tracked.bounding_box & object_detected.bounding_box) & object_detected.bounding_box).area() / object_detected.bounding_box.area(); float overlap3 = intersection_area / reference_area; return std::max({ overlap1, overlap2, overlap3 }); } cv::Scalar InferenceController::get_random_color() { srand(time(0)); int r = rand() % 255; int g = rand() % 255; int b = rand() % 255; return cv::Scalar(r, g, b, 255); }
37.552189
157
0.72949
[ "object", "vector" ]
62eb04eb83e2c1bd0dafbb4106694855f5898c36
5,971
cpp
C++
example/fixed_point_bare_metal_derivative_example.cpp
BoostGSoC15/fixed-point
d71b4a622ded821a2429d8d857097441c2a10246
[ "BSL-1.0" ]
null
null
null
example/fixed_point_bare_metal_derivative_example.cpp
BoostGSoC15/fixed-point
d71b4a622ded821a2429d8d857097441c2a10246
[ "BSL-1.0" ]
null
null
null
example/fixed_point_bare_metal_derivative_example.cpp
BoostGSoC15/fixed-point
d71b4a622ded821a2429d8d857097441c2a10246
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2015 - 2016. // Copyright Paul A. Bristow 2015 - 2016. // 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) // This file is written to be included from a Quickbook .qbk document. // It can be compiled by the C++ compiler, and run. Any output can // also be added here as comment or included or pasted in elsewhere. // Caution: this file contains Quickbook markup as well as code // and comments: don't change any of the special comment markups! // For additional details, see C.M. Kormanyos, // Real-Time C++: Efficient Object-Oriented and // Template Microcontroller Programming (Springer, Heidelberg, 2013). // in Section 12.7 and Chapter 13. // See http://link.springer.com/chapter/10.1007/978-3-642-34688-0_13 #define USE_BARE_METAL #include <cstdint> #if defined(USE_BARE_METAL) #else #include <iostream> #include <iomanip> #endif // Configure Boost.Fixed_point for a bare-metal system. #if defined(USE_BARE_METAL) #define BOOST_FIXED_POINT_DISABLE_MULTIPRECISION // Do not use Boost.Multiprecision. #define BOOST_FIXED_POINT_DISABLE_IOSTREAM // Do not use I/O streaming. #endif #include <boost/fixed_point/fixed_point.hpp> namespace local { /*! Evaluate first derivative of real_function using a three-point central-difference rule of O(dx^6), for more details \see http://www.boost.org/doc/libs/release/libs/multiprecision/doc/html/boost_multiprecision/tut/floats/fp_eg/nd.html. \tparam RealValueType Type of value, for example, a fixed_point_type. \tparam RealFunctionType Type of parameter @c real function. \param x Value of x. \param dx Step size. \param real_function Real Function. \return First derivative at x value. */ //[fixed_point_derivative_function template<typename RealValueType, typename RealFunctionType> RealValueType first_derivative(const RealValueType& x, const RealValueType& dx, RealFunctionType real_function) { const RealValueType dx2(dx + dx); const RealValueType dx3(dx2 + dx); const RealValueType m1(( real_function(x + dx) - real_function(x - dx)) / 2U); const RealValueType m2(( real_function(x + dx2) - real_function(x - dx2)) / 4U); const RealValueType m3(( real_function(x + dx3) - real_function(x - dx3)) / 6U); const RealValueType fifteen_m1(m1 * 15U); const RealValueType six_m2 (m2 * 6U); const RealValueType ten_dx (dx * 10U); return ((fifteen_m1 - six_m2) + m3) / ten_dx; } //] [/fixed_point_derivative_function] } // namespace local // Implement a tiny simulated subset of the mcal (microcontroller abstraction layer). namespace mcal { namespace wdg { void trigger(); } } // namespace mcal::wdg void mcal::wdg::trigger() { // Simulate a fake watchdog trigger mechanism doing nothing here. } // Declare a global Boolean test variable. bool global_result_is_ok; extern "C" int main() { //[fixed_point_derivative_coeffic typedef boost::fixed_point::negatable<6, -9> fixed_point_type; const fixed_point_type a = fixed_point_type(12) / 10; const fixed_point_type b = fixed_point_type(34) / 10; const fixed_point_type c = fixed_point_type(56) / 10; // Compute the approximate derivative of (a * x^2) + (b * x) + c // evaluated at 1/2, where the approximate values of the coefficients // are: a = 1.2, b = 3.4, and c = 5.6. The numerical tolerance is set // to a value of approximately 1/4. //] [/fixed_point_derivative_coeffic] // See http://link.springer.com/chapter/10.1007/978-3-642-34688-0_12 page 219-220. //[fixed_point_derivative_evalution const fixed_point_type d = local::first_derivative(fixed_point_type(1) / 2, // x fixed_point_type(1) / 4, // Step size dx. [&a, &b, &c](const fixed_point_type& x) -> fixed_point_type { return (((a * x) + b) * x) + c; }); //] [/fixed_point_derivative_evalution] // The expected result is ((2 * a) + b) = (2.4 + 3.4) = 4.6 (exact). // We obtain a fixed-point result of approximately 4.5938. // Verify that the result lies within (4.5 < result < 4.7). // The expected result is 4.6, so this is a wide tolerance. //[fixed_point_verify global_result_is_ok = ((d > (fixed_point_type(45) / 10)) && (d < (fixed_point_type(47) / 10))); //] [/fixed_point_verify] #if defined(USE_BARE_METAL) // We can not print the fixed-point number to the output stream // because I/O-streaming is disabled for fixed-point in this // Boost configuration. #else // But if we could print to the output stream, it might look // similar to the lines below. When attempting to print to // the output stream, however, we would need to add <iostream> // and deactivate #define BOOST_FIXED_POINT_DISABLE_IOSTREAM. std::cout << std::setprecision(std::numeric_limits<fixed_point_type>::digits10) << std::fixed << d << std::endl; #endif // Is the result of taking the derivative of the quadratic function OK? if(global_result_is_ok) { // Here we could take some action in the microcontroller // such as toggle a digital output port to high, indicating // success of the test case. } #if defined(USE_BARE_METAL) // In this bare-metal OS-less system, do not return from main(). for(;;) { mcal::wdg::trigger(); } #endif }
36.631902
124
0.638587
[ "object" ]
62f188377237ada5e060683ff4aa2d9a136afaf8
21,253
cpp
C++
src/resources.cpp
cewbost/dlrts
89a89f71a523adb9db2c9937337ddd7fc54d34ba
[ "MIT" ]
null
null
null
src/resources.cpp
cewbost/dlrts
89a89f71a523adb9db2c9937337ddd7fc54d34ba
[ "MIT" ]
null
null
null
src/resources.cpp
cewbost/dlrts
89a89f71a523adb9db2c9937337ddd7fc54d34ba
[ "MIT" ]
null
null
null
#define RESOURCES_CPP #include <horde3d.h> #include <cstdio> #include <cstring> #include <cmath> #include <cassert> #include <memory> #include "mathutils.h" #include "app.h" #include "interface.h" #include "entities.h" #include "resources.h" namespace Resources { ///procedural generation functions std::pair<int, int> generateGridOH(H3DRes r, double size, int div) { /* this function actually generates a grid with overhang and a stray vertex for expanding the AABB box */ int num_vertices; int num_indices; int total_size; char* data_p; union { unsigned int ui[3]; signed short us[6]; float uf[3]; char uc[12]; }; div += 2; num_vertices = (div + 1) * (div + 1); num_indices = div * div * 6 - 24; std::unique_ptr<double[]> divisions(new double[div + 1]); divisions[0] = 0.0; divisions[1] = 0.0; divisions[2] = size / (double)div; for(int n = 3; n < div - 1; ++n) { divisions[n] = divisions[2] * (n - 1); } divisions[div - 1] = size; divisions[div] = size; total_size = 0; total_size += 20; //header total_size += 8 + 12 * (num_vertices + 1);//vetrex stream total_size += 8 + 6 * (num_vertices + 1); //normal stream total_size += 8 + 8 * (num_vertices + 1); //texcoord stream total_size += 4 + 4 * num_indices; //index stream total_size += 4; //morph targets std::unique_ptr<char[]> temp_data(new char[total_size]); data_p = temp_data.get(); ///generate data: //header std::strncpy(uc, "H3DG", 4); //magic string ui[1] = 5; //version number std::memcpy(data_p, uc, 8); data_p += 8; ui[0] = 0; //number of joints ui[1] = 3; //number of streams ui[2] = num_vertices + 1; //number of vertices std::memcpy(data_p, uc, 12); data_p += 12; //vertex stream ui[0] = 0; ui[1] = 12; std::memcpy(data_p, uc, 8); data_p += 8; for(int n = 0; n < num_vertices; ++n) { uf[0] = divisions[n % (div + 1)]; uf[2] = divisions[n / (div + 1)]; if(n % (div + 1) == 0 || n % (div + 1) == div || n < div + 1 || n >= div * (div + 1)) uf[1] = -0.1; else uf[1] = 0.0; std::memcpy(data_p, uc, 12); data_p += 12; } uf[0] = 0.0; uf[1] = 5.0; uf[2] = 0.0; std::memcpy(data_p, uc, 12); data_p += 12; //normal stream ui[0] = 1; ui[1] = 6; std::memcpy(data_p, uc, 8); data_p += 8; for(int n = 0; n < num_vertices; ++n) { if(n % (div + 1) == 0 || n % (div + 1) == div || n < div + 1 || n >= div * (div + 1)) { us[1] = 0; if(n % (div + 1) == 0) us[0] = 0x8000; else if(n % (div + 1) == div) us[0] = 0x7fff; if(n < div + 1) us[2] = 0x8000; else if(n >= div * (div + 1)) us[2] = 0x7fff; } else { us[0] = 0; us[1] = 0x7fff; us[2] = 0; } std::memcpy(data_p, uc, 6); data_p += 6; } us[0] = 0; us[1] = 0x7fff; us[2] = 0; std::memcpy(data_p, uc, 6); data_p += 6; //texcoord stream ui[0] = 6; ui[1] = 8; std::memcpy(data_p, uc, 8); data_p += 8; for(int n = 0; n < num_vertices; ++n) { uf[0] = divisions[n % (div + 1)] / size; uf[1] = divisions[n / (div + 1)] / size; std::memcpy(data_p, uc, 8); data_p += 8; } uf[0] = 0.0; uf[1] = 0.0; std::memcpy(data_p, uc, 8); data_p += 8; //indices ui[0] = num_indices; std::memcpy(data_p, uc, 4); data_p += 4; auto add_indices = [&ui, div, &uc, &data_p](int n) { ui[0] = n + div + 1 + n / div; ui[1] = n + div + 2 + n / div; ui[2] = n + 1 + n / div; std::memcpy(data_p, uc, 12); data_p += 12; ui[0] = n + div + 1 + n / div; ui[1] = n + 1 + n / div; ui[2] = n + n / div; std::memcpy(data_p, uc, 12); data_p += 12; }; for(int n = 1; n < div - 1; ++n) add_indices(n); for(int n = div; n < div * (div - 1); ++n) add_indices(n); for(int n = div * (div - 1) + 1; n < div * div - 1; ++n) add_indices(n); //morph targets ui[0] = 0; std::memcpy(data_p, uc, 4); data_p += 4; ///data generated h3dUnloadResource(r); h3dLoadResource(r, temp_data.get(), total_size); data_p = nullptr; return std::make_pair(num_vertices + 1, num_indices); } std::pair<int, int> generateGrid(H3DRes r, double size, int div) { /* this function actually generates a grid with overhang and a stray vertex for expanding the AABB box */ int num_vertices; int num_indices; int total_size; char* data_p; union { unsigned int ui[3]; signed short us[6]; float uf[3]; char uc[12]; }; num_vertices = (div + 1) * (div + 1); num_indices = div * div * 6; std::unique_ptr<double[]> divisions(new double[div + 1]); divisions[0] = 0.0; divisions[1] = size / (double)div; for(int n = 2; n < div; ++n) { divisions[n] = divisions[1] * n; } divisions[div] = size; total_size = 0; total_size += 20; //header total_size += 8 + 12 * (num_vertices + 1);//vetrex stream total_size += 8 + 6 * (num_vertices + 1); //normal stream total_size += 8 + 8 * (num_vertices + 1); //texcoord stream total_size += 4 + 4 * num_indices; //index stream total_size += 4; //morph targets std::unique_ptr<char[]> temp_data(new char[total_size]); data_p = temp_data.get(); ///generate data: //header std::strncpy(uc, "H3DG", 4); //magic string ui[1] = 5; //version number std::memcpy(data_p, uc, 8); data_p += 8; ui[0] = 0; //number of joints ui[1] = 3; //number of streams ui[2] = num_vertices + 1; //number of vertices std::memcpy(data_p, uc, 12); data_p += 12; //vertex stream ui[0] = 0; ui[1] = 12; std::memcpy(data_p, uc, 8); data_p += 8; for(int n = 0; n < num_vertices; ++n) { uf[0] = divisions[n % (div + 1)]; uf[1] = 0.0; uf[2] = divisions[n / (div + 1)]; std::memcpy(data_p, uc, 12); data_p += 12; } uf[0] = 0.0; uf[1] = 5.0; uf[2] = 0.0; std::memcpy(data_p, uc, 12); data_p += 12; //normal stream ui[0] = 1; ui[1] = 6; std::memcpy(data_p, uc, 8); data_p += 8; for(int n = 0; n < num_vertices; ++n) { us[0] = 0; us[1] = 0x7fff; us[2] = 0; std::memcpy(data_p, uc, 6); data_p += 6; } us[0] = 0; us[1] = 0x7fff; us[2] = 0; std::memcpy(data_p, uc, 6); data_p += 6; //texcoord stream ui[0] = 6; ui[1] = 8; std::memcpy(data_p, uc, 8); data_p += 8; for(int n = 0; n < num_vertices; ++n) { uf[0] = divisions[n % (div + 1)] / size; uf[1] = divisions[n / (div + 1)] / size; std::memcpy(data_p, uc, 8); data_p += 8; } uf[0] = 0.0; uf[1] = 0.0; std::memcpy(data_p, uc, 8); data_p += 8; //indices ui[0] = num_indices; std::memcpy(data_p, uc, 4); data_p += 4; for(int n = 0; n < num_indices / 6; ++n) { ui[0] = n + div + 1 + n / div; ui[1] = n + div + 2 + n / div; ui[2] = n + 1 + n / div; std::memcpy(data_p, uc, 12); data_p += 12; ui[0] = n + div + 1 + n / div; ui[1] = n + 1 + n / div; ui[2] = n + n / div; std::memcpy(data_p, uc, 12); data_p += 12; } //morph targets ui[0] = 0; std::memcpy(data_p, uc, 4); data_p += 4; ///data generated h3dUnloadResource(r); h3dLoadResource(r, temp_data.get(), total_size); data_p = nullptr; return std::make_pair(num_vertices + 1, num_indices); } std::pair<int, int> generateCube(H3DRes r, double size) { uint32_t num_vertices; uint32_t num_indices; uint32_t total_size; char* data_p; union { unsigned int ui[3]; signed short us[6]; float uf[3]; char uc[12]; }; num_vertices = 24; //6*4 num_indices = 36; //6*6 total_size = 0; total_size += 20; //header total_size += 8 + 12 * num_vertices; //vetrex stream total_size += 8 + 6 * num_vertices; //normal stream total_size += 8 + 8 * num_vertices; //texcoord stream total_size += 4 + 4 * num_indices; //index stream total_size += 4; //morph targets std::unique_ptr<char[]> temp_data(new char[total_size]); data_p = temp_data.get(); ///generate data: //header std::strncpy(uc, "H3DG", 4); //magic string ui[1] = 5; //versoin number std::memcpy(data_p, uc, 8); data_p += 8; ui[0] = 0; //number of joints ui[1] = 3; //number of streams ui[2] = num_vertices; //number of vertices std::memcpy(data_p, uc, 12); data_p += 12; //vertex stream ui[0] = 0; ui[1] = 12; std::memcpy(data_p, uc, 8); data_p += 8; for(uint32_t n = 0; n < num_vertices; ++n) { uf[n / 8] = size * (((n / 4) % 2)? 1 : -1); uf[((n / 8) + 1) % 3] = size * (((n / 2) % 2)? 1 : -1); uf[((n / 8) + 2) % 3] = size * ((((n + 1) / 2) % 2)? 1 : -1); std::memcpy(data_p, uc, 12); data_p += 12; } //normal stream ui[0] = 1; ui[1] = 6; std::memcpy(data_p, uc, 8); data_p += 8; for(uint32_t n = 0; n < num_vertices; n += 4) { us[0] = 0; us[1] = 0; us[2] = 0; us[n / 8] = 0x7fff * (((n / 4) % 2)? 1 : -1); //it loops over four vertices at a time std::memcpy(data_p, uc, 6); data_p += 6; std::memcpy(data_p, uc, 6); data_p += 6; std::memcpy(data_p, uc, 6); data_p += 6; std::memcpy(data_p, uc, 6); data_p += 6; } //texcoord stream ui[0] = 6; ui[1] = 8; std::memcpy(data_p, uc, 8); data_p += 8; for(uint32_t n = 0; n < num_vertices; ++n) { uf[0] = ((n / 2) % 2)? 0. : 1.; uf[1] = (((n + 1) / 2) % 2)? 0. : 1.; std::memcpy(data_p, uc, 8); data_p += 8; } //indices ui[0] = num_indices; std::memcpy(data_p, uc, 4); data_p += 4; for(uint32_t n = 0; n < num_indices / 6; ++n) { ui[0] = n * 4; ui[1] = n * 4 + 1; ui[2] = n * 4 + 2; std::memcpy(data_p, uc, 12); data_p += 12; ui[0] = n * 4 + 2; ui[1] = n * 4 + 3; ui[2] = n * 4; std::memcpy(data_p, uc, 12); data_p += 12; } //morph targets ui[0] = 0; std::memcpy(data_p, uc, 4); data_p += 4; ///data generated h3dUnloadResource(r); h3dLoadResource(r, temp_data.get(), total_size); data_p = nullptr; return std::make_pair(num_vertices, num_indices); } ///general functions void registerAll() { int l = 0; int n = 0; int type = 0; int flags = 0; l = _resources[n].length(); while(l != 0) { if(l >= 2 && _resources[n][0] == '-') { //switch type switch(_resources[n][1]) { case 'g': type = H3DResTypes::Geometry; flags = 0; break; case 'm': type = H3DResTypes::Material; flags = 0; break; case 'c': type = H3DResTypes::Code; flags = 0; break; case 's': type = H3DResTypes::Shader; flags = 0; break; case 't': type = H3DResTypes::Texture; flags = H3DResFlags::NoTexMipmaps; break; case 'p': type = H3DResTypes::Pipeline; flags = 0; break; default: break; } } else { h3dAddResource(type, _resources[n].c_str(), flags); } ++n; l = _resources[n].length(); } } int load(int t, const char* name, bool overwrite) { H3DRes res = h3dFindResource(t, name); if(res == 0) return 2; if(h3dIsResLoaded(res)) { if(overwrite) h3dUnloadResource(res); else return 0; } if(name[0] == '_') { h3dLoadResource(res, nullptr, 0); return 0; } std::string path; std::FILE* f; char* data = nullptr; int size = 0; path = ""; path += AppCtrl::app_path; path += _res_directories[h3dGetResType(res)]; path += name; f = fopen(path.c_str(), "rb"); if(f == nullptr) { std::printf("Unable to open file: %s.\n", path.c_str()); h3dLoadResource(res, nullptr, 0); return 1; } std::fseek(f, 0, SEEK_END); size = (int)std::ftell(f); std::fseek(f, 0, SEEK_SET); data = new char[size]; std::fread(data, 1, size, f); //printf("%i\n", size); if(!h3dLoadResource(res, data, size)) { h3dUnloadResource(res); h3dLoadResource(res, nullptr, 0); } std::fclose(f); delete[] data; return 0; } int loadAll() { H3DRes res; std::string path; std::FILE* f; char* data = nullptr; int size = 0; for(res = h3dQueryUnloadedResource(0); res != 0; res = h3dQueryUnloadedResource(0)) { if(h3dGetResName(res)[0] == '_') { h3dLoadResource(res, nullptr, 0); AppCtrl::dumpMessages(); continue; } path = ""; path += AppCtrl::app_path; path += _res_directories[h3dGetResType(res)]; path += h3dGetResName(res); f = fopen(path.c_str(), "rb"); if(f == nullptr) { std::printf("Unable to open file: %s.\n", path.c_str()); h3dLoadResource(res, nullptr, 0); return 1; } std::fseek(f, 0, SEEK_END); size = (int)std::ftell(f); std::fseek(f, 0, SEEK_SET); data = new char[size]; std::fread(data, 1, size, f); //printf("%i\n", size); if(!h3dLoadResource(res, data, size)) { h3dUnloadResource(res); h3dLoadResource(res, nullptr, 0); } std::fclose(f); delete[] data; AppCtrl::dumpMessages(); } Interface::loadFiles(); AppCtrl::dumpMessages(); return 0; } void unloadAll() { if(!(AppCtrl::flags & AppCtrl::H3DINIT_FLAG)) return; H3DRes r = 0; while(true) { r = h3dGetNextResource(H3DResTypes::Undefined, r); if(r == 0) break; else if(h3dIsResLoaded(r)) h3dUnloadResource(r); } return; } void loadEmptyTexture(H3DRes res, uint16_t x, uint16_t y, uint32_t set) { if(h3dIsResLoaded(res)) h3dUnloadResource(res); char *data, *d_ref; uint32_t size = x * y; data = new char[size * 4 + 54]; d_ref = data; union { char ub[4]; uint32_t ul; uint16_t us[2]; }; //bmp header strncpy(ub, "BM", 2); //magic number memcpy(d_ref, ub, 2); d_ref += 2; ul = size * 4 + 54; //file size memcpy(d_ref, ub, 4); d_ref += 4; ul = 0; //unused memcpy(d_ref, ub, 4); d_ref += 4; ul = 54; //offset of pixel array memcpy(d_ref, ub, 4); d_ref += 4; //dib header ul = 40; //size of dib header memcpy(d_ref, ub, 4); d_ref += 4; ul = x; //image width memcpy(d_ref, ub, 4); d_ref += 4; ul = y; //image height memcpy(d_ref, ub, 4); d_ref += 4; us[0] = 1; us[1] = 32; //number of color planes/color depth memcpy(d_ref, ub, 4); d_ref += 4; ul = 0; //pixel array compression used memcpy(d_ref, ub, 4); d_ref += 4; ul = size * 4; //size of pixel array memcpy(d_ref, ub, 4); d_ref += 4; ul = 1000; //pixels/meter memcpy(d_ref, ub, 4); d_ref += 4; memcpy(d_ref, ub, 4); d_ref += 4; ul = 0; //palette size memcpy(d_ref, ub, 4); d_ref += 4; memcpy(d_ref, ub, 4); d_ref += 4; //pixel array ul = set; for(uint32_t n = 0; n < size; ++n) { memcpy(d_ref, ub, 4); d_ref += 4; } h3dLoadResource(res, data, size * 4 + 54); delete[] data; return; } void writeBWBitmap(uint16_t w, uint16_t h, const char* data) { char *d_ref; uint32_t size = w * h; uint32_t _buff_size = size * 4 + 54; char *buffer = new char[_buff_size]; d_ref = buffer; union { char ub[4]; uint16_t us[2]; uint32_t ul; }; //bmp header strncpy(ub, "BM", 2); //magic number memcpy(d_ref, ub, 2); d_ref += 2; ul = size * 4 + 54; //file size memcpy(d_ref, ub, 4); d_ref += 4; ul = 0; //unused memcpy(d_ref, ub, 4); d_ref += 4; ul = 54; //offset of pixel array memcpy(d_ref, ub, 4); d_ref += 4; //dib header ul = 40; //size of dib header memcpy(d_ref, ub, 4); d_ref += 4; ul = w; //image width memcpy(d_ref, ub, 4); d_ref += 4; ul = h; //image height memcpy(d_ref, ub, 4); d_ref += 4; us[0] = 1; us[1] = 32; //number of color planes/color depth memcpy(d_ref, ub, 4); d_ref += 4; ul = 0; //pixel array compression used memcpy(d_ref, ub, 4); d_ref += 4; ul = size * 4; //size of pixel array memcpy(d_ref, ub, 4); d_ref += 4; ul = 1000; //pixels/meter memcpy(d_ref, ub, 4); d_ref += 4; memcpy(d_ref, ub, 4); d_ref += 4; ul = 0; //palette size memcpy(d_ref, ub, 4); d_ref += 4; memcpy(d_ref, ub, 4); d_ref += 4; //pixel array ub[3] = 255; for(uint32_t n = 0; n < size; ++n) { ub[0] = ub[1] = ub[2] = data[n]; memcpy(d_ref, ub, 4); d_ref += 4; } std::string path = AppCtrl::app_path; path += "colmapout.bmp"; FILE* file = fopen(path.c_str(), "wb"); if(file == nullptr) printf("Unable to write file \"%s\"\n", path.c_str()); else { fwrite(buffer, 1, _buff_size, file); fclose(file); } delete[] buffer; } void create2DMesh(H3DRes res, std::vector<std::pair<float, float>>& vertices, std::vector<int>& indices, int& vert_n, int& idx_n) { assert(indices.size() % 3 == 0); int res_size = 44 + indices.size() * 22; char* buffer = new char[res_size]; char* writer = buffer; union { float uf[3]; int ui[3]; short us[6]; char uc[12]; }; //header + num_joints strcpy(uc, "H3DG"); ui[1] = 5; ui[2] = 0; memcpy(writer, uc, 12); writer += 12; //vertex streams & count ui[0] = 2; ui[1] = indices.size(); memcpy(writer, uc, 8); writer += 8; //vertex positions ui[0] = 0; ui[1] = 12; memcpy(writer, uc, 8); writer += 8; for(auto idx: indices) { uf[0] = vertices[idx].first; uf[2] = vertices[idx].second; uf[1] = 0.; memcpy(writer, uc, 12); writer += 12; } //vertex normals ui[0] = 1; ui[1] = 6; memcpy(writer, uc, 8); writer += 8; for(unsigned n = 0; n < indices.size(); n += 3) { us[0] = 0x7fff; us[1] = 0x7fff; us[2] = 0; memcpy(writer, uc, 6); writer += 6; us[0] = 0; us[1] = 0x7fff; us[2] = 0x7fff; memcpy(writer, uc, 6); writer += 6; us[0] = 0x7fff; us[1] = 0; us[2] = 0x7fff; memcpy(writer, uc, 6); writer += 6; } //indices ui[0] = indices.size(); memcpy(writer, uc, 4); writer += 4; for(unsigned n = 0; n < indices.size(); ++n) { ui[0] = n; memcpy(writer, uc, 4); writer += 4; } //morph targets ui[0] = 0; memcpy(writer, uc, 4); writer += 4; h3dLoadResource(res, buffer, res_size); vert_n = indices.size(); idx_n = indices.size(); delete[] buffer; } }
23.329308
79
0.461205
[ "geometry", "vector" ]
62fd39eff22e58989f3c88152391dec2441eeb0c
11,481
cpp
C++
Source/Composer/Widgets/MainWindow.cpp
dmsovetov/Dreemchest
39255c88943abc69c7fa0710b7ca8486c08260e0
[ "MIT" ]
11
2016-02-18T15:24:49.000Z
2021-01-30T18:26:04.000Z
Source/Composer/Widgets/MainWindow.cpp
dmsovetov/dreemchest
39255c88943abc69c7fa0710b7ca8486c08260e0
[ "MIT" ]
2
2016-05-23T22:48:35.000Z
2017-02-13T16:43:32.000Z
Source/Composer/Widgets/MainWindow.cpp
dmsovetov/dreemchest
39255c88943abc69c7fa0710b7ca8486c08260e0
[ "MIT" ]
3
2016-08-19T13:26:59.000Z
2018-08-03T04:28:14.000Z
/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ #include "MainWindow.h" #include "AssetTree.h" #include "Document.h" #include "SceneTree.h" #include "Inspector/EntityInspector.h" #include "Menu.h" #include "RenderingFrame.h" #include "Output.h" #include "../FileSystem.h" #include "../Project/Project.h" #include "../Editors/AssetEditor.h" #if DEV_USE_DOCK_INDICATOR #include "DockIndicator.h" #endif /* DEV_USE_DOCK_INDICATOR */ DC_BEGIN_COMPOSER namespace Ui { // ** convertKey Platform::Key convertKey( s32 key ) { switch( key ) { case Qt::Key_Back: return Platform::Key::Back; case Qt::Key_Delete: return Platform::Key::Delete; case Qt::Key_Left: return Platform::Key::Left; case Qt::Key_Right: return Platform::Key::Right; case Qt::Key_Up: return Platform::Key::Up; case Qt::Key_Down: return Platform::Key::Down; } return Platform::Key::Total; } // ** MainWindow::MainWindow MainWindow::MainWindow( const QString& title ) : m_assetTree( NULL ), m_activeDocument( NULL ), m_sceneTree( NULL ), m_inspector( NULL ) { #if DEV_USE_DOCK_INDICATOR // Add the dock indicator widget new DockIndicator( this ); #endif /* DEV_USE_DOCK_INDICATOR */ // Setup the share OpenGL format RenderingFrame::setupOpenGLFormat(); // Create the shared OpenGL context m_sharedRenderingContext = new RenderingFrame( NULL, this ); m_sharedRenderingContext->hide(); //setCentralWidget( m_sharedRenderingContext->privateInterface<QRenderingFrame>() ); #ifdef NDEBUG //setWindowState( Qt::WindowMaximized ); resize( 1024, 768 ); #else resize( 1024, 768 ); #endif setUnifiedTitleAndToolBarOnMac( true ); show(); setWindowTitle( title ); } // ** MainWindow::initialize bool MainWindow::initialize( ComposerQPtr composer ) { // Listen for signals connect( composer, SIGNAL(projectOpened(Project*)), this, SLOT(createProjectInterface(Project*)) ); connect( composer, SIGNAL(projectClosed(Project*)), this, SLOT(destroyProjectInterface(Project*)) ); return true; } // ** MainWindow::message void MainWindow::message( const String& text, MessageStatus status ) const { switch( status ) { case MessageInfo: QMessageBox::information( const_cast<MainWindow*>( this ), windowTitle(), text.c_str() ); break; case MessageWarning: QMessageBox::warning( const_cast<MainWindow*>( this ), windowTitle(), text.c_str() ); break; case MessageError: QMessageBox::critical( const_cast<MainWindow*>( this ), windowTitle(), text.c_str() ); break; default: NIMBLE_BREAK; } } // ** MainWindow::message MessageBoxResult MainWindow::messageYesNoCancel( const String& text, const String& info, MessageStatus status ) const { QMessageBox msgBox; msgBox.setText( text.c_str() ); msgBox.setInformativeText( info.c_str() ); msgBox.setStandardButtons( QMessageBox::Yes | QMessageBox::Cancel | QMessageBox::No ); msgBox.setDefaultButton( QMessageBox::Cancel ); switch( status ) { case MessageInfo: msgBox.setIcon( QMessageBox::Information ); break; case MessageWarning: msgBox.setIcon( QMessageBox::Warning ); break; case MessageError: msgBox.setIcon( QMessageBox::Critical ); break; default: NIMBLE_BREAK; } switch( msgBox.exec() ) { case QMessageBox::Yes: return MessageBoxYes; case QMessageBox::No: return MessageBoxNo; } return MessageBoxCancel; } // ** MainWindow::sharedRenderingContext RenderingFrameQPtr MainWindow::sharedRenderingContext( void ) const { return m_sharedRenderingContext; } // ** MainWindow::assetTree AssetTreeQPtr MainWindow::assetTree( void ) const { return m_assetTree; } // ** MainWindow::sceneTree SceneTreeQPtr MainWindow::sceneTree( void ) const { return m_sceneTree; } // ** MainWindow::inspector EntityInspectorQPtr MainWindow::inspector( void ) const { return m_inspector; } // ** MainWindow::addMenu MenuQPtr MainWindow::addMenu( const String& title ) { QMenuBar* bar = menuBar(); Menu* menu = new Menu( bar ); menu->setTitle( QString::fromStdString( title ) ); bar->addMenu( menu ); return menu; } // ** MainWindow::addToolBar ToolBarQPtr MainWindow::addToolBar( void ) { ToolBar* toolBar = new ToolBar( this ); QMainWindow::addToolBar( toolBar ); return toolBar; } // ** MainWindow::addDock QDockWidget* MainWindow::addDock( const QString& name, QWidget* widget, Qt::DockWidgetArea initialDockArea, Qt::DockWidgetAreas allowedDockAreas, QDockWidget* destination ) { QDockWidget* dock = new QDockWidget( name ); dock->setAllowedAreas( allowedDockAreas ); dock->setWidget( widget ); addDockWidget( initialDockArea, dock ); if( destination ) { tabifyDockWidget( dock, destination ); } return dock; } // ** MainWindow::editDocument DocumentQPtr MainWindow::editDocument( Editors::AssetEditorQPtr assetEditor, const FileInfo& asset ) { NIMBLE_BREAK_IF( !assetEditor ); // First lookup the exising document DocumentQPtr existing = findDocument( asset ); if( existing ) { existing->raise(); return existing; } // Create the document instance DocumentQPtr document = new Document( this, assetEditor, QString::fromStdString( asset.fileName() ) ); // Initialize the asset editor with a document if( !assetEditor->initialize( m_project, asset, document ) ) { delete document; return NULL; } addDockWidget( Qt::LeftDockWidgetArea, document ); // Find opened documents of a same type QVector<DocumentQPtr> documents = findDocuments( asset ); if( documents.size() ) { QDockWidget* tabifyTo = documents[0]; tabifyDockWidget( tabifyTo, document ); } // Set the document as active setActiveDocument( document ); // Save created document m_documents.append( document ); return document; } // ** MainWindow::closeDocument bool MainWindow::closeDocument( DocumentQPtr document ) { // Find the document int index = m_documents.indexOf( document ); if( index == -1 ) { NIMBLE_BREAK; return false; } // Ensure that document is saved if( !ensureSaved( document ) ) { return false; } // Change active document setActiveDocument( (m_documents.size() - 1) ? m_documents[index - 1] : NULL ); // Remove the document dock widget removeDockWidget( document ); // Remove from documents m_documents.remove( index ); // Delete document delete document; return true; } // ** MainWindow::findDocument DocumentQPtr MainWindow::findDocument( const FileInfo& asset ) const { foreach( DocumentQPtr document, m_documents ) { if( document->assetEditor()->asset() == asset ) { return document; } } return NULL; } // ** MainWindow::findDocuments QVector<DocumentQPtr> MainWindow::findDocuments( const FileInfo& asset ) const { QVector<DocumentQPtr> documents; foreach( DocumentQPtr document, m_documents ) { if( document->assetEditor()->asset().extension() == asset.extension() ) { documents.append( document ); } } return documents; } // ** MainWindow::activeDocument DocumentQPtr MainWindow::activeDocument( void ) const { return m_activeDocument; } // ** MainWindow::setActiveDocument void MainWindow::setActiveDocument( DocumentQPtr document ) { // This document is already set as active if( m_activeDocument == document ) { return; } // Notify the active document about moving to background. if( m_activeDocument ) { m_activeDocument->assetEditor()->notifyEnterBackground( this ); } // Set new active document m_activeDocument = document; // Notify active document about moving to foreground. if( m_activeDocument ) { // Raise the document dock widget m_activeDocument->raise(); // Notify the asset editor m_activeDocument->assetEditor()->notifyEnterForeground( this ); } } // ** MainWindow::ensureSaved bool MainWindow::ensureSaved( DocumentQPtr document ) const { // Get the attached asset editor. Editors::AssetEditorQPtr assetEditor = document->assetEditor(); // The document has no unsaved changes. if( !assetEditor->hasChanges() ) { return true; } // Show the message box String message = "Do you want to save changes to " + assetEditor->asset().fileName() + "?"; String info = "Your changes will be lost if you don't save them"; MessageBoxResult result = messageYesNoCancel( message, info, MessageWarning ); switch( result ) { case MessageBoxCancel: return false; case MessageBoxYes: assetEditor->save(); case MessageBoxNo: break; } return true; } // ** MainWindow::createProjectInterface void MainWindow::createProjectInterface( Project* project ) { NIMBLE_BREAK_IF( m_assetTree ); NIMBLE_BREAK_IF( m_sceneTree ); NIMBLE_BREAK_IF( m_inspector ); // Get the project from event m_project = project; // Create the asset tree m_assetTree = new AssetTree( m_project, this ); m_assetTree->setModel( m_project->assetFileSystem() ); // Create the scene tree m_sceneTree = new SceneTree( this ); // Create the object inspector m_inspector = new EntityInspector( this ); // Setup status bar statusBar()->show(); // Add dock windows addDock( "Inspector", m_inspector, Qt::RightDockWidgetArea ); addDock( "Assets", m_assetTree, Qt::RightDockWidgetArea ); addDock( "Hierarchy", m_sceneTree, Qt::LeftDockWidgetArea ); addDock( "Output", new Output( this ), Qt::LeftDockWidgetArea ); // Update window caption setWindowTitle( m_project->name().c_str() + QString( " - " + windowTitle() ) ); } // ** MainWindow::destroyProjectInterface void MainWindow::destroyProjectInterface( Project* project ) { m_project = NULL; NIMBLE_BREAK; } } // namespace Ui DC_END_COMPOSER
29.065823
172
0.672764
[ "object" ]
1a0969b4fb495d761d9912091b16a4fb3fe7e0f9
548
cpp
C++
sycl/test/basic_tests/buffer/buffer_for_not_device_copyable.cpp
yuriykoch/llvm
c4ce4f0feb46ec7dd4235fa2709609be06fb2153
[ "Apache-2.0" ]
null
null
null
sycl/test/basic_tests/buffer/buffer_for_not_device_copyable.cpp
yuriykoch/llvm
c4ce4f0feb46ec7dd4235fa2709609be06fb2153
[ "Apache-2.0" ]
4
2019-07-05T08:41:19.000Z
2019-12-13T02:25:06.000Z
sycl/test/basic_tests/buffer/buffer_for_not_device_copyable.cpp
yuriykoch/llvm
c4ce4f0feb46ec7dd4235fa2709609be06fb2153
[ "Apache-2.0" ]
1
2019-07-05T08:33:16.000Z
2019-07-05T08:33:16.000Z
// RUN: %clangxx -fsycl -fsyntax-only -Xclang -verify %s -Xclang -verify-ignore-unexpected=note,warning #include <string> #include <sycl/sycl.hpp> using namespace sycl; int main() { static_assert(is_device_copyable_v<int>); std::vector<int> iv(5, 1); buffer b1(iv.data(), range<1>(5)); static_assert(!is_device_copyable_v<std::string>); std::vector<std::string> sv{"hello", "sycl", "world"}; buffer b2(sv.data(), range<1>(3)); //expected-error@CL/sycl/buffer.hpp:* {{"'std::string' is not a device copyable type"}} return 0; }
27.4
103
0.678832
[ "vector" ]
1a0c03379888bc115e1edbaf6e721c511b327200
13,360
cpp
C++
reactor.cpp
Vitorbnc/VVERSimulator
10be76f7daa32abcb003f92e7fec0eede2ee1eb1
[ "Apache-2.0" ]
12
2020-09-10T06:21:34.000Z
2021-10-19T04:35:23.000Z
reactor.cpp
Vitorbnc/VVERSimulator
10be76f7daa32abcb003f92e7fec0eede2ee1eb1
[ "Apache-2.0" ]
null
null
null
reactor.cpp
Vitorbnc/VVERSimulator
10be76f7daa32abcb003f92e7fec0eede2ee1eb1
[ "Apache-2.0" ]
3
2020-11-04T10:34:15.000Z
2021-06-21T10:26:04.000Z
#include "reactor.h" #include "iostream" #include <chrono> #include <cmath> using namespace std; //Imprimir ou saídas de depuração #define REACTOR_DEBUG false //Reactor::Reactor(pareters p,Inputs i ,Outputs o,Disturbances d,States s, double samplingTime) // :par(p),in(i),out(o),dist(d),vars(s),Ts(samplingTime){} const Reactor::INDEX Reactor::IDX_MAP[IDX_COUNT]={ Reactor::TIME, Reactor::NO_INDEX, // Entradas,1 Reactor::m_in, Reactor::v_R, Reactor::W_heat_PR, Reactor::NO_INDEX, // Dist,5 Reactor::m_out, Reactor::m_SG, Reactor::M_SG, Reactor::T_PC_I, Reactor::T_SG_SW, Reactor::NO_INDEX, //Saídas, 11 Reactor::l_PR, Reactor::p_PR, Reactor::p_SG, Reactor::W_R, Reactor::W_SG, Reactor::NO_INDEX, //Estados, 17 Reactor::N, Reactor::m_PR, Reactor::M_PC, Reactor::T_PC, Reactor::T_PR, Reactor::T_SG }; const string Reactor::IDX_NAME[IDX_COUNT]={ "TIME", "NO_INDEX", "m_in", "v_R", "W_heat_PR", "NO_INDEX", "m_out", "m_SG", "M_SG", "T_PC_I", "T_SG_W", "NO_INDEX", "l_PR", "p_PR", "p_SG", "W_R", "W_SG", "NO_INDEX", "N", "m_PR" "M_PC", "T_PC", "T_PR", "T_SG" }; //Cria uma unidade do reator com parâmetros medidos na Unidade 3 da Planta Paks Reactor::Reactor(double samplingTime): buf(0), //Inicializa com buffer 0 do ring buf Ts(samplingTime), // Tempo de amostragem em segundos T0(60*60*2.5), //2.5h, valor especificado no artigo para a unidade 3 k(0), //Índice atual nFilledBuffers(0), //Buffers preenchidos removeExternalNeutronSource(false), sampleReady(false) { samplingThreadKilled = samplingThreadShouldDie = samplingThreadStarted = false; #if REACTOR_DEBUG cout<<"Criando Reactor"<<endl; #endif for(auto& x: in) x = MatrixXd::Zero(IN_COUNT,BUF_SIZE); for(auto& x: out) x = MatrixXd::Zero(OUT_COUNT,BUF_SIZE); for(auto& x: dist) x = MatrixXd::Zero(DIST_COUNT,BUF_SIZE); for(auto& x: sta) x = MatrixXd::Zero(STATE_COUNT,BUF_SIZE); par= new Parameters{ .Lambda_R=1e-5, //Tempo de geração [s] .S_R=1938.9, //Fluxo de Nêutrons da Fonte Externa [%/s] .c_psi_R=13.75e6, //Razão entre Potência e Fluxo de Nêutrons [W/%] .p_R={-1.223e-4,-5.502e-5,-1.953e-4}, // Coef de reatividade, unidades [1/m^2],[1/m], [1] .cp_PC = 5355, // Calor específico do PC (a 282°C) [J/(kg*K)] .KT_SG = 9.5296e6, //Coef. de Transferência de Calor do PC [J/(K*s)] .W_loss_PC = 2.996e7, //Perda de calor do PC [J/s] .V0_PC = 242, //Volume nominal de água no PC [m^3] .cp_PR = 6873.1,//Calor específico do PR a 325°C [J/(kg*K)] .W_loss_PR = 1.6823e5, //Perda de calor do PR [J/s] .A_PR=4.52, //Seção transversal do PR [m^2] .M_PR=19400, //Massa de água nominal no PR [kg] // const double cp_L_SG, cp_V_SG,W_loss_SG; .cp_L_SG = 3809.9, // Calor específico da água a 260°C [J/(kg*K)] .cp_V_SG = 3635.6, // Calor específico do vapor a 260°C [J/(kg*K)] .E_evap_SG = 1.658e6, //Energia de evaporação no SG a 260°C[J/kg] .W_loss_SG = 1.8932e7, //Perda de calor no SG [J/s] .pt = {28884.78,-258.01,0.63}, //Coeficientes de pressão de saturação de vapor .cphi = {581.2,2.98,-0.00848} //Coeficientes que relacionam densidade da água à temperatura. [kg/m^3],[kg/(m^3K)],[kg/(m^3/K^2)] }; //Inicializa todos os valores como zero //memset(in,0,sizeof(in)); //Entradas e distúrbios devem permanecer constantes até que sofram alterações for(int i=0;i<BUF_COUNT;i++){ //Valores iniciais extraídos da unidade 3 in[i].row(v_R) = MatrixXd::Zero(1,BUF_SIZE); //Rod pos [cm] in[i].row(m_in)= MatrixXd::Constant(1,BUF_SIZE, 1.4222); //PC mass inflow [kg/s] in[i].row(W_heat_PR) = MatrixXd::Constant(1,BUF_SIZE,168); //kW //in[buf].row(ones) = MatrixXd::Ones(); dist[i].row(m_out) = MatrixXd::Constant(1,BUF_SIZE,2.11); //kg/s dist[i].row(m_SG) = MatrixXd::Constant(1,BUF_SIZE,119.31); //kg/s dist[i].row(M_SG) = MatrixXd::Constant(1,BUF_SIZE,34920); //Water and Steam mass Second. Circuit(SC) of SG, kg dist[i].row(T_PC_I) = MatrixXd::Constant(1,BUF_SIZE,258.85); //PC inlet temp, °C dist[i].row(T_SG_SW) = MatrixXd::Constant(1,BUF_SIZE,220.85); //SC inlet water temp, °C } sta[buf](N,0) = 99.3; //neutron flux % sta[buf](M_PC,0) = 200000; //kg //sta[buf](M_PC_inv,0) = 1/20000; computeInitial_m_PR(); sta[buf](T_PC,0) = 281.13;// °C sta[buf](T_PR,0) = 326.57; sta[buf](T_SG,0) = 257.78; //sta[buf](rho,0) = rho_of_v(in[buf](v,0)); out[buf](W_R,0) = 13.75e8; //Potência do reator [W] out[buf](W_SG,0) = 222516666.666; //Potência de saída em cada um dos geradores de vapor //cout<<"Dist m_SG:"<<dist[0](m_SG,0)<<endl; //cout<<"Input one:"<<in[1](ones,100)<<endl; cout<<"par"<<Ts*(1.0/(6873.1*19400))<<endl; startSamplingThread(); //cout<<"After timer"<<endl; } //######################################################################################### Fim do Construtor //Funções que auxiliam no cálculo dos estados //Reatividade do núcleo em função da posição das barras double Reactor::rho_of_v(double v){ //Potencias de 10 convertem de cm para metro return par->p_R[0]*1e-4*v*v +par->p_R[1]*1e-2*v +par->p_R[2]; } //Densidade em função da temperatura double Reactor::phi_of_T(double T){ return par->cphi[0]+par->cphi[1]*T + par->cphi[2]*T*T; } //Pressão em função de temperatura double Reactor::p_of_T(double T){ return (par->pt[0] + par->pt[1]*T + par->pt[2]*T*T)*1e3; } //Precisamos de pelo menos o m_PR inicial para calcular os estados void Reactor::computeInitial_m_PR(){ double dTPCdt = (1/(par->cp_PC*sta[buf](M_PC,0))) \ *(par->cp_PC*in[buf](m_in,0)*(dist[buf](T_PC_I,0)-sta[buf](T_PC)) \ +par->cp_PC*dist[buf](m_out,0)*15 + out[buf](W_R,0) -6*out[buf](W_SG,0) -par->W_loss_SG); sta[buf](m_PR,0)= in[buf](m_in,0) -dist[buf](m_out,0) \ -par->V0_PC*(par->cphi[0]+2*par->cphi[1]*sta[buf](T_PC,0))*dTPCdt; } void Reactor::updateOutputs(){ out[buf](W_R,k) = par->c_psi_R*sta[buf](N,k); out[buf](p_SG,k) = p_of_T(sta[buf](T_SG,k)); out[buf](l_PR,k) = 1/par->A_PR*(sta[buf](M_PC,k)/phi_of_T(sta[buf](T_PC,k))-par->V0_PC); out[buf](p_PR,k) = p_of_T(sta[buf](T_PR,k));//sta[buf](T_PR,k);// out[buf](W_SG,k) = par->KT_SG*(sta[buf](T_PC,k)-sta[buf](T_SG,k)); //cout<<"p_PR:"<<sta[buf](T_SG,k)<<endl; } void Reactor::updateStates(){ // Computa os estados com base no método de Euler sta[buf](N,k+1) = sta[buf](N,k)+ Ts*(1.0/par->Lambda_R*(rho_of_v(in[buf](v_R,k)))*sta[buf](N,k)+(removeExternalNeutronSource?0.0:par->S_R)); sta[buf](M_PC,k+1) = sta[buf](M_PC,k) + Ts*(in[buf](m_in,k) - dist[buf](m_out,k)); sta[buf](T_PC,k+1) = sta[buf](T_PC,k) + Ts*((1.0/(par->cp_PC*sta[buf](M_PC,k))) \ *( par->cp_PC*in[buf](m_in,k)*(dist[buf](T_PC_I,k)-sta[buf](T_PC,k)) \ +par->cp_PC*dist[buf](m_out,k)*15.0 + out[buf](W_R,k) -6.0*out[buf](W_SG,k) -par->W_loss_SG) ); sta[buf](m_PR,k+1) = sta[buf](m_PR,k) + Ts*(sta[buf](M_PC,k)-par->V0_PC\ *(par->cphi[0]+2.0*par->cphi[1]*sta[buf](T_PC,k))*sta[buf](T_PC,k+1)); sta[buf](T_PR,k+1) = sta[buf](T_PR,k) + Ts*(1.0/(par->cp_PR*par->M_PR))\ *(1e3*in[buf](W_heat_PR,k) -par->W_loss_PR -par->cp_PR*sta[buf](m_PR,k+1)*sta[buf](T_PR,k)+\ ((sta[buf](m_PR,k+1)>0.0)?(par->cp_PC*sta[buf](m_PR,k+1)*(15.0+sta[buf](T_PC,k))):(par->cp_PR*sta[buf](m_PR,k+1)*sta[buf](T_PR,k))) ); sta[buf](T_SG,k+1) = sta[buf](T_SG,k) + Ts*(1/(par->cp_L_SG*dist[buf](M_SG,k)))*(par->cp_L_SG*dist[buf](m_SG,k)*dist[buf](T_SG_SW,k) \ -par->cp_V_SG*dist[buf](m_SG,k)*sta[buf](T_SG,k) -dist[buf](m_SG,k)*par->E_evap_SG \ -par->W_loss_SG +out[buf](W_SG,k)); } //Mudar de buffer quando um encher void Reactor::switchBuffers(int oldBuf, int newBuf){ #if REACTOR_DEBUG cout<<"Filled a buffer"<<endl; #endif in[newBuf] = in[oldBuf].col(k).replicate(1,BUF_SIZE); dist[newBuf] = dist[oldBuf].col(k).replicate(1,BUF_SIZE); out[newBuf].col(0) = out[oldBuf].col(k); sta[newBuf].col(0) = sta[oldBuf].col(k); } //Chamado a cada período de amostragem //Roda na sua própria thread void Reactor::onSample(){ while(!samplingThreadShouldDie){ muxInputs.lock(); muxDisturbances.lock(); //updateStates atualiza os próximos estados, e depende de algumas saídas atuais updateOutputs(); updateStates(); muxInputs.unlock(); muxDisturbances.unlock(); //cout<<"k: "<<k<<"\t"<<"Var: "<<out[buf](W_SG,k)<<endl;//sta[buf](N,k)<<endl; #if REACTOR_DEBUG cout<<"k: "<<k<<"\t"<<"N: "<<sta[buf](N,k)<<"\t"<<"W_R:" <<out[buf](W_R,k)<<"\t"<<"T_PC: "<<sta[buf](T_PC,k)<<"\t"<<"T_SG: "<<sta[buf](T_SG,k)<<"\t"<<"W_SG: "<<out[buf](W_SG,k)<<endl; #endif bool reset_k=false; if(k>=BUF_SIZE-2){ int oldBuf = buf; switchBuffers(oldBuf, buf = (buf+1)%BUF_COUNT); nFilledBuffers++; reset_k=true; } sampleReady=true; //testes //if(k==150) in[buf]((int)W_heat_PR,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,200); /* if(k==50) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,0.05); if(k==100) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,0.08); if(k==150) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,0.5); if(k==200) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,0.7); if(k==250) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,0.8); if(k==300) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,0.9); if(k==350) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,1.1); if(k==420) in[buf]((int)v_R,Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-k,1.3); */ //if(k==550) removeExternalNeutronSource = true; //if(k==800) removeExternalNeutronSource = false; this_thread::sleep_for(chrono::milliseconds(int(1000*Ts))); //Incrementar só no final, para que de tempo de pegar o valor if(reset_k) k=0; else k++; } } //################################### Funções para interface com a UI em Qml /* vector<double> Reactor::getInputs(){ //Usando const & para não criar cópias extras const auto& vec = in[buf].col(k); //QVector<type> v( type *primeiro, type *ultimo); //matrix.data() retorna um ponteiro para a localidade de memória do primeiro elemento da matriz return vector<double>(vec.data(),vec.data()+vec.size()); } vector<double> Reactor::getOutputs(){ const auto& v = out[buf].col(k); return vector<double>(v.data(),v.data()+v.size()); //return vector<double>(); } vector<double> Reactor::getStates(){ const auto& v = sta[buf].col(k); return vector<double>(v.data(),v.data()+v.size()); //return vector<double>(); } vector<double> Reactor::getDisturbances(){ const auto& v = dist[buf].col(k); return vector<double>(v.data(),v.data()+v.size()); //return vector<double>(); } */ MatrixXd Reactor::getInputs(){ return in[buf].col(k); } const MatrixXd* Reactor::getInputsMatrix(){ return &in[buf]; } const MatrixXd* Reactor::getOutputsMatrix(){ return &out[buf]; } const MatrixXd* Reactor::getStatesMatrix(){ return &sta[buf]; } const MatrixXd* Reactor::getDisturbancesMatrix(){ return &dist[buf]; } MatrixXd Reactor::getOutputs(){ return out[buf].col(k); } MatrixXd Reactor::getStates(){ return sta[buf].col(k); } MatrixXd Reactor::getDisturbances(){ return dist[buf].col(k); } //Carrega uma única entrada void Reactor::setInput(const double &val, INDEX idx){ if(in[buf](idx,k)==val) return; //Se a entrada for igual, não mude muxInputs.lock(); in[buf](int(idx),Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,in[buf].cols()-(k),val); muxInputs.unlock(); } void Reactor::setDisturbance(const double &val, INDEX idx){ if(dist[buf](idx,k)==val) return; //Se a entrada for igual, não mude muxDisturbances.lock(); dist[buf](int(idx),Eigen::seq(k,Eigen::last)) = MatrixXd::Constant(1,dist[buf].cols()-(k),val); muxDisturbances.unlock(); } void Reactor::startSamplingThread(){ if(!samplingThreadStarted){ //Evitar a recriação de threads #if(REACTOR_DEBUG) cout<<"Starting Thread"<<endl; #endif samplingThread=thread([this]{onSample();}); samplingThreadShouldDie = false; //limpar as flags samplingThreadStarted = true; } } void Reactor::killSamplingThread(){ // t1.detach libera a thread principal de esperar a execução da thread t1 // Quando a execuçao termina, os recursos são limpos da memória if(samplingThreadStarted){ samplingThread.detach(); samplingThreadShouldDie = true; samplingThreadStarted = false; } } Reactor::~Reactor(){ killSamplingThread(); if(par!=nullptr) delete par; }
36.40327
192
0.610704
[ "vector" ]
1a14d18e81ba725be6201ffaecdea0f74b1a1bee
6,036
cpp
C++
server/DataBase.cpp
matteovol/async-server-boost
1e850037603a65b21e4857d3d059e3a02b23b551
[ "MIT" ]
1
2019-10-13T16:56:06.000Z
2019-10-13T16:56:06.000Z
server/DataBase.cpp
matteovol/async-server-boost
1e850037603a65b21e4857d3d059e3a02b23b551
[ "MIT" ]
null
null
null
server/DataBase.cpp
matteovol/async-server-boost
1e850037603a65b21e4857d3d059e3a02b23b551
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2019 ** Babel ** File description: ** Database Object */ /// \file DataBase.cpp /// \author Matteo V. Arthur L. /// \brief DataBase implementation file #include "DataBase.hpp" /// \brief Constructor. /// Open (or create) the database. /// Throw a Babel::Exception if something went wrong with sqlite3 /// \param dbName : Name of the database to be opened (or created) Serv::DataBase::DataBase(const std::string &dbName) : _db(nullptr), _errorMsg(nullptr) { int quit = sqlite3_open(dbName.c_str(), &_db); if (quit) throw Babel::Exception("Can't open " + dbName + " Data base", "DataBase constructor"); } /// \brief Destructor. /// Free _errorMsg and close the connection to database Serv::DataBase::~DataBase() { if (_errorMsg != nullptr) sqlite3_free(_errorMsg); sqlite3_close(_db); } /// \param table : name of the table you want to insert something into /// \param values : all values needed in the table /// \brief Insert values in the specified table. /// If insertion is not possible throw a Babel::Exception void Serv::DataBase::insert(const std::string &table, const std::vector<std::string> &values) { std::string querry = "INSERT INTO " + table + " VALUES "; unsigned int count = 0; for (auto i : values) { querry += i; if (++count < values.size()) querry += ", "; } querry += ";"; std::cout << "Querry insert: " << querry << std::endl; if (sqlite3_exec(_db, querry.c_str(), 0, nullptr, &_errorMsg) != SQLITE_OK) std::cerr << _errorMsg << std::endl; } /// \param name : name of the table to delete /// \brief Drop the 'name' table from the current database. /// Drop a table is a dangerous action, be careful when using it. /// Throw a Babel::Exception if connection with database is impossible void Serv::DataBase::deleteTable(const std::string &name) { std::string querry = "DROP TABLE " + name; if (sqlite3_exec(_db, querry.c_str(), 0, nullptr, &_errorMsg) != SQLITE_OK) throw Babel::Exception(_errorMsg, "DataBase deleteTable"); } /// \param name : name of the table to be created /// \param columns : vector containing a pair of strings, first string is the columns' name and second string is the columns' type /// \brief Create a table named 'name' and create all requested columns with their respective types void Serv::DataBase::createTable( const std::string &name, std::vector<std::pair<std::string, std::string>> &columns ) { std::string querry = "CREATE TABLE IF NOT EXISTS " + name + "("; for (auto i : columns) querry += i.first + " " + i.second; querry += ");"; std::cout << "Querry create table: " << querry << std::endl; if (sqlite3_exec(_db, querry.c_str(), 0, nullptr, &_errorMsg) != SQLITE_OK) throw Babel::Exception(_errorMsg, "DataBase createTable"); } /// \param table : name of the table /// \param value : new value /// \param where : criteria /// \brief Update the value 'value' in the table 'table'. You can use 'where' for changing multiple values. void Serv::DataBase::update( const std::string &table, const std::string &value, const std::string &where ) { std::string querry = "UPDATE " + table + " SET " + value; if (where != "") querry += " WHERE " + where; querry += ";"; std::cout << "Querry update: " << querry << std::endl; if (sqlite3_exec(_db, querry.c_str(), 0, nullptr, &_errorMsg) != SQLITE_OK) std::cerr << "Error: Failed to update " + value + " in DataBase" << std::endl; } /// \param res : containers fill with all selected data /// \param argc : size of data array /// \param argv : array of selected data /// \param colName : name of column in data base /// \brief Call back function call to transform 'argv' array in 'res' container /// \return return 0 int Serv::DataBase::selectCallback(void *res, int argc, char **argv, char **colName) { std::unordered_map<std::string, std::string> tmp; if (res == nullptr) throw Babel::Exception("Data container pointer is null", "DataBase select"); for (int i = 0; i < argc; i++) tmp[colName[i]] = argv[i] ? argv[i] : NULL; static_cast<std::vector<std::unordered_map<std::string, std::string>> *>(res)->push_back(tmp); return (0); } /// \param row : name of the values you want to select /// \param table : table where datas are located /// \param where : special selection in the table /// \brief It's an implementation of the SELECT sql function. It return a certain set of datas contained in the data base. /// \return Return a vector of map. Each element of the vector is a line of the DataBase, /// inside each unordered_map a value is mapped with its column name std::vector<std::unordered_map<std::string, std::string>> Serv::DataBase::select (const std::string &row, const std::string &table, const std::string &where) { std::vector<std::unordered_map<std::string, std::string>> res; std::string querry = "SELECT " + row + " FROM " + table; if (where != "") querry += " WHERE " + where; querry += ";"; std::cout << "Querry select: " << querry << std::endl; if (sqlite3_exec(_db, querry.c_str(), selectCallback, &res, &_errorMsg) != SQLITE_OK) std::cerr << "Error: Failed to select " + row + " from " + table << std::endl; return (res); } /// \param elem : element(s) to delete /// \param table : table where you want delete some datas /// \param where : special criteria for deletion /// \brief Implementation of DELETE function in SQL. It's allow to remove some data 'elem' from 'table'. void Serv::DataBase::del(const std::string &elem, const std::string &table, const std::string &where) { std::string querry = "DELETE " + elem + " FROM " + table; if (where != "") querry += (" WHERE " + where); querry += ";"; if (sqlite3_exec(_db, querry.c_str(), 0, nullptr, &_errorMsg) != SQLITE_OK) std::cerr << "Error: Failed to delete " + elem + " from " + table << std::endl; }
39.97351
130
0.64662
[ "object", "vector", "transform" ]
1a1b52f84dbe318e24cb428cb9536491e60b44a1
2,834
cpp
C++
aws-cpp-sdk-glue/source/model/TaskType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-glue/source/model/TaskType.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-glue/source/model/TaskType.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/glue/model/TaskType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace Glue { namespace Model { namespace TaskTypeMapper { static const int EVALUATION_HASH = HashingUtils::HashString("EVALUATION"); static const int LABELING_SET_GENERATION_HASH = HashingUtils::HashString("LABELING_SET_GENERATION"); static const int IMPORT_LABELS_HASH = HashingUtils::HashString("IMPORT_LABELS"); static const int EXPORT_LABELS_HASH = HashingUtils::HashString("EXPORT_LABELS"); static const int FIND_MATCHES_HASH = HashingUtils::HashString("FIND_MATCHES"); TaskType GetTaskTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == EVALUATION_HASH) { return TaskType::EVALUATION; } else if (hashCode == LABELING_SET_GENERATION_HASH) { return TaskType::LABELING_SET_GENERATION; } else if (hashCode == IMPORT_LABELS_HASH) { return TaskType::IMPORT_LABELS; } else if (hashCode == EXPORT_LABELS_HASH) { return TaskType::EXPORT_LABELS; } else if (hashCode == FIND_MATCHES_HASH) { return TaskType::FIND_MATCHES; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<TaskType>(hashCode); } return TaskType::NOT_SET; } Aws::String GetNameForTaskType(TaskType enumValue) { switch(enumValue) { case TaskType::EVALUATION: return "EVALUATION"; case TaskType::LABELING_SET_GENERATION: return "LABELING_SET_GENERATION"; case TaskType::IMPORT_LABELS: return "IMPORT_LABELS"; case TaskType::EXPORT_LABELS: return "EXPORT_LABELS"; case TaskType::FIND_MATCHES: return "FIND_MATCHES"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace TaskTypeMapper } // namespace Model } // namespace Glue } // namespace Aws
30.804348
108
0.61115
[ "model" ]
1a3126a6f6d483a0225ddad5f52f8aaed60fa70b
1,180
cpp
C++
Libraries/xcassets/Tests/test_FullyQualifiedName.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
9
2018-04-30T23:18:27.000Z
2021-06-20T15:13:38.000Z
Libraries/xcassets/Tests/test_FullyQualifiedName.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
null
null
null
Libraries/xcassets/Tests/test_FullyQualifiedName.cpp
djgalloway/xcbuild
936df10e59e5f5d531efca8bd48e445d88e78e0c
[ "BSD-2-Clause-NetBSD" ]
4
2018-10-10T19:44:17.000Z
2020-01-12T11:56:31.000Z
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #include <gtest/gtest.h> #include <xcassets/FullyQualifiedName.h> using xcassets::FullyQualifiedName; TEST(FullyQualifiedName, Parse) { auto name1 = FullyQualifiedName::Parse(""); EXPECT_EQ(name1.name(), ""); EXPECT_EQ(name1.groups(), std::vector<std::string>()); auto name2 = FullyQualifiedName::Parse("name"); EXPECT_EQ(name2.name(), "name"); EXPECT_EQ(name2.groups(), std::vector<std::string>()); auto name3 = FullyQualifiedName::Parse("group1/group2/name"); EXPECT_EQ(name3.name(), "name"); EXPECT_EQ(name3.groups(), std::vector<std::string>({ "group1", "group2" })); EXPECT_EQ(name3.string(), "group1/group2/name"); auto name4 = FullyQualifiedName::Parse("//group//name"); EXPECT_EQ(name4.name(), "name"); EXPECT_EQ(name4.groups(), std::vector<std::string>({ "group" })); EXPECT_EQ(name4.string(), "group/name"); }
32.777778
80
0.687288
[ "vector" ]
1a337959bd2a812d495f72103aeeba052c09263a
2,737
cpp
C++
src/do-re-mi.cpp
maximg/do-re-mi
fcac16f6e266d32d9f9b9fde11684cde34b355f4
[ "MIT" ]
null
null
null
src/do-re-mi.cpp
maximg/do-re-mi
fcac16f6e266d32d9f9b9fde11684cde34b355f4
[ "MIT" ]
null
null
null
src/do-re-mi.cpp
maximg/do-re-mi
fcac16f6e266d32d9f9b9fde11684cde34b355f4
[ "MIT" ]
null
null
null
// Copyright (C) M.Golov 2016 #include <iostream> #include <string> #include <functional> #include <typeinfo> template<typename T> struct TraceConstr { TraceConstr() { std::cout << ">>> " << typeid(T).name() << "\n"; } ~TraceConstr() { std::cout << "<<< " << typeid(T).name() << "\n"; } }; // Framework template<typename TResult, typename TInput, typename TMeta> std::function<TResult(TInput)> getFinalizer(TMeta) { throw std::runtime_error("getFinalizer must be specialized"); } template<typename TMeta, typename TContent> class MetaData { TMeta meta; public: TContent content; MetaData(TMeta meta, TContent content) : meta(meta), content(content) {} template<typename TResult> MetaData<TMeta, TResult> transform(std::function<TResult(TContent)> fx) { return MetaData<TMeta, TResult>{meta, fx(content)}; } template<typename TResult> TResult finalize() { const auto finalizer = getFinalizer<TResult, TContent, TMeta>(meta); return finalizer(content); } }; // Specific application class Backend; using MetaInfo = struct { std::string data; Backend *backend; }; template<typename TContent> using Meta = MetaData<MetaInfo, TContent>; struct InputData : public TraceConstr<InputData> { explicit InputData(int v) : value(v) {} int value; }; struct TransformedData : public TraceConstr<TransformedData> { explicit TransformedData(int v) : value(v) {} double value; }; class Backend { public: explicit Backend(const std::string &id) : id(id) {} Meta<InputData> addMeta(const std::string &meta, std::function<InputData()> fx) { return Meta<InputData>{MetaInfo{meta, this}, fx()}; } std::string finalize(MetaInfo info, TransformedData input) { return std::string("[") + id + ":" + info.data + "]: " + std::to_string(input.value); } private: const std::string id; }; template<> std::function<std::string(TransformedData)> getFinalizer<std::string, TransformedData, MetaInfo>(MetaInfo meta) { return [meta](TransformedData content){ return meta.backend->finalize(meta, content); }; } // Usage example TransformedData transformFxC(const InputData &input) { return TransformedData{(double)input.value}; } int main(int argc, char **argv) { const auto transformFx = [](InputData input) { return TransformedData{(double)input.value}; }; Backend backend("id"); Meta<InputData> input = backend.addMeta("meta", [](){return InputData{42};}); Meta<TransformedData> transformed = input.transform<TransformedData>(transformFxC); std::string output = transformed.finalize<std::string>(); std::cout << "Output: " << output << "\n"; return 0; }
25.579439
93
0.669346
[ "transform" ]
1a3505f2c0870ef8ed30fe10a20b3352c94d2428
10,287
hpp
C++
src/formula_callable.hpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/formula_callable.hpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/formula_callable.hpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2003-2014 by David White <davewx7@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 acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include <functional> #include <iostream> #include <map> #include <string> #include "formula_garbage_collector.hpp" #include "variant.hpp" namespace game_logic { enum class FORMULA_ACCESS_TYPE { READ_ONLY, WRITE_ONLY, READ_WRITE }; struct FormulaInput { std::string name; FORMULA_ACCESS_TYPE access; FormulaInput(const std::string& name, FORMULA_ACCESS_TYPE access=FORMULA_ACCESS_TYPE::READ_WRITE) : name(name), access(access) {} }; class FormulaCallableVisitor; //interface for objects that can have formulae run on them class FormulaCallable : public GarbageCollectible { public: explicit FormulaCallable(bool has_self=false) : has_self_(has_self) {} explicit FormulaCallable(GARBAGE_COLLECTOR_EXCLUDE_OPTIONS options) : has_self_(false), GarbageCollectible(options) {} std::string queryId() const { return getObjectId(); } variant queryValue(const std::string& key) const { if(has_self_ && key == "self") { return variant(this); } return getValue(key); } variant queryValueBySlot(int slot) const { return getValueBySlot(slot); } bool queryConstantValue(const std::string& key, variant* value) const { return getConstantValue(key, value); } void mutateValue(const std::string& key, const variant& value) { setValue(key, value); } void mutateValueBySlot(int slot, const variant& value) { setValueBySlot(slot, value); } std::vector<FormulaInput> inputs() const { std::vector<FormulaInput> res; getInputs(&res); return res; } bool equals(const FormulaCallable* other) const { return doCompare(other) == 0; } bool less(const FormulaCallable* other) const { return doCompare(other) < 0; } virtual std::string toDebugString() const { return ""; } virtual void getInputs(std::vector<FormulaInput>* /*inputs*/) const {}; void serialize(std::string& str) const { serializeToString(str); } bool has_key(const std::string& key) const { return !queryValue(key).is_null(); } // In order to provide support for widgets to be able to have FFL handlers for events // The following two functions are provided for them to use to respectively execute // a command and create a new formula from a variant (which is expected to contain FFL // commands). If you're making some new that object that provides a custom symbol // table or supports different types of CommandCallable you should override these // two functions to provide widget support. virtual bool executeCommand(const variant &v); virtual FormulaPtr createFormula(const variant& v); //is some kind of command to the engine. virtual bool isCommand() const { return false; } virtual bool isCairoOp() const { return false; } void performVisitValues(FormulaCallableVisitor& visitor) { visitValues(visitor); } protected: virtual ~FormulaCallable() {} virtual variant getValueDefault(const std::string& key) const { return variant(); } virtual void setValueDefault(const std::string& key, const variant& value) {} virtual void setValue(const std::string& key, const variant& value); virtual void setValueBySlot(int slot, const variant& value); virtual int doCompare(const FormulaCallable* callable) const { return this < callable ? -1 : (this == callable ? 0 : 1); } virtual void serializeToString(std::string& str) const; virtual void visitValues(FormulaCallableVisitor& visitor) {} private: virtual variant getValue(const std::string& key) const = 0; virtual variant getValueBySlot(int slot) const; virtual bool getConstantValue(const std::string& key, variant* value) const { return false; } virtual std::string getObjectId() const { return "FormulaCallable"; } bool has_self_; }; class FormulaCallableNoRefCount : public FormulaCallable { public: FormulaCallableNoRefCount() { turn_reference_counting_off(); } virtual ~FormulaCallableNoRefCount() {} }; class FormulaCallableWithBackup : public FormulaCallable { const FormulaCallable& main_; const FormulaCallable& backup_; void setValueBySlot(int slot, const variant& value) override { const_cast<FormulaCallable&>(backup_).mutateValueBySlot(slot, value); } variant getValueBySlot(int slot) const override { return backup_.queryValueBySlot(slot); } variant getValue(const std::string& key) const override { variant var = main_.queryValue(key); if(var.is_null()) { return backup_.queryValue(key); } return var; } void getInputs(std::vector<FormulaInput>* inputs) const override { main_.getInputs(inputs); backup_.getInputs(inputs); } public: FormulaCallableWithBackup(const FormulaCallable& main, const FormulaCallable& backup) : FormulaCallable(false), main_(main), backup_(backup) {} }; class FormulaVariantCallableWithBackup : public FormulaCallable { variant var_; const FormulaCallable& backup_; variant getValue(const std::string& key) const override { variant var = var_.get_member(key); if(var.is_null()) { return backup_.queryValue(key); } return var; } void setValueBySlot(int slot, const variant& value) override { const_cast<FormulaCallable&>(backup_).mutateValueBySlot(slot, value); } variant getValueBySlot(int slot) const override { return backup_.queryValueBySlot(slot); } void getInputs(std::vector<FormulaInput>* inputs) const override { backup_.getInputs(inputs); } public: FormulaVariantCallableWithBackup(const variant& var, const FormulaCallable& backup) : FormulaCallable(false), var_(var), backup_(backup) {} void surrenderReferences(GarbageCollector* collector) override { collector->surrenderVariant(&var_); } }; class MapFormulaCallable : public FormulaCallable { public: explicit MapFormulaCallable(variant node); explicit MapFormulaCallable(const FormulaCallable* fallback=nullptr); explicit MapFormulaCallable(const std::map<std::string, variant>& m); variant write() const; MapFormulaCallable& add(const std::string& key, const variant& value); void setFallback(const FormulaCallable* fallback) { fallback_ = fallback; } //adds an entry and gets direct access to the variant. Use with caution //and for cases where calling add() repeatedy isn't efficient enough. variant& addDirectAccess(const std::string& key); bool empty() const { return values_.empty(); } void clear() { values_.clear(); } bool contains(const std::string& key) const { return values_.count(key) != 0; } const std::map<std::string, variant>& values() const { return values_; } typedef std::map<std::string,variant>::const_iterator const_iterator; const_iterator begin() const { return values_.begin(); } const_iterator end() const { return values_.end(); } variant& ref(const std::string& key) { return values_[key]; } void surrenderReferences(GarbageCollector* collector) override; private: //MapFormulaCallable(const MapFormulaCallable&); variant getValueBySlot(int slot) const override { return fallback_->queryValueBySlot(slot); } void setValueBySlot(int slot, const variant& value) override { const_cast<FormulaCallable*>(fallback_)->mutateValueBySlot(slot, value); } virtual void visitValues(FormulaCallableVisitor& visitor) override; variant getValue(const std::string& key) const override; void getInputs(std::vector<FormulaInput>* inputs) const override; void setValue(const std::string& key, const variant& value) override; std::map<std::string,variant> values_; const FormulaCallable* fallback_; }; typedef ffl::IntrusivePtr<FormulaCallable> FormulaCallablePtr; typedef ffl::IntrusivePtr<const FormulaCallable> ConstFormulaCallablePtr; typedef ffl::IntrusivePtr<MapFormulaCallable> MapFormulaCallablePtr; typedef ffl::IntrusivePtr<const MapFormulaCallable> ConstMapFormulaCallablePtr; class FormulaExpression; class CommandCallable : public FormulaCallable { public: CommandCallable(); void runCommand(FormulaCallable& context) const; void setExpression(const FormulaExpression* expr); bool isCommand() const override { return true; } std::string toDebugString() const override { std::string s = typeid(*this).name(); return "(Command Object: " + s + ")"; } private: virtual void execute(FormulaCallable& context) const = 0; variant getValue(const std::string& key) const override { return variant(); } void getInputs(std::vector<game_logic::FormulaInput>* inputs) const override {} //these two members are a more compiler-friendly version of a //intrusive_ptr<FormulaExpression> const FormulaExpression* expr_; ffl::IntrusivePtr<const reference_counted_object> expr_holder_; }; class FnCommandCallable : public CommandCallable { public: FnCommandCallable(const char* name, std::function<void()> fn); std::string debugObjectName() const override; private: virtual void execute(FormulaCallable& context) const override; const char* name_; std::function<void()> fn_; }; class FnCommandCallableArg : public CommandCallable { public: FnCommandCallableArg(const char* name, std::function<void(FormulaCallable*)> fn); std::string debugObjectName() const override; private: virtual void execute(FormulaCallable& context) const override; const char* name_; std::function<void(FormulaCallable*)> fn_; }; variant deferCurrentCommandSequence(); }
31.75
142
0.742588
[ "object", "vector" ]
1a37847b0cd17c6fde6dee6dcf23529f0cf116d7
2,420
cpp
C++
src/processor.cpp
alshakir/CppND-System-Monitor
f506cb2e19d17d69318def1dcc80d86f83d39e66
[ "MIT" ]
null
null
null
src/processor.cpp
alshakir/CppND-System-Monitor
f506cb2e19d17d69318def1dcc80d86f83d39e66
[ "MIT" ]
null
null
null
src/processor.cpp
alshakir/CppND-System-Monitor
f506cb2e19d17d69318def1dcc80d86f83d39e66
[ "MIT" ]
null
null
null
#include "processor.h" #include <iostream> #include "linux_parser.h" using namespace LinuxParser; using namespace std; using std::stod; using std::stof; // TODO: Return the aggregate CPU utilization float Processor::Utilization() { vector<string> f = LinuxParser::CpuUtilization(); std::stringstream s(f[0]); string cpu, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice; s >> cpu >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice; /* I used the folliwng link https://github.com/Leo-G/DevopsWiki/wiki/How-Linux-CPU-Usage-Time-and-Percentage-is-calculated Formula To calculate Linux CPU usage time subtract the idle CPU time from the total CPU time as follows: Total CPU time since boot = user+nice+system+idle+iowait+irq+softirq+steal Total CPU Idle time since boot = idle + iowait Total CPU usage time since boot = Total CPU time since boot - Total CPU Idle time since boot Total CPU percentage = Total CPU usage time since boot/Total CPU time since boot X 100 For real time CPU usage, you will need to calculate the time between two intervals. also the following link helped for the real time calculations https://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux */ size_t sz; double d_nice = std::stod(nice, &sz); double d_user = std::stod(user, &sz); double d_system = std::stod(system, &sz); double d_idle = std::stod(idle, &sz); double d_iowait = std::stod(iowait, &sz); double d_irq = std::stod(irq, &sz); double d_softirq = std::stod(softirq, &sz); double d_steal = std::stod(steal, &sz); // double d_guest = std::stod(guest,&sz); // double d_guest_nice = std::stod(guest_nice,&sz); double TotalCPUTime = d_user + d_nice + d_system + d_idle + d_iowait + d_irq + d_softirq + d_steal; double TotalIdleTime = d_idle + d_iowait; double currentTotalCPUTime = TotalCPUTime - previousTotal; double currentTotalIdleTime = TotalIdleTime - previousIdle; // reset values for next cycle previousTotal = TotalCPUTime; previousIdle = TotalIdleTime; // ouble TotalCPUUsageSinceBoot = TotalCPUTime - TotalIdleTime; double totalCPUPercentageSinceBoot = (currentTotalCPUTime - currentTotalIdleTime) / currentTotalCPUTime; return totalCPUPercentageSinceBoot; }
32.702703
110
0.713223
[ "vector" ]
1a43b69be0bb02d4de540e6e5730776c80a89af1
1,491
cpp
C++
Algorithms/0382.LinkedListRandomNode/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0382.LinkedListRandomNode/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0382.LinkedListRandomNode/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <algorithm> #include <memory> #include <random> #include <vector> #include "ListNode.h" #include "ListNodeUtils.h" #include "gtest/gtest.h" using CommonLib::ListNode; namespace { class Solution { public: Solution(ListNode* head) : _generator(std::random_device()()) { while (head != nullptr) { _nodes.push_back(head); head = head->next; } _distribution = std::uniform_int_distribution<>(0, static_cast<int>(_nodes.size() - 1)); } // Returns a random node's value. int getRandom() { return _nodes[_distribution(_generator)]->val; } private: std::mt19937 _generator; std::uniform_int_distribution<> _distribution; std::vector<ListNode*> _nodes; }; } using CommonLib::createLinkedList; namespace { bool contains(std::vector<int> const &sourceValues, int value) { return std::find(sourceValues.cbegin(), sourceValues.cend(), value) != sourceValues.cend(); } } namespace LinkedListRandomNodeTask { TEST(LinkedListRandomNodeTaskTests, Examples) { const std::vector<int> values({1, 2, 3}); const std::shared_ptr<ListNode> linkedList(createLinkedList(values, true)); Solution solution(linkedList.get()); // TODO (std_string) : think about check for uniform distribution constexpr size_t caseCount = 5; for (size_t caseIndex = 0; caseIndex < caseCount; ++caseIndex) ASSERT_TRUE(contains(values, solution.getRandom())); } }
22.253731
99
0.666667
[ "vector" ]
1a44eb97006ef3c8bed530b76f1303b85592d9c7
20,197
cpp
C++
display/GUI.cpp
mbellier/FluidSolver
c75c95f1725a362703d500c0dd3443df7d710bc3
[ "Apache-2.0" ]
18
2015-01-08T00:48:40.000Z
2022-01-12T15:04:04.000Z
display/GUI.cpp
mbellier/FluidSolver
c75c95f1725a362703d500c0dd3443df7d710bc3
[ "Apache-2.0" ]
null
null
null
display/GUI.cpp
mbellier/FluidSolver
c75c95f1725a362703d500c0dd3443df7d710bc3
[ "Apache-2.0" ]
3
2015-11-20T02:35:16.000Z
2018-03-25T20:14:55.000Z
#include "GUI.hpp" #include "../config.hpp" #include "../solver/FloatMatrix2D.hpp" #include "../solver/FluidSolver2D.hpp" #include "Leap.h" #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) GUI::GUI(QWidget *parent, QString name, Print *p, Config &configurationDatas, bool drawVelocityField, bool enableMouseMove) : QGLWidget(parent), _pause(false), b_Fullscreen(false), _drawVelocityField(drawVelocityField), _enableMouseMove(enableMouseMove), configuration(configurationDatas) { /* default title */ setWindowTitle(name); /* set window geometry */ resize(configuration.getWidth(true), configuration.getHeight(true)); if(configuration.getFPS() == 0){ /* No refreshing */ t_Timer = NULL; } else{ /* new timer */ t_Timer = new QTimer(this); connect(t_Timer, SIGNAL(timeout()), this, SLOT(timeOutSlot())); /* set interval in millisecond */ t_Timer->start(1000 / configuration.getFPS()); } /* new fluid */ fluid = new FluidSolver(configuration.getWidth(), configuration.getHeight(), configurationDatas); if(strcmp("",configurationDatas.getVelXFile()) != 0) fluid->_u_prev->load(configurationDatas.getVelXFile()); if(strcmp("",configurationDatas.getVelYFile()) != 0) fluid->_v_prev->load(configurationDatas.getVelYFile()); if(strcmp("",configurationDatas.getDensFile()) != 0) fluid->_dens_prev->load(configurationDatas.getDensFile()); /* print modes */ _printModes.append(p); _currentPrintMode = 0; /* will be used by resized velocity field drawings */ M1 = new FloatMatrix2D(fluid->_u->getSize(1) / k, fluid->_u->getSize(0) / k); M2 = new FloatMatrix2D(fluid->_v->getSize(1) / k, fluid->_v->getSize(0) / k); /* mouse parameters */ setMouseTracking(true); coef = 0.5; mouseX = 0; mouseY = 0; dispMouseX = 0; dispMouseY = 0; pressing = false; emptying = false; waitingMousePress = false; /* dialog windows to save/load a configuration*/ saveWin = new Dialog(this); saveWin->setWindowTitle("Save configuration"); connect(saveWin, SIGNAL(accepted()), this, SLOT(saveConfig())); connect(saveWin, SIGNAL(rejected()), this, SLOT(desPause())); loadWin = new Dialog(this); loadWin->setWindowTitle("Open configuration"); connect(loadWin, SIGNAL(accepted()), this, SLOT(loadConfig())); connect(loadWin, SIGNAL(rejected()), this, SLOT(desPause())); } /** * Initializes the openGL parameters */ void GUI::initializeGL(){ glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel (GL_SMOOTH); glClearColor (0.0f, 0.0f, 0.0f, 0.0f); glClearDepth (1.0f); glEnable (GL_DEPTH_TEST); glDepthFunc (GL_LEQUAL); glHint (GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } /** * Resizes the openGL window. */ void GUI::resizeGL(int width, int height){ if(height == 0) height = 1; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /** * Draws the new state of the screen */ void GUI::paintGL(){ /* clear opengl buffer */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); /* * * drawings * * */ /* (1) density */ _printModes[_currentPrintMode]->printMatrixScalar(*(fluid->_dens), *(fluid->_u), *(fluid->_v)); /* (2) velocity */ if (_drawVelocityField){ /* adjusting display resolution of the velocity field */ resizeMatrix(*M2, *(fluid->_v), k); resizeMatrix(*M1, *(fluid->_u), k); _printModes[_currentPrintMode]->printMatrixVector(*M1, *M2); } /* (3) obstacles */ _printModes[_currentPrintMode]->drawObstacle(fluid->_dens->getSize(1), fluid->_dens->getSize(0), *(fluid->_obstacles)); /* (4) cursor */ _printModes[_currentPrintMode]->printSquare(mouseX, mouseY, (20 * coef) / fluid->_dens->getSize(1), (20 * coef) / fluid->_dens->getSize(0), width(), height()); /* (5) Leap Motion cursors */ for (int i=0; i < fingers.size(); i++) _printModes[_currentPrintMode]->drawCircle(fingers[i].x / fluid->_dens->getSize(1) * width(), fingers[i].y / fluid->_dens->getSize(0) * height(), 40, width(), height(), 0.5f, 0.5f, 0.8f); } /** * Creates a new obstacle defined by the dimension given * * @param sqrWidth Width of the obstacle wanted * @param sqrHeight Height of the obstacle wanted */ void GUI::addObstacle(float sqrWidth, float sqrHeight){ /* matrix size */ const int n = fluid->_dens->getSize(0); const int m = fluid->_dens->getSize(1); int xPos, yPos; /* position of the mouse on the grid */ xPos = 1 + ((float) mouseX / width() ) * m; yPos = 1 + n - ((float) mouseY / height()) * n; /* avoid out of bound positions */ if (xPos < 0) xPos = 0; if (xPos > m) xPos = m; if (yPos < 0) yPos = 0; if (yPos > n) yPos = n; const int A1 = MAX(2, yPos - (int)sqrHeight / 2); const int A0 = MAX(2, xPos - (int)sqrWidth / 2); const int B1 = MIN(n-2, yPos + (int)sqrHeight / 2); const int B0 = A0; sqrWidth = MIN(sqrWidth, m - 2 - A0 - 1); fluid->_obstacles->addSegment(A0, A1, B0, B1, sqrWidth); } /** * Refresh loop */ void GUI::timeOutSlot(){ /* calculates simulation FPS */ calculateFPS(); /* updates window title */ dispDens = fluid->_dens->get(dispMouseX, dispMouseY); dispVelX = fluid->_u->get(dispMouseX, dispMouseY); dispVelY = fluid->_v->get(dispMouseX, dispMouseY); QString title; if (_pause) title.sprintf("PAUSED"); else title.sprintf("%.1f fps", fps); title.sprintf("%s - (%d ; %d) - Density = %.3f - Velocity = (%.1e ; %.1e)", title.toStdString().c_str(), dispMouseX, dispMouseY, dispDens, dispVelX, dispVelY); this->setWindowTitle(title); // TODO: attribute const float _fillingSpeed = 1.0 / 10; /* Mouse events */ if(pressing) fillSquare(20 * coef, 20 * coef, configuration.getDt() * _fillingSpeed, fluid->_dens); if(emptying) fillSquare(20 * coef, 20 * coef, -configuration.getDt() * _fillingSpeed, fluid->_dens); /* Leap Motion */ Leap::PointableList pointables = leap.frame().pointables(); Leap::InteractionBox iBox = leap.frame().interactionBox(); float windowWidth = configuration.getWidth(); float windowHeight = configuration.getHeight(); fingers.clear(); for( int p = 0; p < pointables.count(); p++ ) { Leap::Pointable pointable = pointables[p]; Leap::Vector normalizedPosition = iBox.normalizePoint(pointable.stabilizedTipPosition()); normalizedPosition.x *= windowWidth; normalizedPosition.y *= windowHeight; float x = normalizedPosition.x;// * windowWidth; float y = normalizedPosition.y;// * windowHeight; if(pointable.touchZone() != Leap::Pointable::Zone::ZONE_NONE) { Leap::Vector vel = pointable.tipVelocity(); fluid->_u->set(x,y, (vel.x)/windowWidth / 2); fluid->_v->set(x,y, (vel.y)/windowHeight / 2); if(pointable.touchDistance() <= 0) { // gl::color(1, 0, 0, -pointable.touchDistance()); int delta = 10; for (int i=-delta/2; i<delta/2;i++) for (int j=-delta/2; j<delta/2; j++) fluid->_dens->set(x-i,y-j, fluid->_dens->get(x-i,y-j) + (0.5-pointable.touchDistance())/4); } fingers.append(normalizedPosition); } else { // gl::color(0, 0, 1, .05); } _printModes[_currentPrintMode]->drawCircle(x, y, 40, windowWidth, windowHeight, 1., 1., 1.); } if (!_pause){ /* Solver computations */ fluid->velStep (fluid->_u, fluid->_v, fluid->_u_prev, fluid->_v_prev, configuration.getViscosity(), configuration.getDt()); fluid->densStep(fluid->_dens, fluid->_dens_prev, fluid->_u, fluid->_v, configuration.getDiff(), configuration.getDt()); /* Reset matrices */ fluid->_u_prev->fill(0); fluid->_v_prev->fill(0); fluid->_dens_prev->fill(0); fluid->_dens_prev->add(*(fluid->_dens_src)); fluid->_u_prev->add(*(fluid->_u_vel_src)); fluid->_v_prev->add(*(fluid->_v_vel_src)); } /* drawings */ updateGL(); } /* * * * * * * * * * * * * * * * TOOLS * * * * * * * * * * * * * * * * * * */ /** * Toggles fullscreen */ void GUI::toggleFullWindow(){ if(b_Fullscreen){ showNormal(); b_Fullscreen = false; } else{ showFullScreen(); b_Fullscreen = true; } } /** * Adds a new print mode to the list * * @param p Print mode to add */ void GUI::addPrintMode(Print *p){ _printModes.append(p); } /** * Calculates the frames per second */ void GUI::calculateFPS(){ static QTime time; static unsigned int frameNumber = 1; unsigned int msec; msec = time.elapsed(); if (msec < 1000) { frameNumber++; } else { fps = frameNumber * (1000 / (float)msec); frameNumber = 0; time.restart(); } } /** * Fills a centered square in the matrix with a specific value * * @param sqrWidth Width of the square to fill * @param sqrHeight Height of the square to fill * @param value Value to set in the matrix * @param matrix Matrix to modify * @param prev Indicates if you are seting a velocity source or not */ void GUI::fillSquare(unsigned int sqrWidth, unsigned int sqrHeight, float value, FloatMatrix2D* matrix, bool prev){ /* matrix size */ const int n = matrix->getSize(0); const int m = matrix->getSize(1); int xPos, yPos; if(prev){ /* previous position of the mouse on the grid */ xPos = ((float) firstPosX / width() ) * m; yPos = n - ((float) firstPosY / height()) * n; } else{ /* position of the mouse on the grid */ xPos = 1 + ((float) mouseX / width() ) * m; yPos = 1 + n - ((float) mouseY / height()) * n; } /* avoid out of bound positions */ if (xPos < 0) xPos = 0; if (xPos > m) xPos = m; if (yPos < 0) yPos = 0; if (yPos > n) yPos = n; /* center a square on the mouse cursor */ const int jMin = MAX(0, yPos - (int)sqrHeight / 2); const int iMin = MAX(0, xPos - (int)sqrWidth / 2); const int jMax = MIN(n, yPos + (int)sqrHeight / 2); const int iMax = MIN(m, xPos + (int)sqrWidth / 2); /* fill the square */ float newVal; for (int i = iMin; i < iMax; ++ i){ for(int j = jMin; j < jMax; ++ j){ newVal = matrix->get(i, j) + value; if(!prev) if (newVal < 0) newVal = 0; if(!(fluid->_obstacles->isInObstacles(i,j))){ matrix->set( i, j, newVal); } } } } /** * Returns a matrix 'out' given a matrix 'in'. * The values of out are the average of the values of in * located in submatrix of size k. * * @param out Matrix resized * @param in Matrix to resize * @param k Reduction factor */ void GUI::resizeMatrix(FloatMatrix2D &out, const FloatMatrix2D &in, int k){ /* out size */ const unsigned int newSize1 = in.getSize(0) / k; const unsigned int newSize2 = in.getSize(1) / k; /* size checking */ if (out.getSize(0) != newSize1 || out.getSize(1) != newSize2) { fprintf(stderr, "Error in GUI::resizeMatrix : wrong size of output matrix.\n"); return; } float average = 0; /* for each submatrix */ for (unsigned int im = 0; im < newSize2; ++im){ for (unsigned int jm = 0; jm < newSize1; ++jm){ /* compute the average value of a submatrix */ for (unsigned int iX = im * k; iX < (im + 1) * k; ++iX){ for (unsigned int jX = jm * k; jX < (jm + 1) * k; ++jX){ average += in.get(iX,jX); } } out.set(im, jm, average / ( k * k )); average = 0; } } } /* * * * * * * * * * * * * * * * EVENTS * * * * * * * * * * * * * * * * * * */ /** * Manages the events on mouse buttons. * * @param mouseEvent Event of the mouse related to a pressure */ void GUI::mousePressEvent(QMouseEvent *mouseEvent){ Qt::KeyboardModifiers modifiers = mouseEvent->modifiers(); if(mouseEvent->buttons() == Qt::LeftButton){ if(waitingMousePress == true){ float dirX = ((int)mouseX - firstPosX); float dirY = -((int)mouseY - firstPosY); fillSquare(20 * coef, 20 * coef, 0.00001 * dirX, fluid->_u_vel_src, true); fillSquare(20 * coef, 20 * coef, 0.00001 * dirY, fluid->_v_vel_src, true); fillSquare(20 * coef, 20 * coef, 0.05, fluid->_dens_src, true); waitingMousePress = false; } else if(modifiers == Qt::ShiftModifier){ firstPosX = mouseX; firstPosY = mouseY; waitingMousePress = true; } else if(modifiers == Qt::ControlModifier){ fillSquare(20 * coef, 20 * coef, 0.05, fluid->_dens_src); //TO DO parmeter the value with dt } else{ pressing = true; } } if(mouseEvent->buttons() == Qt::RightButton){ if(modifiers == Qt::ControlModifier){ addObstacle(20 * coef, 20 * coef); } else{ emptying = true; } } } /** * Manages the events on mouse buttons when they are released. * * @param mouseEvent Event of the mouse related to a release */ void GUI::mouseReleaseEvent(QMouseEvent *mouseEvent) { if(mouseEvent->buttons() != Qt::LeftButton) { pressing = false; } if(mouseEvent->buttons() != Qt::RightButton) { emptying = false; } } /** * Manages the events on mouse movements. * * @param mouseEvent Event of the mouse related to a movement */ void GUI::mouseMoveEvent(QMouseEvent *mouseEvent){ /* matrix size */ const unsigned int n = (fluid->_dens)->getSize(0); const unsigned int m = (fluid->_dens)->getSize(1); /* mouse position */ const unsigned int xPos = (float) mouseEvent->x() / width() * m; const unsigned int yPos = n - (float) mouseEvent->y() / height() * n; /* store mouse pos. */ prevMouseX = mouseX; prevMouseY = mouseY; mouseX = mouseEvent->x(); mouseY = mouseEvent->y(); /* if the mouse is on the grid */ if( xPos < m && yPos < n){ /* update title information */ dispMouseX = xPos; dispMouseY = yPos; if (_enableMouseMove && !_pause){ /* mouse speed */ float velX = ((int)(mouseX - prevMouseX) * coef); // caution: signed operation float velY = ((int)(mouseY - prevMouseY) * coef); /* update fluid speed */ if(!(fluid->_obstacles->isInObstacles(xPos,yPos))){ fluid->_u->set (xPos, yPos, fluid->_u->get(xPos, yPos) + velX); fluid->_v->set (xPos, yPos, fluid->_v->get(xPos, yPos) - velY); } } } } /** * Manages the events on mouse wheel. * * @param mouseEvent Event of the mouse related to its wheel */ void GUI::wheelEvent(QWheelEvent *mouseEvent){ int n = (fluid->_dens)->getSize(0); int m = (fluid->_dens)->getSize(1); int pos = mouseEvent->delta(); coef += (float) pos/120; if(coef > m/20){ coef = m/20; } else if(coef > n/20){ coef = n/20; } else if(coef < 0){ coef = 0.1; } } /** * Saves the current configuration */ void GUI::saveConfig(){ QString densFile, velXFile, velYFile; QString densSrcFile, velXSrcFile, velYSrcFile; QString configName = saveWin->getText(); /* check if the config. already exists */ bool test = configuration.setConfig(configName); if(!test){ configuration.setName(configName); configuration.createConfig(); } /* absolute file paths */ densFile = QCoreApplication::applicationDirPath() + "/" + configName + "_density"; velXFile = QCoreApplication::applicationDirPath() + "/" + configName + "_velX"; velYFile = QCoreApplication::applicationDirPath() + "/" + configName + "_velY"; densSrcFile = QCoreApplication::applicationDirPath() + "/" + configName + "_density_src"; velXSrcFile = QCoreApplication::applicationDirPath() + "/" + configName + "_velX_src"; velYSrcFile = QCoreApplication::applicationDirPath() + "/" + configName + "_velY_src"; /* save matrices */ fluid->_dens->save(densFile.toStdString().c_str()); configuration.setDensFile(densFile); fluid->_u->save(velXFile.toStdString().c_str()); configuration.setVelXFile(velXFile); fluid->_v->save(velYFile.toStdString().c_str()); configuration.setVelYFile(velYFile); fluid->_dens_src->save(densSrcFile.toStdString().c_str()); configuration.setDensSrcFile(densSrcFile); fluid->_u_vel_src->save(velXSrcFile.toStdString().c_str()); configuration.setVelXSrcFile(velXSrcFile); fluid->_v_vel_src->save(velYSrcFile.toStdString().c_str()); configuration.setVelYSrcFile(velYSrcFile); /* update the configuration file */ configuration.writeConfig(fluid->_obstacles->getSegList()); /* resume the simulation */ _pause = false; } /** * Loads a new configuration */ void GUI::loadConfig(){ QString densFile, velXFile, velYFile; QString configName = loadWin->getText(); /* check the validity of the config name */ bool test = configuration.setConfig(configName); if(!test){ std::cerr << "Error: invalid config name '" << configName.toStdString(); std::cerr << "'." << std::endl; _pause = false; return; } /* load the new config */ configuration.updateConfig(); /* if files provided, load them */ if(strcmp("",configuration.getVelXFile()) != 0) fluid->_u->load(configuration.getVelXFile()); if(strcmp("",configuration.getVelYFile()) != 0) fluid->_v->load(configuration.getVelYFile()); if(strcmp("",configuration.getDensFile()) != 0) fluid->_dens->load(configuration.getDensFile()); if(strcmp("",configuration.getVelXSrcFile()) != 0) fluid->_u_vel_src->load(configuration.getVelXSrcFile()); if(strcmp("",configuration.getVelYSrcFile()) != 0) fluid->_v_vel_src->load(configuration.getVelYSrcFile()); if(strcmp("",configuration.getDensSrcFile()) != 0) fluid->_dens_src->load(configuration.getDensSrcFile()); /* overwrite the obstacles */ delete fluid->_obstacles; fluid->_obstacles = new Obstacles(fluid->_dens->getSize(1),fluid->_dens->getSize(0),configuration); /* resume the simulation */ _pause = false; } /** * Manages keyboard events. * * @param keyEvent Event of the keybord */ void GUI::keyPressEvent(QKeyEvent *keyEvent){ Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); switch(keyEvent->key()){ case Qt::Key_Escape: close(); break; case Qt::Key_F1: toggleFullWindow(); break; case Qt::Key_S: if(modifiers == Qt::ControlModifier){ _pause = true; saveWin->show(); } break; case Qt::Key_O: if(modifiers == Qt::ControlModifier){ _pause = true; loadWin->show(); } break; case Qt::Key_Enter: // Numpad Enter case Qt::Key_Return: // Classic Enter _currentPrintMode ++; _currentPrintMode %= _printModes.count(); break; case Qt::Key_V: _drawVelocityField = !_drawVelocityField; break; case Qt::Key_Backspace: // reset fluid + sources + obstacles fluid->_obstacles->reset(); case Qt::Key_R: // reset sources + obstacles fluid->resetSources(); case Qt::Key_F: // reset only the fluid fluid->resetFluid(); for (int i = 0; i < _printModes.count(); i++){ _printModes[i]->reset(); } break; case Qt::Key_M: _enableMouseMove = !_enableMouseMove; break; case Qt::Key_Plus: coef += .2; break; case Qt::Key_Minus: coef -= .2; if (coef < .1) coef = .1; break; case Qt::Key_Space: _pause = !_pause; for (int i = 0; i < _printModes.count(); i++){ _printModes[i]->pause(); } break; case Qt::Key_W: Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); if(modifiers == Qt::ControlModifier){ close(); } break; } } GUI::~GUI(){ delete t_Timer; delete fluid; delete M1; delete M2; }
26.893475
103
0.609546
[ "geometry", "vector" ]
1a51bec40137f0a3b13bf2e16993eda095e12877
2,561
hpp
C++
naos/includes/kernel/mm/slab.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
14
2020-02-12T11:07:58.000Z
2022-02-02T00:05:08.000Z
naos/includes/kernel/mm/slab.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
null
null
null
naos/includes/kernel/mm/slab.hpp
kadds/NaOS
ea5eeed6f777b8f62acf3400b185c94131b6e1f0
[ "BSD-3-Clause" ]
4
2020-02-27T09:53:53.000Z
2021-11-07T17:43:44.000Z
#pragma once #include "../util/bit_set.hpp" #include "../util/hash_map.hpp" #include "../util/linked_list.hpp" #include "../util/str.hpp" #include "buddy.hpp" #include "common.hpp" #include "list_node_cache.hpp" #define NewSlabGroup(domain, struct, align, flags) \ domain->create_new_slab_group(sizeof(struct), util::string(memory::KernelCommonAllocatorV, #struct), align, flags) namespace memory { struct slab { using bitmap_t = util::bit_set_inplace<512>; bitmap_t bitmap; // max 512 element u32 rest; u32 color_offset; slab *prev; slab *next; char *data_ptr; slab(slab &) = delete; slab(const slab &) = delete; slab(slab &&) = delete; slab &operator=(const slab &) = delete; slab &operator=(slab &&) = delete; slab(u32 element_count, u32 color) : rest(element_count) , color_offset(color) , prev(nullptr) , next(nullptr){}; }; /// A same slab list set class slab_group { private: lock::rw_lock_t slab_lock; const u64 obj_align_size; const u64 size; util::string name; u32 color_offset; u64 flags; u64 align; u32 node_pre_slab; u32 page_pre_slab; u64 all_obj_count; u64 all_obj_used; slab *free_head, *used_head; private: slab *new_memory_node(); void delete_memory_node(slab *s); public: slab_group(u64 size, const char *name, u64 align, u64 flags); const util::string get_name() const { return name; } u64 get_size() const { return size; } void *alloc(); void free(void *ptr); int shrink(); static slab_group *get_group_from(void *ptr); }; /// The slab_group collection of the specified domain struct slab_cache_pool { private: lock::rw_lock_t group_lock; util::hash_map<util::string, slab_group *> map; public: slab_group *find_slab_group(const util::string &name); slab_group *create_new_slab_group(u64 size, util::string name, u64 align, u64 flags); void remove_slab_group(slab_group *group); slab_cache_pool(); }; extern slab_cache_pool *global_kmalloc_slab_domain; extern slab_cache_pool *global_dma_slab_domain; extern slab_cache_pool *global_object_slab_domain; /// An object allocator struct SlabObjectAllocator : IAllocator { private: slab_group *slab_obj; public: SlabObjectAllocator(slab_group *obj) : slab_obj(obj){}; void *allocate(u64 size, u64 align) override; void deallocate(void *ptr) override; }; } // namespace memory
24.390476
120
0.664975
[ "object" ]
1a524c5e3d3fc5765165ac1d7d8b0d07e22934bf
4,051
cc
C++
packages/CudaUtils/test/tstHost_Vector.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/CudaUtils/test/tstHost_Vector.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/CudaUtils/test/tstHost_Vector.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file CudaUtils/test/tstHost_Vector.cc * \author Seth R Johnson * \date Mon Aug 12 10:29:26 2013 * \brief * \note Copyright (C) 2013 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "../cuda_utils/Host_Vector.hh" #include "gtest/utils_gtest.hh" #include "../cuda_utils/Device_Vector.hh" #include "../cuda_utils/Hardware.hh" #include "utils/View_Field.hh" #include <config.h> #include "Polyglot_Kernel.cuh" //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// class HostVectorTest : public ::testing::Test { protected: typedef cuda::arch::Device Arch_t; typedef cuda::Device_Vector<Arch_t,float> Device_Vector_t; typedef std::vector<float> Vector_t; typedef cuda::Host_Vector<float> Host_Vector_t; typedef profugus::const_View_Field<float> const_View_Field_t; typedef profugus::View_Field<float> View_Field_t; protected: void SetUp() { #ifdef USE_CUDA typedef cuda::Hardware<Arch_t> Hardware_t; // Initialize device if (!Hardware_t::have_acquired()) { std::cout << "Acquiring device..." << std::flush; Hardware_t::acquire(); std::cout << "done." << std::endl; } INSIST(Hardware_t::have_acquired(), "Device could not be acquired."); #endif // Add values to the vector for (std::size_t i = 0; i < 63; ++i) { original.push_back(i * i); } } protected: Vector_t original; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST_F(HostVectorTest, accessors) { Host_Vector_t hv(original.size(), 1.23f); ASSERT_EQ(63, hv.size()); ASSERT_TRUE(!hv.empty()); EXPECT_FALSE(hv.is_mapped()); EXPECT_FALSE(hv.is_write_combined()); // Check default value and iterators for (Host_Vector_t::const_iterator it = hv.begin(), end_it = hv.end(); it != end_it; ++it) { EXPECT_FLOAT_EQ(1.23f, *it); } // Copy data hv.assign(profugus::make_view(original)); // Check equivalence and bracket accessors for (std::size_t i = 0; i < 63; ++i) { EXPECT_FLOAT_EQ(original[i], hv[i]); } } //---------------------------------------------------------------------------// // Mapped memory is only supported when CUDA is enabled TEST_F(HostVectorTest, mapped_memory) { #ifdef USE_CUDA // Create a "mapped memory, write-only" vector where assigning to the host // memory will automagically be copied to the GPU Host_Vector_t hv(original.size(), 0.f, cuda::alloc::MAPPED_WRITE_COMBINED); // Create blank destination vector Device_Vector_t gpu_out(original.size()); // Copy data hv.assign(profugus::make_view(original)); // Call kernel; the host wrapper uses the .data() accessor to extract the // GPU pointer polyglot_copy(hv, gpu_out); // Copy from device vector to new vector Vector_t result(original.size()); device_to_host(gpu_out, profugus::make_view(result)); // Check result for (std::size_t i = 0; i < original.size(); ++i) { EXPECT_FLOAT_EQ(original[i], result[i]) << "Failure at index " << i; } #else // No cuda, no mapped memory; INSIST should be raised EXPECT_THROW({Host_Vector_t hv(original.size(), 0.f, cuda::alloc::MAPPED_WRITE_COMBINED);}, profugus::assertion); #endif } //---------------------------------------------------------------------------// // end of tstHost_Vector.cc //---------------------------------------------------------------------------//
30.458647
79
0.515181
[ "vector" ]
1a528256946b1b489ebcbb67c54a2230d083b52f
2,226
cpp
C++
src/main/algorithms/cpp/dynamic-programming/decode_ways_91/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/dynamic-programming/decode_ways_91/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
src/main/algorithms/cpp/dynamic-programming/decode_ways_91/solution.cpp
algorithmlover2016/leet_code
2eecc7971194c8a755e67719d8f66c636694e7e9
[ "Apache-2.0" ]
null
null
null
#include "../../head.h" class Solution { public: int numDecodings(std::string const & s) { // plagiarizing from https://www.youtube.com/watch?v=_kg-U4j0gQg // Boundary conditions if (s.empty() || '0' == s[0]) { return 0; } int const sSize = s.size(); std::vector<int> dpMemo(sSize + 1, 0); // when s is empty, the solution is 1 way which means "" -> "" // when s is ["1"-"9"], the solution is 1 way dpMemo[0] = dpMemo[1] = 1; for (int idx = 2; idx < dpMemo.size(); idx++) { // if using one digit to form a solution, the digit can not be zero if ('0' != s[idx - 1]) { dpMemo[idx] = dpMemo[idx - 1]; } int val = std::stol(s.substr(idx - 2, 2)); if (val > LOW_BOARDER && val < UP_BOARDER) { dpMemo[idx] += dpMemo[idx - 2]; } } return dpMemo[sSize]; } private: static int const LOW_BOARDER = 9; static int const UP_BOARDER = 27; }; class SolutionOptimize { public: int numDecodings(std::string const & s) { // plagiarizing from https://www.youtube.com/watch?v=_kg-U4j0gQg // the if (s.empty()) { return 0; } int const sSize = s.size(); std::vector<int> dpMemo(sSize + 1, 0); // when s is empty, the solution is 1 way which means "" -> "" // when s is ["1"-"9"], the solution is 1 way, is s = "0", there is no way dpMemo[0] = 1; dpMemo[1] = '0' == s[0] ? 0 : 1; for (int idx = 2; idx < dpMemo.size(); idx++) { // if using one digit to form a solution, the digit can not be zero if ('0' != s[idx - 1]) { dpMemo[idx] = dpMemo[idx - 1]; } int val = std::stol(s.substr(idx - 2, 2)); #ifdef DEBUG std::cout << idx << "\t" << val << "\t"; #endif if (val > LOW_BOARDER && val < UP_BOARDER) { dpMemo[idx] += dpMemo[idx - 2]; } } return dpMemo[sSize]; } private: static int const LOW_BOARDER = 9; static int const UP_BOARDER = 27; };
31.8
82
0.482031
[ "vector" ]
1a58da2e01d493e42428e58a4dca20b7a93d85d5
705
cpp
C++
Interpolation/Test.cpp
kai156277/NumericalAnalysis
0a84badb3247f23b7b2604a2e85cd15727e03c26
[ "MIT" ]
null
null
null
Interpolation/Test.cpp
kai156277/NumericalAnalysis
0a84badb3247f23b7b2604a2e85cd15727e03c26
[ "MIT" ]
null
null
null
Interpolation/Test.cpp
kai156277/NumericalAnalysis
0a84badb3247f23b7b2604a2e85cd15727e03c26
[ "MIT" ]
null
null
null
#include "Interpolation.h" #include "gtest/gtest.h" TEST(Interpolation, lagrange_1) { std::vector<double> xs = {-1, 0, 1, 2}; std::vector<double> ys = {-7, -4, 5, 26}; double fx = lagrange(xs, ys, 0.5); EXPECT_DOUBLE_EQ(fx, -0.625); } TEST(Interpolation, lagrange_2) { std::vector<double> xs = {0.32, 0.34}; std::vector<double> ys = {0.314567, 0.333487}; double fx = lagrange(xs, ys, 0.3367); EXPECT_NEAR(fx, 0.330365, 0.92 * 1e-5); } TEST(Interpolation, lagrange_3) { std::vector<double> xs = {0.32, 0.34, 0.36}; std::vector<double> ys = {0.314567, 0.333487, 0.352274}; double fx = lagrange(xs, ys, 0.3367); EXPECT_NEAR(fx, 0.330374, 0.5 * 1e-5); }
23.5
60
0.604255
[ "vector" ]
1a5fc7ff40b168d110a52a3198bd2069ba20fe70
8,039
cpp
C++
eip/src/v3/model/ShareBandwidthTypeShowResp.cpp
huaweicloud/huaweicloud-sdk-cpp-v3
d3b5e07b0ee8367d1c7f6dad17be0212166d959c
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
eip/src/v3/model/ShareBandwidthTypeShowResp.cpp
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
null
null
null
eip/src/v3/model/ShareBandwidthTypeShowResp.cpp
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/eip/v3/model/ShareBandwidthTypeShowResp.h" namespace HuaweiCloud { namespace Sdk { namespace Eip { namespace V3 { namespace Model { ShareBandwidthTypeShowResp::ShareBandwidthTypeShowResp() { id_ = ""; idIsSet_ = false; bandwidthType_ = ""; bandwidthTypeIsSet_ = false; publicBorderGroup_ = ""; publicBorderGroupIsSet_ = false; createdAt_ = ""; createdAtIsSet_ = false; updatedAt_ = ""; updatedAtIsSet_ = false; nameEn_ = ""; nameEnIsSet_ = false; nameZh_ = ""; nameZhIsSet_ = false; description_ = ""; descriptionIsSet_ = false; } ShareBandwidthTypeShowResp::~ShareBandwidthTypeShowResp() = default; void ShareBandwidthTypeShowResp::validate() { } web::json::value ShareBandwidthTypeShowResp::toJson() const { web::json::value val = web::json::value::object(); if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(bandwidthTypeIsSet_) { val[utility::conversions::to_string_t("bandwidth_type")] = ModelBase::toJson(bandwidthType_); } if(publicBorderGroupIsSet_) { val[utility::conversions::to_string_t("public_border_group")] = ModelBase::toJson(publicBorderGroup_); } if(createdAtIsSet_) { val[utility::conversions::to_string_t("created_at")] = ModelBase::toJson(createdAt_); } if(updatedAtIsSet_) { val[utility::conversions::to_string_t("updated_at")] = ModelBase::toJson(updatedAt_); } if(nameEnIsSet_) { val[utility::conversions::to_string_t("name_en")] = ModelBase::toJson(nameEn_); } if(nameZhIsSet_) { val[utility::conversions::to_string_t("name_zh")] = ModelBase::toJson(nameZh_); } if(descriptionIsSet_) { val[utility::conversions::to_string_t("description")] = ModelBase::toJson(description_); } return val; } bool ShareBandwidthTypeShowResp::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("bandwidth_type"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("bandwidth_type")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setBandwidthType(refVal); } } if(val.has_field(utility::conversions::to_string_t("public_border_group"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("public_border_group")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setPublicBorderGroup(refVal); } } if(val.has_field(utility::conversions::to_string_t("created_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("created_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setCreatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("updated_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("updated_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setUpdatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("name_en"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name_en")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setNameEn(refVal); } } if(val.has_field(utility::conversions::to_string_t("name_zh"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name_zh")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setNameZh(refVal); } } if(val.has_field(utility::conversions::to_string_t("description"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("description")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDescription(refVal); } } return ok; } std::string ShareBandwidthTypeShowResp::getId() const { return id_; } void ShareBandwidthTypeShowResp::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool ShareBandwidthTypeShowResp::idIsSet() const { return idIsSet_; } void ShareBandwidthTypeShowResp::unsetid() { idIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getBandwidthType() const { return bandwidthType_; } void ShareBandwidthTypeShowResp::setBandwidthType(const std::string& value) { bandwidthType_ = value; bandwidthTypeIsSet_ = true; } bool ShareBandwidthTypeShowResp::bandwidthTypeIsSet() const { return bandwidthTypeIsSet_; } void ShareBandwidthTypeShowResp::unsetbandwidthType() { bandwidthTypeIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getPublicBorderGroup() const { return publicBorderGroup_; } void ShareBandwidthTypeShowResp::setPublicBorderGroup(const std::string& value) { publicBorderGroup_ = value; publicBorderGroupIsSet_ = true; } bool ShareBandwidthTypeShowResp::publicBorderGroupIsSet() const { return publicBorderGroupIsSet_; } void ShareBandwidthTypeShowResp::unsetpublicBorderGroup() { publicBorderGroupIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getCreatedAt() const { return createdAt_; } void ShareBandwidthTypeShowResp::setCreatedAt(const std::string& value) { createdAt_ = value; createdAtIsSet_ = true; } bool ShareBandwidthTypeShowResp::createdAtIsSet() const { return createdAtIsSet_; } void ShareBandwidthTypeShowResp::unsetcreatedAt() { createdAtIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getUpdatedAt() const { return updatedAt_; } void ShareBandwidthTypeShowResp::setUpdatedAt(const std::string& value) { updatedAt_ = value; updatedAtIsSet_ = true; } bool ShareBandwidthTypeShowResp::updatedAtIsSet() const { return updatedAtIsSet_; } void ShareBandwidthTypeShowResp::unsetupdatedAt() { updatedAtIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getNameEn() const { return nameEn_; } void ShareBandwidthTypeShowResp::setNameEn(const std::string& value) { nameEn_ = value; nameEnIsSet_ = true; } bool ShareBandwidthTypeShowResp::nameEnIsSet() const { return nameEnIsSet_; } void ShareBandwidthTypeShowResp::unsetnameEn() { nameEnIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getNameZh() const { return nameZh_; } void ShareBandwidthTypeShowResp::setNameZh(const std::string& value) { nameZh_ = value; nameZhIsSet_ = true; } bool ShareBandwidthTypeShowResp::nameZhIsSet() const { return nameZhIsSet_; } void ShareBandwidthTypeShowResp::unsetnameZh() { nameZhIsSet_ = false; } std::string ShareBandwidthTypeShowResp::getDescription() const { return description_; } void ShareBandwidthTypeShowResp::setDescription(const std::string& value) { description_ = value; descriptionIsSet_ = true; } bool ShareBandwidthTypeShowResp::descriptionIsSet() const { return descriptionIsSet_; } void ShareBandwidthTypeShowResp::unsetdescription() { descriptionIsSet_ = false; } } } } } }
24.584098
110
0.675457
[ "object", "model" ]
1a61329736dfb9585430b6db73724675d9a29ea5
2,840
cpp
C++
RabbitEngine/src/graphics/Shader.cpp
chasedig/RabbitEngine
e0d1613443713470741eee99631b518483504be6
[ "MIT" ]
4
2021-05-04T18:34:14.000Z
2021-05-05T18:09:56.000Z
RabbitEngine/src/graphics/Shader.cpp
chasedig/RabbitEngine
e0d1613443713470741eee99631b518483504be6
[ "MIT" ]
6
2021-05-05T17:47:15.000Z
2021-08-10T01:24:06.000Z
RabbitEngine/src/graphics/Shader.cpp
chasedig/RabbitEngine
e0d1613443713470741eee99631b518483504be6
[ "MIT" ]
1
2021-05-05T18:31:02.000Z
2021-05-05T18:31:02.000Z
#include "RBT/graphics/Shader.h" #include "glad/glad.h" #include <iostream> #include <fstream> #include <string> #include <vector> namespace RBT { const std::string SHADER_DIRECTORY_PATH = "shaders/"; const int INFO_LOG_BUFFER_SIZE = 2048; void createShader(std::string filename, int shaderId); std::string readShader(std::string filename); Shader::Shader(std::string vs_filename, std::string fs_filename) { program = glCreateProgram(); vs = glCreateShader(GL_VERTEX_SHADER); createShader(vs_filename, vs); fs = glCreateShader(GL_FRAGMENT_SHADER); createShader(fs_filename, fs); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); int linkSuccess; glGetProgramiv(program, GL_LINK_STATUS, &linkSuccess); if (!linkSuccess) { char infoLog[INFO_LOG_BUFFER_SIZE]; glGetProgramInfoLog(program, INFO_LOG_BUFFER_SIZE, NULL, infoLog); std::cout << "Shader linking error with program ID " << program << ": " << infoLog << std::endl; } } void Shader::bind() { glUseProgram(program); } void Shader::unbind() { glUseProgram(0); } int Shader::getUniformLocation(std::string name) { return glGetUniformLocation(this->program, &name[0]); } void Shader::setIntUniform(std::string name, int uniform) { glUniform1i(getUniformLocation(name), uniform); } void Shader::setFloatUniform(std::string name, float uniform) { glUniform1f(getUniformLocation(name), uniform); } void Shader::setMat4Uniform(std::string name, glm::mat4 uniform) { glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, glm::value_ptr(uniform)); } void Shader::setVec3Uniform(std::string name, glm::vec3 uniform) { glUniform3fv(getUniformLocation(name), 1, glm::value_ptr(uniform)); } void createShader(std::string filename, int shaderId) { std::string source = readShader(filename); const char* source_cstr = &source[0]; //const int* length = std::string::length(source); glShaderSource(shaderId, 1, &source_cstr, NULL); glCompileShader(shaderId); int compileSuccess; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compileSuccess); if (!compileSuccess) { char infoLog[INFO_LOG_BUFFER_SIZE]; glGetShaderInfoLog(shaderId, INFO_LOG_BUFFER_SIZE, NULL, infoLog); std::cout << "Shader compilation failed for '" << filename << "'" << " with error " << infoLog << std::endl; } } std::string readShader(std::string filename) { filename = SHADER_DIRECTORY_PATH + filename; std::string content = ""; try { std::ifstream shaderFile(filename); std::string line; while (std::getline(shaderFile, line)) { content = content + line + "\n"; } shaderFile.close(); return content; } catch (std::exception e) { std::cout << "Exception when reading shader: " << e.what() << std::endl; } return ""; } }
25.132743
111
0.703521
[ "vector" ]
2b3a4a75d4f22948f4836cf1113063e54287dd07
1,748
cpp
C++
Code/Projects/Eldritch/src/Screens/uiscreen-eldcredits.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
Code/Projects/Eldritch/src/Screens/uiscreen-eldcredits.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
Code/Projects/Eldritch/src/Screens/uiscreen-eldcredits.cpp
kas1e/Eldritch
032b4ac52f7508c89efa407d6fe60f40c6281fd9
[ "Zlib" ]
null
null
null
#include "core.h" #include "uiscreen-eldcredits.h" #include "Widgets/uiwidget-text.h" #include "configmanager.h" #include "mesh.h" UIScreenEldCredits::UIScreenEldCredits() {} UIScreenEldCredits::~UIScreenEldCredits() {} /*virtual*/ UIScreen::ETickReturn UIScreenEldCredits::Tick(float DeltaTime, bool HasFocus) { XTRACE_FUNCTION; STATIC_HASHED_STRING(CreditsText); UIWidgetText* const pCreditsText = GetWidget<UIWidgetText>(sCreditsText); ASSERT(pCreditsText); const float Bottom = pCreditsText->m_TopLeft.y + pCreditsText->m_Mesh->m_AABB.m_Max.z - pCreditsText->m_Mesh->m_AABB.m_Min.z; if (Bottom < 0.0f) { STATICHASH(DisplayHeight); const float DisplayHeight = ConfigManager::GetFloat(sDisplayHeight); const float ParentHeight = pCreditsText->m_OriginParent ? pCreditsText->m_OriginParent->GetHeight() : DisplayHeight; pCreditsText->m_TopLeft.y = ParentHeight; pCreditsText->UpdateRenderPosition(); } return UIScreen::Tick(DeltaTime, HasFocus); } /*virtual*/ void UIScreenEldCredits::Pushed() { UIScreen::Pushed(); STATIC_HASHED_STRING(CreditsText); UIWidgetText* const pCreditsText = GetWidget<UIWidgetText>(sCreditsText); ASSERT(pCreditsText); STATICHASH(DisplayHeight); const float DisplayHeight = ConfigManager::GetFloat(sDisplayHeight); const float ParentHeight = pCreditsText->m_OriginParent ? pCreditsText->m_OriginParent->GetHeight() : DisplayHeight; pCreditsText->m_TopLeft.y = ParentHeight; pCreditsText->UpdateRenderPosition(); }
34.27451
78
0.663616
[ "mesh" ]
2b4985672453f224239a32424174384f432cbb2e
5,399
cpp
C++
aegisub/src/subtitle_format_txt.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
1
2018-02-12T02:44:57.000Z
2018-02-12T02:44:57.000Z
aegisub/src/subtitle_format_txt.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
null
null
null
aegisub/src/subtitle_format_txt.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
2
2018-02-12T03:46:24.000Z
2018-02-12T14:36:07.000Z
// Copyright (c) 2006, Rodrigo Braz Monteiro // 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 Aegisub Group nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Aegisub Project http://www.aegisub.org/ /// @file subtitle_format_txt.cpp /// @brief Importing/exporting subtitles to untimed plain text /// @ingroup subtitle_io /// #include "config.h" #include "subtitle_format_txt.h" #include "ass_dialogue.h" #include "ass_file.h" #include "dialog_text_import.h" #include "options.h" #include "text_file_reader.h" #include "text_file_writer.h" #include "utils.h" #include "version.h" #include <libaegisub/of_type_adaptor.h> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/trim.hpp> TXTSubtitleFormat::TXTSubtitleFormat() : SubtitleFormat("Plain-Text") { } std::vector<std::string> TXTSubtitleFormat::GetReadWildcards() const { std::vector<std::string> formats; formats.push_back("txt"); return formats; } std::vector<std::string> TXTSubtitleFormat::GetWriteWildcards() const { return GetReadWildcards(); } bool TXTSubtitleFormat::CanWriteFile(agi::fs::path const& filename) const { auto str = filename.string(); return boost::iends_with(str, ".txt") && !(boost::iends_with(str, ".encore.txt") || boost::iends_with(str, ".transtation.txt")); } void TXTSubtitleFormat::ReadFile(AssFile *target, agi::fs::path const& filename, std::string const& encoding) const { DialogTextImport dlg; if (dlg.ShowModal() == wxID_CANCEL) return; TextFileReader file(filename, encoding, false); target->LoadDefault(false); std::string actor; std::string separator = OPT_GET("Tool/Import/Text/Actor Separator")->GetString(); std::string comment = OPT_GET("Tool/Import/Text/Comment Starter")->GetString(); // Parse file while (file.HasMoreLines()) { std::string value = file.ReadLineFromFile(); if (value.empty() && !OPT_GET("Tool/Import/Text/Include Blank")->GetBool()) continue; // Check if this isn't a timecodes file if (boost::starts_with(value, "# timecode")) throw SubtitleFormatParseError("File is a timecode file, cannot load as subtitles.", nullptr); // Read comment data bool isComment = false; if (!comment.empty() && boost::starts_with(value, comment)) { isComment = true; value.erase(0, comment.size()); } // Read actor data if (!isComment && !separator.empty() && !value.empty()) { if (value[0] != ' ' && value[0] != '\t') { size_t pos = value.find(separator); if (pos != std::string::npos) { actor = value.substr(0, pos); boost::trim(actor); value.erase(0, pos + 1); } } } // Trim spaces at start boost::trim_left(value); if (value.empty()) isComment = true; // Sets line up auto line = new AssDialogue; line->Actor = isComment ? std::string() : actor; line->Comment = isComment; line->Text = value; line->End = 0; target->Line.push_back(*line); } } void TXTSubtitleFormat::WriteFile(const AssFile *src, agi::fs::path const& filename, std::string const& encoding) const { size_t num_actor_names = 0, num_dialogue_lines = 0; // Detect number of lines with Actor field filled out for (auto dia : src->Line | agi::of_type<AssDialogue>()) { if (!dia->Comment) { num_dialogue_lines++; if (!dia->Actor.get().empty()) num_actor_names++; } } // If too few lines have Actor filled out, don't write it bool write_actors = num_actor_names > num_dialogue_lines/2; bool strip_formatting = true; TextFileWriter file(filename, encoding); file.WriteLineToFile(std::string("# Exported by Aegisub ") + GetAegisubShortVersionString()); // Write the file for (auto dia : src->Line | agi::of_type<AssDialogue>()) { std::string out_line; if (dia->Comment) out_line = "# "; if (write_actors) out_line += dia->Actor.get() + ": "; std::string out_text = strip_formatting ? dia->GetStrippedText() : dia->Text; out_line += out_text; if (!out_text.empty()) file.WriteLineToFile(out_line); } }
32.524096
129
0.712169
[ "vector" ]
2b4cac3079deaeaec37b412a4d7f13ee0d8c854e
2,632
cpp
C++
src/lr/coefficients.cpp
leinkemmer/Ensign
0b0321b136ded776b4dc653aa692f131f6c25a24
[ "MIT" ]
3
2022-03-03T12:40:36.000Z
2022-03-29T20:18:04.000Z
src/lr/coefficients.cpp
leinkemmer/Ensign
0b0321b136ded776b4dc653aa692f131f6c25a24
[ "MIT" ]
null
null
null
src/lr/coefficients.cpp
leinkemmer/Ensign
0b0321b136ded776b4dc653aa692f131f6c25a24
[ "MIT" ]
null
null
null
#include <lr/coefficients.hpp> template<class T> void coeff(const multi_array<T,2>& a, const multi_array<T,2>& b, T w, multi_array<T,2>& out, const blas_ops& blas) { blas.matmul_transa(a,b,out); if(a.sl == stloc::host){ out *= w; }else{ #ifdef __CUDACC__ ptw_mult_scal<<<(out.num_elements()+n_threads-1)/n_threads,n_threads>>>(out.num_elements(), out.begin(), w); #else cout << "ERROR: compiled without GPU support" << __FILE__ << ":" << __LINE__ << endl; exit(1); #endif } } template void coeff(const multi_array<double,2>& a, const multi_array<double,2>& b, double w, multi_array<double,2>& out, const blas_ops& blas); template void coeff(const multi_array<float,2>& a, const multi_array<float,2>& b, float w, multi_array<float,2>& out, const blas_ops& blas); template<class T> void coeff(const multi_array<T,2>& a, const multi_array<T,2>& b, const multi_array<T,1>& w, multi_array<T,2>& out, const blas_ops& blas) { multi_array<T,2> tmp(b.shape(),b.sl); if(b.sl == stloc::host){ ptw_mult_row(b,w,tmp); }else{ #ifdef __CUDACC__ ptw_mult_row_k<<<(b.num_elements()+n_threads-1)/n_threads,n_threads>>>(b.num_elements(), b.shape()[0], b.begin(), w.begin(), tmp.begin()); #else cout << "ERROR: compiled without GPU support" << __FILE__ << ":" << __LINE__ << endl; exit(1); #endif } blas.matmul_transa(a,tmp,out); } template void coeff(const multi_array<double,2>& a, const multi_array<double,2>& b, const multi_array<double,1>& w, multi_array<double,2>& out, const blas_ops& blas); template void coeff(const multi_array<float,2>& a, const multi_array<float,2>& b, const multi_array<float,1>&, multi_array<float,2>& out, const blas_ops& blas); template<class T> void integrate(const multi_array<T,2>& a, const multi_array<T,1>& w, multi_array<T,1>& out, const blas_ops& blas) { blas.matvec_trans(a,w,out); } template void integrate(const multi_array<double,2>& a, const multi_array<double,1>& w, multi_array<double,1>& out, const blas_ops& blas); template void integrate(const multi_array<float,2>& a, const multi_array<float,1>& w, multi_array<float,1>& out, const blas_ops& blas); template<class T> void integrate(const multi_array<T,2>& a, T w, multi_array<T,1>& out, const blas_ops& blas) { multi_array<T,1> vec({a.shape()[0]}, a.sl); set_const(vec,w); blas.matvec_trans(a,vec,out); } template void integrate(const multi_array<double,2>& a, double w, multi_array<double,1>& out, const blas_ops& blas); template void integrate(const multi_array<float,2>& a, float w, multi_array<float,1>& out, const blas_ops& blas);
43.866667
166
0.69035
[ "shape" ]
2b4e81af3acd616f8f5d7e3609093857a19f68b5
1,294
hh
C++
lib/spot-2.8.1/spot/kripke/fwd.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
1
2018-03-02T14:29:57.000Z
2018-03-02T14:29:57.000Z
lib/spot-2.8.1/spot/kripke/fwd.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
null
null
null
lib/spot-2.8.1/spot/kripke/fwd.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
1
2015-06-05T12:42:07.000Z
2015-06-05T12:42:07.000Z
// -*- coding: utf-8 -*- // Copyright (C) 2014, 2016 Laboratoire de Recherche et Développement de // l'Epita (LRDE). // // This file is part of Spot, a model checking library. // // Spot is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // Spot is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public // License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once #include <memory> namespace spot { class fair_kripke; typedef std::shared_ptr<fair_kripke> fair_kripke_ptr; typedef std::shared_ptr<const fair_kripke> const_fair_kripke_ptr; class kripke; typedef std::shared_ptr<kripke> kripke_ptr; typedef std::shared_ptr<const kripke> const_kripke_ptr; class kripke_explicit; typedef std::shared_ptr<const kripke_explicit> const_kripke_explicit_ptr; typedef std::shared_ptr<kripke_explicit> kripke_explicit_ptr; }
34.052632
75
0.755796
[ "model" ]
2b5b5f01fac3ea4d02e193c52855406612658086
1,635
cpp
C++
src/ThreadablesThreadObject.cpp
k2snowman69/threadily-sample-cpp
1b7f3dc36a8814f79383db84e31c799da8fc42e3
[ "MIT" ]
null
null
null
src/ThreadablesThreadObject.cpp
k2snowman69/threadily-sample-cpp
1b7f3dc36a8814f79383db84e31c799da8fc42e3
[ "MIT" ]
null
null
null
src/ThreadablesThreadObject.cpp
k2snowman69/threadily-sample-cpp
1b7f3dc36a8814f79383db84e31c799da8fc42e3
[ "MIT" ]
null
null
null
#include "ThreadablesThreadObject.h" #ifdef EMSCRIPTEN #include <ThreadObjectManager.h> #include <emscripten/bind.h> using namespace emscripten; #endif namespace threadily { namespace test { ThreadablesThreadObject::ThreadablesThreadObject(std::shared_ptr<IThreadObjectManager> objectManager, unsigned int threadId, const ThreadObjectId & id) : ThreadObject(objectManager, threadId, id) { emptyObject = std::make_shared<Observable<EmptyThreadObject>>(threadId); emptyObjectArray = std::make_shared<Observable<std::vector<EmptyThreadObject>>>(threadId); emptyObject->set(nullptr); } std::vector<std::shared_ptr<IObservable>> ThreadablesThreadObject::getObservableProperties() { auto d = std::vector<std::shared_ptr<IObservable>>(); d.push_back(emptyObject); d.push_back(emptyObjectArray); return d; } #ifdef EMSCRIPTEN EMSCRIPTEN_BINDINGS(ThreadablesThreadObjectManager) { class_<ThreadablesThreadObject, base<ThreadObject<>>>("ThreadablesThreadObject") .smart_ptr<std::shared_ptr<ThreadablesThreadObject>>("ThreadablesThreadObject") .property("emptyObject", &ThreadablesThreadObject::emptyObject) .property("emptyObjectArray", &ThreadablesThreadObject::emptyObjectArray) ; class_<ThreadObjectManager<ThreadablesThreadObject>, base<IThreadObjectManager>>("ThreadablesThreadObjectManager") .smart_ptr_constructor("ThreadablesThreadObjectManager", &std::make_shared<ThreadObjectManager<ThreadablesThreadObject>, std::shared_ptr<IThreadManager>>) .function("getOrCreateObject", &ThreadObjectManager<ThreadablesThreadObject>::getOrCreateObject) ; } #endif } }
38.023256
158
0.788379
[ "vector" ]
2b5ff83de9046a2bc82bed1c6faf430c4b464879
4,478
hpp
C++
RobWork/src/rwlibs/simulation/FrameGrabber25D.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rwlibs/simulation/FrameGrabber25D.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rwlibs/simulation/FrameGrabber25D.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RWLIBS_SIMULATION_FRAMEGRAPPER25D_HPP #define RWLIBS_SIMULATION_FRAMEGRAPPER25D_HPP /** * @file FrameGrabber.hpp */ #include <rw/core/Ptr.hpp> #include <rw/geometry/PointCloud.hpp> namespace rw { namespace kinematics { class Frame; }} // namespace rw::kinematics namespace rw { namespace kinematics { class State; }} // namespace rw::kinematics namespace rwlibs { namespace simulation { /** @addtogroup simulation */ /* @{ */ /** * @brief The FrameGrabber25D abstract interface, can be used to grab images from a * specialized source. */ class FrameGrabber25D { public: //! @brief Smart pointer type for FrameGrabber25D. typedef rw::core::Ptr< FrameGrabber25D > Ptr; /** * @brief constructor * @param width [in] width of the image that this FrameGrabber25D uses. * @param height [in] height of the image that this FrameGrabber25D uses. */ FrameGrabber25D (size_t width, size_t height) : _width (width), _height (height) { _img = new rw::geometry::PointCloud ((int) width, (int) height); } /** * @brief destructor */ virtual ~FrameGrabber25D () { delete _img; } /** * @brief returns the width of the image * @return the height of the image */ size_t getWidth () const { return _img->getWidth (); } /** * @brief returns the height of the image * @return the height of the image */ size_t getHeight () const { return _img->getHeight (); } /** * @brief Returns the field of view measured around the y-axis. * @return Field of view measured around y-axis in radians */ virtual double getFieldOfViewY () = 0; /** * @brief resizes the image that this frameGrabber use. The colorcode will * default to the one that FrameGrabber25D was initialized with. * @param width [in] width of image * @param height [in] height of image */ void resize (size_t width, size_t height) { delete _img; _width = width; _height = height; _img = new rw::geometry::PointCloud ((int) width, (int) height); }; /** * @brief returns the image * @return the image */ virtual rw::geometry::PointCloud& getImage () { return *_img; } /** * @brief this function grabs a image from the specialized source and * copies it to the FrameGrabber25D image. */ // virtual void grab(rw::kinematics::Frame *frame, // const rw::kinematics::State& state, // std::vector<rw::math::Vector3D<float> >* result) = 0; virtual void grab (rw::kinematics::Frame* frame, const rw::kinematics::State& state) = 0; /** * @brief maximum depth that this framegrabber can handle * @return maximum depth in meter */ virtual double getMaxDepth () = 0; /** * @brief minimum depth that this framegrabber can handle * @return minimum depth in meter */ virtual double getMinDepth () = 0; protected: //! @brief The image rw::geometry::PointCloud* _img; //! @brief Width of the image. size_t _width; //! @brief Height of the image. size_t _height; }; /* @} */ }} // namespace rwlibs::simulation #endif // end include guard
32.686131
97
0.575257
[ "geometry", "vector" ]
2b66515f507b708b5be6e1f23405098435491ace
617
cpp
C++
C++/remove-interval.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/remove-interval.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/remove-interval.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(1) class Solution { public: vector<vector<int>> removeInterval(vector<vector<int>>& intervals, vector<int>& toBeRemoved) { vector<vector<int>> result; for (const auto& interval : intervals) { vector<pair<int, int>> tmp = {{interval[0], min(toBeRemoved[0], interval[1])}, {max(interval[0], toBeRemoved[1]), interval[1]}}; for (const auto& [x, y] : tmp) { if (x < y) { result.push_back({x, y}); } } } return result; } };
30.85
98
0.470016
[ "vector" ]
2b67e79327dabe52e6d5432caeaf98fac57543a2
724
hpp
C++
pixel.hpp
RedByte0/RB-PIE
382ea44a6b1859f63399a4cc2d885ebc2cd01594
[ "Unlicense" ]
null
null
null
pixel.hpp
RedByte0/RB-PIE
382ea44a6b1859f63399a4cc2d885ebc2cd01594
[ "Unlicense" ]
null
null
null
pixel.hpp
RedByte0/RB-PIE
382ea44a6b1859f63399a4cc2d885ebc2cd01594
[ "Unlicense" ]
null
null
null
#ifndef PIXEL_HPP_ #define PIXEL_HPP_ #include <iostream> #include <vector> #include <numeric> //pie = ppm_image_editor namespace pie { class pixel { private: const int NUMBER_OF_COLOR_CHANNELS = 3; std::vector<int> rgb_; bool out_of_bounds(int channel) const; public: pixel(); pixel(const pixel& px); pixel(pixel&& px); pixel(std::vector<int>&& colors); ~pixel(); std::size_t size() {return rgb_.size();} float brightness(); pixel& operator=(const pixel& px); void operator=(pixel&& px); int & operator[](const int channel); const int & operator[](const int channel) const; bool operator==(const pixel& px) const; bool operator!=(const pixel& px) const; }; } #endif
20.685714
50
0.665746
[ "vector" ]
2b6df0bd5f4a4ae377a37be6392ed89066efdc12
10,270
cpp
C++
MMOCoreORB/src/server/zone/objects/creature/VehicleObjectImplementation.cpp
Voxxy-Flurry/SWGFlurry
9aeb11251e8c8e4307b51ec048ce007ac02685ba
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/objects/creature/VehicleObjectImplementation.cpp
Voxxy-Flurry/SWGFlurry
9aeb11251e8c8e4307b51ec048ce007ac02685ba
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/objects/creature/VehicleObjectImplementation.cpp
Voxxy-Flurry/SWGFlurry
9aeb11251e8c8e4307b51ec048ce007ac02685ba
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * VehicleObjectImplementation.cpp * * Created on: 10/04/2010 * Author: victor */ #include "server/zone/objects/creature/VehicleObject.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/Zone.h" #include "server/zone/objects/player/sui/listbox/SuiListBox.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/region/CityRegion.h" #include "server/zone/objects/region/Region.h" #include "server/zone/objects/creature/sui/RepairVehicleSuiCallback.h" #include "templates/customization/AssetCustomizationManagerTemplate.h" void VehicleObjectImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) { if (!player->getPlayerObject()->isPrivileged() && linkedCreature != player) return; menuResponse->addRadialMenuItem(205, 1, "@pet/pet_menu:menu_enter_exit"); menuResponse->addRadialMenuItem(61, 3, ""); if (player->getPlayerObject()->isPrivileged() || (checkInRangeGarage())) menuResponse->addRadialMenuItem(62, 3, "@pet/pet_menu:menu_repair_vehicle"); //Repair Vehicle } void VehicleObjectImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object){ alm->insertAttribute("armorrating", "@obj_attr_n:armor_pierce_none"); //None StringBuffer kin; kin << Math::getPrecision(getKinetic(),1) << "%"; alm->insertAttribute("cat_armor_special_protection.armor_eff_kinetic", kin.toString()); StringBuffer ene; ene << Math::getPrecision(getEnergy(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_energy", ene.toString()); StringBuffer bla; bla << Math::getPrecision(getBlast(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_blast", bla.toString()); StringBuffer stu; stu << Math::getPrecision(getStun(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_stun", stu.toString()); StringBuffer lig; lig << Math::getPrecision(getLightSaber(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_restraint", lig.toString()); StringBuffer hea; hea << Math::getPrecision(getHeat(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_heat", hea.toString()); StringBuffer col; col << Math::getPrecision(getCold(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_cold", col.toString()); StringBuffer aci; aci << Math::getPrecision(getAcid(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_acid", aci.toString()); StringBuffer ele; ele << Math::getPrecision(getElectricity(),1) << "%"; alm->insertAttribute("cat_armor_effectiveness.armor_eff_elemental_electrical", ele.toString()); ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if( linkedCreature == nullptr ) return; alm->insertAttribute("@obj_attr_n:owner", linkedCreature->getFirstName()); } void VehicleObjectImplementation::notifyInsertToZone(Zone* zone) { SceneObjectImplementation::notifyInsertToZone(zone); if( this->linkedCreature == nullptr ) return; ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if( linkedCreature == nullptr ) return; // Decay customized paint (if any) if (paintCount > 0){ // Paint starts to fade when there are 4 calls left if (paintCount <= 4){ // Send player notification of decay if( paintCount == 1 ){ linkedCreature->sendSystemMessage("@pet/pet_menu:customization_gone_veh"); // "Your vehicle's customization has completely faded away." } else{ linkedCreature->sendSystemMessage("@pet/pet_menu:customization_fading_veh"); // "Your vehicle's customization is fading away." } // Fade color to white String appearanceFilename = getObjectTemplate()->getAppearanceFilename(); VectorMap<String, Reference<CustomizationVariable*> > variables; AssetCustomizationManagerTemplate::instance()->getCustomizationVariables(appearanceFilename.hashCode(), variables, false); for(int i = 0; i< variables.size(); ++i){ String varkey = variables.elementAt(i).getKey(); if (varkey.contains("color")){ setCustomizationVariable(varkey, paintCount-1, true); // Palette values 3,2,1,0 are grey->white } } } --paintCount; } } bool VehicleObjectImplementation::checkInRangeGarage() { Reference<SceneObject*> garage = StructureManager::instance()->getInRangeParkingGarage(_this.getReferenceUnsafeStaticCast()); if (garage == nullptr) return false; return true; } int VehicleObjectImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) { if (selectedID == 61 && linkedCreature == player) { unlock(); try { ManagedReference<ControlDevice* > strongRef = controlDevice.get(); if (strongRef != nullptr) strongRef->storeObject(player); } catch (Exception& e) { } catch (...) { wlock(player); throw; } wlock(player); } else if (selectedID == 62) { repairVehicle(player); } return 0; } void VehicleObjectImplementation::sendMessage(BasePacket* msg) { ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if (linkedCreature != nullptr && linkedCreature->getParent().get() == _this.getReferenceUnsafeStaticCast()) linkedCreature->sendMessage(msg); else { #ifdef LOCKFREE_BCLIENT_BUFFERS if (!msg->getReferenceCount()) #endif delete msg; } } void VehicleObjectImplementation::repairVehicle(CreatureObject* player) { if (!player->getPlayerObject()->isPrivileged()) { //Need to check if they are city banned. ManagedReference<ActiveArea*> activeArea = getActiveRegion(); if (activeArea != nullptr && activeArea->isRegion()) { Region* region = cast<Region*>( activeArea.get()); ManagedReference<CityRegion*> gb = region->getCityRegion().get(); if (gb == nullptr) return; if (gb->isBanned(player->getObjectID())) { player->sendSystemMessage("@city/city:garage_banned"); //You are city banned and cannot use this garage. return; } if (getConditionDamage() == 0) { player->sendSystemMessage("@pet/pet_menu:undamaged_vehicle"); //The targeted vehicle does not require any repairs at the moment. return; } /* if (isDisabled()) { player->sendSystemMessage("@pet/pet_menu:cannot_repair_disabled"); //You may not repair a disabled vehicle. return; } */ if (!checkInRangeGarage()) { player->sendSystemMessage("@pet/pet_menu:repair_unrecognized_garages"); //Your vehicle does not recognize any local garages. Try again in a garage repair zone. return; } } } sendRepairConfirmTo(player); } void VehicleObjectImplementation::sendRepairConfirmTo(CreatureObject* player) { ManagedReference<SuiListBox*> listbox = new SuiListBox(player, SuiWindowType::GARAGE_REPAIR); listbox->setCallback(new RepairVehicleSuiCallback(getZoneServer())); listbox->setPromptTitle("@pet/pet_menu:confirm_repairs_t"); //Confirm Vehicle Repairs listbox->setPromptText("@pet/pet_menu:vehicle_repair_d"); //You have chosen to repair your vehicle. Please review the listed details and confirm your selection. listbox->setUsingObject(_this.getReferenceUnsafeStaticCast()); listbox->setCancelButton(true, "@cancel"); int repairCost = calculateRepairCost(player); int totalFunds = player->getBankCredits(); int tax = 0; ManagedReference<CityRegion*> city = getCityRegion().get(); if(city != nullptr && city->getGarageTax() > 0){ repairCost += repairCost * city->getGarageTax() / 100; } listbox->addMenuItem("@pet/pet_menu:vehicle_prompt " + getDisplayedName()); //Vehicle: listbox->addMenuItem("@pet/pet_menu:repair_cost_prompt " + String::valueOf(repairCost)); //Repair Cost: listbox->addMenuItem("@pet/pet_menu:total_funds_prompt " + String::valueOf(totalFunds)); //Total Funds Available: player->getPlayerObject()->addSuiBox(listbox); player->sendMessage(listbox->generateMessage()); } int VehicleObjectImplementation::calculateRepairCost(CreatureObject* player) { if (player->getPlayerObject()->isPrivileged()) return 0; int repairCost = getConditionDamage() * 4; if (isDisabled()) repairCost += 1000000; return repairCost; } int VehicleObjectImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, bool notifyClient, bool isCombatAction) { return TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, notifyClient, isCombatAction); } int VehicleObjectImplementation::inflictDamage(TangibleObject* attacker, int damageType, float damage, bool destroy, const String& xp, bool notifyClient, bool isCombatAction) { return TangibleObjectImplementation::inflictDamage(attacker, damageType, damage, destroy, xp, notifyClient, isCombatAction); } int VehicleObjectImplementation::healDamage(TangibleObject* healer, int damageType, int damage, bool notifyClient) { return TangibleObjectImplementation::healDamage(healer, damageType, damage, notifyClient); } int VehicleObjectImplementation::notifyObjectDestructionObservers(TangibleObject* attacker, int condition, bool isCombatAction) { unlock(); ManagedReference<CreatureObject* > linkedCreature = this->linkedCreature.get(); if (linkedCreature != nullptr) { if (!isDisabled()) linkedCreature->sendSystemMessage("@pet/pet_menu:veh_disabled"); try { if (attacker != _this.getReferenceUnsafeStaticCast()) { Locker clocker(linkedCreature, attacker); linkedCreature->updateCooldownTimer("mount_dismount", 0); linkedCreature->executeObjectControllerAction(STRING_HASHCODE("dismount")); } else { Locker locker(linkedCreature); linkedCreature->updateCooldownTimer("mount_dismount", 0); linkedCreature->executeObjectControllerAction(STRING_HASHCODE("dismount")); } } catch (Exception& e) { } } if (attacker != _this.getReferenceUnsafeStaticCast()) wlock(attacker); else wlock(); return CreatureObjectImplementation::notifyObjectDestructionObservers(attacker, condition, false); } bool VehicleObject::isVehicleObject() { return true; } bool VehicleObjectImplementation::isVehicleObject() { return true; }
34.695946
176
0.751996
[ "object" ]
2b6f3201defd260216368da7503404e0157d5484
3,555
hpp
C++
src/Mesh.hpp
liminchen/DOT
26525fba815fb081e90676321e42d0a60ecb0cb1
[ "MIT" ]
29
2019-11-27T00:43:07.000Z
2020-02-25T14:35:54.000Z
src/Mesh.hpp
liminchen/DOT
26525fba815fb081e90676321e42d0a60ecb0cb1
[ "MIT" ]
null
null
null
src/Mesh.hpp
liminchen/DOT
26525fba815fb081e90676321e42d0a60ecb0cb1
[ "MIT" ]
4
2019-11-27T05:19:03.000Z
2020-03-23T22:49:53.000Z
// // Mesh.hpp // DOT // // Created by Minchen Li on 8/30/17. // #ifndef Mesh_hpp #define Mesh_hpp #include <Eigen/Eigen> #include <igl/massmatrix.h> #include <set> #include <array> #include "Types.hpp" namespace DOT{ enum Primitive { P_GRID, P_SQUARE, P_RECTANGLE, P_SPIKES, P_SHARKEY, P_CYLINDER, P_INPUT }; // duplicate the vertices and edges of a mesh to separate its triangles, // adjacent triangles in the original mesh will have a cohesive edge structure to // indicate the connectivity template<int dim> class Mesh{ public: // owned data Eigen::MatrixXd V_rest; // duplicated rest vertex coordinates in 3D Eigen::MatrixXd V; // duplicated vertex coordinates, the dimension depends on the search space Eigen::MatrixXi F; // reordered triangle draw list (0, 1, 2, ...), indices based on V public: // owned features Eigen::SparseMatrix<double> massMatrix; // V.rows() wide double density, m_YM, m_PR; Eigen::VectorXd u, lambda; Eigen::VectorXd triArea; // triangle rest area double surfaceArea; double avgEdgeLen; std::set<int> fixedVert; // for linear solve std::vector<bool> isFixedVert; Eigen::Matrix<double, 2, 3> bbox; Eigen::VectorXd triWeight; // for weighted stencil std::vector<std::vector<int>> borderVerts_primitive; std::vector<Eigen::Matrix<double, dim, dim>> restTriInv; std::vector<bool> m_isBoundaryVert; // indices for fast access std::vector<std::set<int>> vNeighbor; std::vector<std::set<std::pair<int, int>>> vFLoc; public: // constructor // default constructor that doesn't do anything Mesh(void); // initialize from a triangle mesh, V will be constructed from UV_mesh in 2D, // V_mesh will be used to initialize restShape Mesh(const Eigen::MatrixXd& V_mesh, const Eigen::MatrixXi& F_mesh, const Eigen::MatrixXd& Vt_mesh, double YM, double PR, double rho); Mesh(Primitive primitive, double size, int elemAmt, double YM, double PR, double rho); public: // API void computeMassMatrix(const igl::MassMatrixType type = igl::MASSMATRIX_TYPE_VORONOI); void computeFeatures(bool multiComp = false, bool resetFixedV = false); void resetFixedVert(const std::set<int>& p_fixedVert = std::set<int>()); void addFixedVert(int vI); void addFixedVert(const std::vector<int>& p_fixedVert); void removeFixedVert(int vI); void setLameParam(double YM, double PR); bool checkInversion(int triI, bool mute) const; bool checkInversion(bool mute = false, const std::vector<int>& triangles = std::vector<int>()) const; void saveAsMesh(const std::string& filePath, bool scaleUV = false, const Eigen::MatrixXi& SF = Eigen::MatrixXi()) const; void constructSubmesh(const Eigen::VectorXi& triangles, Mesh& submesh, std::map<int, int>& globalVIToLocal, std::map<int, int>& globalTriIToLocal) const; public: // helper function bool isBoundaryVert(int vI) const; void computeBoundaryVert(const Eigen::MatrixXi& SF); }; } #endif /* Mesh_hpp */
34.182692
109
0.602532
[ "mesh", "vector", "3d" ]
2b75166fc18ebbd9e88f6ed284a1ad47f3801135
8,941
cpp
C++
python/detectionAlgorithm/main.cpp
NunoDuarte/openCVdevelop
43204a903a3c96758332a86c7d6b10c285d6ed37
[ "MIT" ]
null
null
null
python/detectionAlgorithm/main.cpp
NunoDuarte/openCVdevelop
43204a903a3c96758332a86c7d6b10c285d6ed37
[ "MIT" ]
null
null
null
python/detectionAlgorithm/main.cpp
NunoDuarte/openCVdevelop
43204a903a3c96758332a86c7d6b10c285d6ed37
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <thread> // std::thread #include <vector> #include <unistd.h> #include "lsl_cpp.h" #include "json.hpp" #include "yarp/os/all.h" //#define LSL_OT #define LSL_PL1 #define LSL_PL1YARP //#define LSL_PL2 using namespace std; using namespace yarp::os; // for convenience using json = nlohmann::json; time_t rawtime; unsigned int microseconds; double sample_ot[15]; string sample_pl1; string sample_pl1yarp; string sample_pl2; std::string strtse01 = "-1"; std::string strtse11 = "-1"; std::string strtse02 = "-1"; std::string strtse12 = "-1"; char ot_new_data_ready=0; char pl1_new_data_ready=0; char pl2_new_data_ready=0; char pl1yarp_new_data_ready=0; void optitrack_capture() { #ifdef LSL_OT double ts_ot,old_timestamp; string file_name_ot; ofstream sample_ot_file; sample_ot_file.precision(17); vector<lsl::stream_info> results = lsl::resolve_stream("name","MyOptitrack"); lsl::stream_inlet inlet_ot(results[0]); file_name_ot = "samples_ot"; file_name_ot.append(ctime (&rawtime)); file_name_ot.append(".csv"); sample_ot_file.open (file_name_ot.c_str()); while(1) { //sample_ot_file.open ("test_ot2pl.csv"); ts_ot = inlet_ot.pull_sample(sample_ot,15,0.009); if(sample_ot[0]!=old_timestamp) { old_timestamp = sample_ot[0]; for (unsigned c=0;c<15;c++) { //cout << "\t" << sample_ot[c]; sample_ot_file << sample_ot[c]; sample_ot_file <<","; } sample_ot_file << endl; //cout << endl; ot_new_data_ready = 1; } } sample_ot_file.close(); #else while(1) ot_new_data_ready = 1; #endif } void ReplaceStringInPlace(std::string& subject, const std::string& search, const std::string& replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } } void pl1_capture() { #ifdef LSL_PL1 double ts_pl1; float sample[3]; ofstream sample_pl1_file; const char *channels[] = {"TS","Nx","Ny"}; std::size_t found, foundtse0, foundtse1, foundtse2, foundcfe0, foundcfe1, foundcfe2; string name = "NormPose2IP"; string type = "Gaze Norm pose"; lsl::stream_info info(name,type,3,100,lsl::cf_float32,string(name)+=type); info.desc().append_child_value("manufacturer", "Vislab"); lsl::xml_element chns = info.desc().append_child("channels"); chns.append_child("channel").append_child_value("label",channels[0]).append_child_value("unit","sec").append_child_value("type","timestamp"); chns.append_child("channel").append_child_value("label",channels[1]).append_child_value("unit","NA").append_child_value("type","normpose_x"); chns.append_child("channel").append_child_value("label",channels[2]).append_child_value("unit","NA").append_child_value("type","normpose_y"); lsl::stream_outlet outlet(info); json j_obj; vector<lsl::stream_info> results = lsl::resolve_stream("name","Gaze Python Representation"); lsl::stream_inlet inlet_pl1(results[0]); while(1) { ts_pl1 = inlet_pl1.pull_sample(&sample_pl1,1,0.009);//wait up to 9ms ReplaceStringInPlace(sample_pl1, "0:", "'0':"); ReplaceStringInPlace(sample_pl1, "1:", "'1':"); std::replace( sample_pl1.begin(), sample_pl1.end(), '\'', '"'); // replace all 'x' to 'y' if(sample_pl1.length()>1)//if within 9ms data from glasses arrived { j_obj = json::parse(sample_pl1); pl1_new_data_ready = 1; sample[0] = (float)(j_obj["timestamp"].get<double>()); sample[1] = (float)(j_obj["norm_pos"][0].get<double>()); sample[2] = (float)(j_obj["norm_pos"][1].get<double>()); outlet.push_sample(sample); } } #else while(1) pl1_new_data_ready = 1; #endif } void pl1_yarp() { #ifdef LSL_PL1YARP double ts_pl1; Network yarp; BufferedPort<Bottle> port; double result_input[4]; float input_str[4]; Bottle& output = port.prepare(); port.open("/pupil_gaze_tracker"); vector<lsl::stream_info> results = lsl::resolve_stream("name","GazePose"); lsl::stream_inlet inlet_plyarp(results[0]); try { while(1) { pl1_new_data_ready = 1; ts_pl1 = inlet_plyarp.pull_sample(input_str,4); output = port.prepare(); output.clear(); output.addDouble(input_str[0]); output.addDouble(input_str[1]); output.addDouble(input_str[2]); output.addDouble(input_str[3]); port.write(); } } catch(std::exception &e) { cerr << "Got an exception: " << e.what() << endl; } #else while(1) pl1yarp_new_data_ready = 1; #endif } void pl2_capture() { #ifdef LSL_PL2 double ts_pl2; ofstream sample_pl_file2; string file_name_pl2; char input_str2[10000]; double ts_e02,ts_e12; std::size_t found2, foundtse02, foundtse12, foundcfe02, foundcfe12; sample_pl_file2.precision(17); vector<lsl::stream_info> results = lsl::resolve_stream("name","Gaze Python Representation"); lsl::stream_inlet inlet_pl2(results[1]); file_name_pl2 = "samples_pl2"; file_name_pl2.append(ctime (&rawtime)); file_name_pl2.append(".csv"); sample_pl_file2.open (file_name_pl2.c_str()); while(1) { ts_pl2 = inlet_pl2.pull_sample(&sample_pl2,1,0.008334); cout << "got: " << sample_pl2 << endl; sample_pl_file2 << sample_pl2 << endl; if(sample_pl2.length()>1000) { found2 = sample_pl2.find("'timestamp': "); foundtse02 = sample_pl2.find("'timestamp': ",found2+1)+12; foundcfe02 = sample_pl2.find(", 'projected_sphere':",foundtse02+1)-1; foundtse12 = sample_pl2.find("'timestamp': ",foundcfe02+1)+12; foundcfe12 = sample_pl2.find(", 'projected_sphere':",foundtse12+1)-1; if(foundtse02<foundcfe02 && foundtse12<foundcfe12) { strtse02 = sample_pl2.substr(foundtse02+1,13); strtse12 = sample_pl2.substr(foundtse12+1,13); } } pl2_new_data_ready = 1; } sample_pl2_file.close(); #else while(1) pl2_new_data_ready = 1; #endif } int main(int argc, char *argv[]) { std::vector<std::thread> threads; cout.precision(17); cout << "Here is a one-shot resolve of all current streams:" << endl; // discover all streams on the network vector<lsl::stream_info> results_all = lsl::resolve_streams(); // display them cout << "Display all resolved streams: " << endl; for (unsigned k=0;k<results_all.size();k++) cout << results_all[k].as_xml() << endl << endl; cout << "Now creating the inlet..." << endl; time(&rawtime); ofstream sample_file; string file_name; sample_file.precision(17); file_name = "samples_"; file_name.append(ctime (&rawtime)); file_name.append(".csv"); sample_file.open(file_name.c_str()); threads.push_back(std::thread(optitrack_capture)); threads.push_back(std::thread(pl1_capture)); threads.push_back(std::thread(pl1_yarp)); threads.push_back(std::thread(pl2_capture)); sample_file <<"header"; sample_file <<strtse11; sample_file <<","; sample_file <<strtse02; sample_file <<","; sample_file <<strtse12; sample_file << endl; long int sample = 0; while(1) { time(&rawtime); if(ot_new_data_ready && pl1_new_data_ready && pl1yarp_new_data_ready && pl2_new_data_ready) { ot_new_data_ready = 0; pl1_new_data_ready = 0; pl1yarp_new_data_ready = 0; pl2_new_data_ready = 0; for (unsigned c=0;c<11;c++) { //cout << "\t" << sample_ot[c]; sample_file << sample_ot[c]; sample_file <<","; } cout << ++sample << endl; sample_file <<strtse01; sample_file <<","; sample_file <<strtse11; sample_file <<","; sample_file <<strtse02; sample_file <<","; sample_file <<strtse12; sample_file << endl; } } sample_file.close(); for(auto& thread : threads){ thread.join(); } return 0; }
27.259146
147
0.587071
[ "vector" ]
2b8c8e077266c3c35da994c0765698601d37139b
2,804
hpp
C++
evias/tests/regularExpressions/boostRegex.hpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
1
2015-10-31T03:18:02.000Z
2015-10-31T03:18:02.000Z
evias/tests/regularExpressions/boostRegex.hpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
null
null
null
evias/tests/regularExpressions/boostRegex.hpp
evias/evias
5b5d4c16404f855c3234afa05b11c339a3ebb4cb
[ "BSD-3-Clause" ]
null
null
null
#ifndef __EVIAS_CORE_TEST_REGULAREXPRESSIONS_NS_BOOSTREGEX__ #define __EVIAS_CORE_TEST_REGULAREXPRESSIONS_NS_BOOSTREGEX__ /** * Package : eVias unitary test suite * * Copyright (c) 2010 - 2011 Grégory Saive * * For more informations about the licensing of this product, please refer * to the LICENCE file in the root application directory. * * Version: 1.0 */ #include <iostream> #include <string> #include <vector> #include <map> #include <boost/regex.hpp> #include "core/unit_test_abstract.hpp" namespace evias { namespace core { namespace test { namespace regularExpressions { using evias::core::intToString; class boostRegex : public unitTest { public : boostRegex () : unitTest () { }; ~boostRegex () {}; inline void prepare () { setReturnCode((int) RETURN_SUCCESS); } inline int execute () { if (! (bool) _returnCode) return _returnCode; // test easy match boost::regex expr("^EVS([A-Za-z0-9_]{3})+$"); boost::cmatch what; assertable<bool>::assertEqual(boost::regex_match("EVS0056_3", what, expr), true); // test match with subexpressions expr.assign(boost::regex("^(?<group_name>[ABC]{2})(?<user_id>[0-9]+)$")); boost::cmatch matches; assertable<bool>::assertEqual(boost::regex_match("AB092100", matches, expr), true); // iterate matches and test values for (int i = 0; i < matches.size(); i++) { string match(matches[i].first, matches[i].second); switch (i) { case 0: assertable<string>::assertEqual(match, "AB092100"); break; case 1: assertable<string>::assertEqual(match, "AB"); break; case 2: assertable<string>::assertEqual(match, "092100"); break; default : return setReturnCode((int) ERROR_EXTERNAL_UPDATE); } } boost::smatch m; assertable<bool>::assertEqual(boost::regex_match(string("CC092100"), m, expr), true); return setReturnCode((int) RETURN_SUCCESS); } inline int shutdown () { return _returnCode; } }; }; // end namespace regularExpressions }; // end namespace test }; // end namespace core }; // end namespace evias #endif
26.45283
101
0.508203
[ "vector" ]
2b931476dd6a3ff2eb88ffdc27f79668ac6bef84
7,661
cpp
C++
src/writer/Writer.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
3
2018-02-26T19:53:46.000Z
2021-05-05T10:06:52.000Z
src/writer/Writer.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
1
2018-07-03T14:38:15.000Z
2018-07-09T19:06:01.000Z
src/writer/Writer.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
1
2019-03-28T03:02:07.000Z
2019-03-28T03:02:07.000Z
#include <mpi.h> #include <string> #include <memory> #include <vector> #include <iostream> #include <iomanip> #include <fstream> #include <chrono> // now() #include <ctime> //ctime() #include <cmath> //PI #include "debug.hpp" #include "floatWriter.hpp" #include "intWriter.hpp" #include "Config.hpp" #include "version.hpp" using namespace std; Writer::Writer(Config::ptr conf) { this->conf = conf; file_opened=false; } Writer::ptr Writer::get(Config::ptr &conf) { if ( (conf->kernel == Config::histogram) or (conf->kernel == Config::rdf)) { return make_shared<intWriter>(conf); } else if ( (conf->kernel == Config::omega) or (conf->kernel == Config::msid)) { return make_shared<floatWriter>(conf); } else { cerr << "Error! Writer not fully set up for this kernel!" << endl; cerr << "Kernel: " << conf->KernelMap[conf->kernel] << endl; LOC(); MPI::Finalize(); exit(EXIT_FAILURE); } } void Writer::write(bool vertical,bool reset) { if (not vertical) { writeHorizontal(reset); } else { writeVertical(reset); } } void Writer::writeVertical(bool reset) { gather(); // fill vecMaster with data from all procs if (conf->isRoot()) { buildCoeff(); float cutoff; if ( conf->kernel == Config::histogram or conf->kernel == Config::rdf) { cutoff = box[0]/(step_count*2.0); cout << "--> Cutting off data at lx/2.0 = " << cutoff << endl; } else { cutoff = conf->xmax; cout << "--> Using full data range with xmax = " << cutoff << endl; } int width=15; ofstream file(conf->output_file->path.string()); file << "#"; file << setw(width-1)<< "x"; file << setw(width) << conf->KernelMap[conf->kernel]; file << endl; for (int i=0;i<conf->xsize;i++) { float x = i*conf->dx; if (x<=cutoff) { file << setw(width) << x; file << setw(width) << vecMaster[i]*coeffMult[i] + coeffAdd[i]; file << endl; } } file.close(); } MPI::COMM_WORLD.Barrier(); if (reset) this->reset(); //reset counters and arrays } void Writer::writeHeader(float cutoff) { ofstream file(conf->output_file->path.string()); time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now()); string date = ctime(&now); int gcc_major = __GNUC__; int gcc_minor = __GNUC_MINOR__; int gcc_patch = __GNUC_PATCHLEVEL__; int boost_major = BOOST_VERSION/100000; int boost_minor = BOOST_VERSION/100 % 1000; int boost_patch = BOOST_VERSION % 1000; int ompi_major = OMPI_MAJOR_VERSION; int ompi_minor = OMPI_MINOR_VERSION; int ompi_patch = OMPI_RELEASE_VERSION; file << "# --------------------------------------------------------------------------" << endl; file << "# >>> CORRELATE <<<" << endl; file << "# --------------------------------------------------------------------------" << endl; file << "# ==> Correlate Version: " << version << endl; file << "# ==> GCC Version: " << gcc_major << "." << gcc_minor << "."<< gcc_patch << endl; file << "# ==> Boost Version: " << boost_major << "." << boost_minor << "."<< boost_patch << endl; file << "# ==> OpenMPI Version: " << ompi_major << "." << ompi_minor << "."<< ompi_patch << endl; file << "# ==> Build Date: " << build_date << endl; file << "# ==> File Creation: " << date; // date already has newline file << "# --------------------------------------------------------------------------" << endl; file << "# topo file = " << conf->topo_file->path << endl; file << "# trj file = " << conf->trj_file->path << endl; file << "# output file = " << conf->output_file->path << endl; file << "# output freq = " << conf->output_freq << endl; file << "# overwrite = " << boolalpha<<conf->overwrite<< endl; file << "# type1 = " << conf->type1 << endl; file << "# type2 = " << conf->type2 << endl; file << "# natoms1 = " << conf->natoms1 << endl; file << "# natoms2 = " << conf->natoms2 << endl; file << "# frame_start = " << conf->frame_start << endl; file << "# frame_end = " << conf->frame_end << endl; file << "# frame_step = " << conf->frame_step << endl; file << "# dx = " << conf->dx << endl; file << "# xmax = " << conf->xmax << endl; file << "# xsize = " << conf->xsize << endl; file << "# selfHist = " << boolalpha<<conf->selfHist << endl; file << "# kernel = " << conf->Config::KernelMap[conf->kernel] << endl; file << "# intra = " << boolalpha<<conf->intra << endl; file << "# inter = " << boolalpha<<conf->inter << endl; file << "# --------------------------------------------------------------------------" << endl; file << "# --> First row below is the grid bin edges (either fourier or real space)" << endl; file << "# --> Subsequent rows are data chunks calculated over output_freq timesteps" << endl; file << "# --------------------------------------------------------------------------" << endl; for (int i=0;i<conf->xsize;i++) { float x = ((i+1)*conf->dx); if (x<=cutoff) { file << x << " "; } } file << endl; } void Writer::writeHorizontal(bool reset) { gather(); // fill vecMaster with data from all procs if (conf->isRoot()) { buildCoeff(); float cutoff; if ( conf->kernel == Config::histogram or conf->kernel == Config::rdf) { cutoff = box[0]/(step_count*2.0); cout << "--> Cutting off data at lx/2.0 = " << cutoff << endl; } else { cutoff = conf->xmax; cout << "--> Using full data range with xmax = " << cutoff << endl; } if (not file_opened) { if (not (conf->output_file->exists())) { writeHeader(cutoff); } else if ((conf->overwrite) and (conf->output_file->exists())) { writeHeader(cutoff); } file_opened = true; } ofstream file(conf->output_file->path.string(),std::ofstream::app); for (int i=0;i<conf->xsize;i++) { float x = ((i+1)*conf->dx); float value = (vecMaster[i]*coeffMult[i] + coeffAdd[i]); if (x<=cutoff) { file << value << " "; } } file << endl; file.close(); } MPI::COMM_WORLD.Barrier(); if (reset) this->reset(); //reset counters and arrays } void Writer::buildCoeff() { float tot_natoms; if (conf->selfHist) { tot_natoms = conf->natoms1; } else { tot_natoms = conf->natoms1+conf->natoms2; } // process incremental box data pair_count_master /= step_count; float lx = box[0]/step_count; float ly = box[1]/step_count; float lz = box[2]/step_count; float box_volume = lx*ly*lz; float pair_rho = pair_count_master/box_volume; coeffAdd.assign(conf->xsize,0.0f); coeffMult.assign(conf->xsize,1.0f); for (int i=0;i<conf->xsize;i++) { if (conf->kernel == Config::histogram) { coeffMult[i]*=(1.0/(step_count)); } else if (conf->kernel == Config::msid) { int fac = 2*((conf->xsize)-i-1); coeffMult[i]*=(1.0/(step_count*fac)); } else if (conf->kernel == Config::rdf) { float x1 = (i*conf->dx); float x2 = ((i+1)*conf->dx); float vol = ((4.0/3.0) * M_PI * (x2*x2*x2 - x1*x1*x1)); coeffMult[i]*=(1.0/(step_count*vol*pair_rho)); } else if ( conf->kernel == Config::omega) { float x2 = ((i+1)*conf->dx); if (conf->selfHist) coeffAdd[i] += 1.0; coeffMult[i]*=(1.0/(step_count*tot_natoms*x2)); } } }
33.600877
104
0.524736
[ "vector" ]
2b9758e77d4e3597fa701c2cdc9e20088ae570c5
16,414
hh
C++
mesh3D_dirs_STD_SET.hh
gmanzini-LANL/PDE-Mesh-Manager
f3193f4be25043b1976503af3fe4b130153bac2d
[ "BSD-3-Clause" ]
null
null
null
mesh3D_dirs_STD_SET.hh
gmanzini-LANL/PDE-Mesh-Manager
f3193f4be25043b1976503af3fe4b130153bac2d
[ "BSD-3-Clause" ]
null
null
null
mesh3D_dirs_STD_SET.hh
gmanzini-LANL/PDE-Mesh-Manager
f3193f4be25043b1976503af3fe4b130153bac2d
[ "BSD-3-Clause" ]
null
null
null
/* ----------------------------------------------------------------/ This is open source software; you can redistribute it and/or modify it under the terms of the BSD-3 License. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL. Full text of the BSD-3 License can be found in the License file of the repository. /---------------------------------------------------------------- */ #ifndef _MESH_DIRS #define _MESH_DIRS const int TETGEN_FMT = 0 ; const int REGN_FACE_FMT = 1 ; class MeshDirsBase { protected: int fmt_flag ; string mesh_dir ; string mesh_name ; int vec_size ; vector<int> vec_offset ; vector<string> vec_fname ; public: MeshDirsBase( int _vec_size ) : vec_size (_vec_size), fmt_flag (-1), mesh_dir ("<undefined>"), mesh_name("<undefined>") { vec_offset.resize( vec_size ) ; vec_fname .resize( vec_size ) ; for ( int i=0; i<vec_size; ++i ) { vec_offset[i] = 0 ; vec_fname [i] = string("<undefined>") ; } } ; ~MeshDirsBase() {} ; virtual void setup() = 0 ; int get_offset( int ifile ) { PRT(ifile) ; assert( 0<=ifile && ifile<vec_size ) ; return vec_offset[ifile] ; } string get_fname( int ifile ) { assert( 0<=ifile && ifile<vec_size ) ; string retval = mesh_dir ; switch ( fmt_flag ) { case TETGEN_FMT: retval += string("TG_fmt/") ; break ; case REGN_FACE_FMT: retval += string("RF_fmt/") ; break ; default: assert(false) ; } retval += vec_fname[ifile] ; return retval ; } int get_fmt_flag () { return fmt_flag ; } string get_mesh_dir () { return mesh_dir ; } string get_mesh_name() { return mesh_name ; } string get_mesh_file( int ifile ) { return vec_fname[ifile] ; } } ; // -------------------------------------------------------------------------------------------- // mesh index 0 // -------------------------------------------------------------------------------------------- class Mesh_Cube_Tetrahedra_2 : public MeshDirsBase { public: Mesh_Cube_Tetrahedra_2() : MeshDirsBase(6) { setup() ; } ~Mesh_Cube_Tetrahedra_2() {} virtual void setup() { // mesh fmt_flag = TETGEN_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/CUBE-test-0/") ; mesh_name = string("Cube - Tetrahedra") ; vec_fname[0] = string("cube.1") ; vec_fname[1] = string("cube.2") ; vec_fname[2] = string("cube.3") ; vec_fname[3] = string("cube.4") ; vec_fname[4] = string("cube.5") ; vec_fname[5] = string("cube.6") ; for ( int i=0; i<vec_offset.size(); ++i ) { vec_offset[i] = 1 ; } } } ; class Mesh_Cube_Tetrahedra_1 : public MeshDirsBase { public: Mesh_Cube_Tetrahedra_1() : MeshDirsBase(5) { setup() ; } ~Mesh_Cube_Tetrahedra_1() {} virtual void setup() { // mesh fmt_flag = TETGEN_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Tetgen-Cube-1/") ; mesh_name = string("Cube - Tetrahedra") ; vec_fname[0] = string("cube.1") ; vec_fname[1] = string("cube.2") ; vec_fname[2] = string("cube.3") ; vec_fname[3] = string("cube.4") ; vec_fname[4] = string("cube.5") ; for ( int i=0; i<vec_offset.size(); ++i ) { vec_offset[i] = 1 ; } } } ; class Mesh_Cube_Tetrahedra_0 : public MeshDirsBase { public: Mesh_Cube_Tetrahedra_0() : MeshDirsBase(6) { setup() ; } ~Mesh_Cube_Tetrahedra_0() {} virtual void setup() { // mesh fmt_flag = TETGEN_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Tetgen-Cube-0/") ; mesh_name = string("Cube - Tetrahedra") ; vec_fname[0] = string("cube.1") ; vec_fname[1] = string("cube.2") ; vec_fname[2] = string("cube.3") ; vec_fname[3] = string("cube.4") ; vec_fname[4] = string("cube.5") ; vec_fname[5] = string("cube.6") ; for ( int i=0; i<vec_offset.size(); ++i ) { vec_offset[i] = 1 ; } } } ; // -------------------------------------------------------------------------------------------- // previous class : Mesh_M1 // previous version: Layered/Quad-2/ // current version: STANDARD_SET/Cubic-Cells // mesh index: 1 #if 0 class Mesh_CubicCells : public MeshDirsBase { public: Mesh_CubicCells() : MeshDirsBase(6) { setup() ; } ~Mesh_CubicCells() {} virtual void setup() { // mesh M1 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Cubic-Cells/") ; mesh_name = string("Cubic cells") ; vec_fname[0] = string("gcube_2x2x2") ; vec_fname[1] = string("gcube_4x4x4") ; vec_fname[2] = string("gcube_8x8x8") ; vec_fname[3] = string("gcube_16x16x16") ; vec_fname[4] = string("gcube_32x32x32") ; vec_fname[5] = string("gcube_64x64x64") ; } } ; #endif class Mesh_CubicCells : public MeshDirsBase { public: Mesh_CubicCells() : MeshDirsBase(7) { setup() ; } ~Mesh_CubicCells() {} virtual void setup() { // mesh M1 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Cubic-Cells/") ; mesh_name = string("Cubic cells") ; vec_fname[0] = string("gcube_1x1x1") ; // TESTING VERSION vec_fname[1] = string("gcube_2x2x2") ; vec_fname[2] = string("gcube_4x4x4") ; vec_fname[3] = string("gcube_8x8x8") ; vec_fname[4] = string("gcube_16x16x16") ; vec_fname[5] = string("gcube_32x32x32") ; vec_fname[6] = string("gcube_64x64x64") ; } } ; // -------------------------------------------------------------------------------------------- // previous class : Mesh_M3 // previous version : Layered/Dual-1b // current version : STANDARD-SET/Prysmatic-Cells // mesh index: 2 // no hanging nodes (they have been removed from the 2D base mesh) class Mesh_PrysmaticCells : public MeshDirsBase { public: Mesh_PrysmaticCells() : MeshDirsBase(9) { setup() ; } ~Mesh_PrysmaticCells() {} virtual void setup() { // mesh M3 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Prysmatic-Cells/") ; mesh_name = string("Prysmatic cells with polygonal basis - no hanging nodes") ; vec_fname[0] = string("vprism_2x2x2") ; vec_fname[1] = string("vprism_4x4x4") ; vec_fname[2] = string("vprism_8x8x8") ; vec_fname[3] = string("vprism_16x16x16") ; vec_fname[4] = string("vprism_32x32x32") ; vec_fname[5] = string("vprism_64x64x64") ; vec_fname[6] = string("vprism_128x128x128") ; } } ; #if 0 // these cells have hanging nodes class Mesh_PrysmaticCells : public MeshDirsBase { public: Mesh_PrysmaticCells() : MeshDirsBase(9) { setup() ; } ~Mesh_PrysmaticCells() {} virtual void setup() { // mesh M3 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Prysmatic-Cells-1/") ; mesh_name = string("Prysmatic cells with polygonal basis") ; vec_fname[0] = string("gdual_1x1x1") ; // TESTING VERSION vec_fname[1] = string("gdual_5x5x5") ; vec_fname[2] = string("gdual_10x10x10") ; vec_fname[3] = string("gdual_15x15x15") ; vec_fname[4] = string("gdual_20x20x20") ; vec_fname[5] = string("gdual_25x25x25") ; vec_fname[6] = string("gdual_30x30x30") ; vec_fname[7] = string("gdual_35x35x35") ; vec_fname[8] = string("gdual_40x40x40") ; } } ; #endif // -------------------------------------------------------------------------------------------- // previous class : Mesh_M4 // previous version : Hexa-test-2 // current version : STANDARD_SET/Random-Hexahedra // mesh index: 3 class Mesh_RandomHexahedra : public MeshDirsBase { public: Mesh_RandomHexahedra() : MeshDirsBase(6) { setup() ; } ~Mesh_RandomHexahedra() {} virtual void setup() { // mesh M4 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Random-Hexahedra/") ; mesh_name = string("Random Hexahedra") ; vec_fname[0] = string("gcube.1") ; vec_fname[1] = string("gcube.2") ; vec_fname[2] = string("gcube.3") ; vec_fname[3] = string("gcube.4") ; vec_fname[4] = string("gcube.5") ; vec_fname[5] = string("gcube.6") ; } } ; // -------------------------------------------------------------------------------------------- // previous class : Mesh_M7 // previous version : Voronoi-SuperMesh/Voro-BIG // current version : STANDARD_SET/Voronoi-SuperMesh/Voro-BIG // mesh index: 4 class Mesh_VoronoiBIG : public MeshDirsBase { public: Mesh_VoronoiBIG() : MeshDirsBase(6) { setup() ; } ~Mesh_VoronoiBIG() {} virtual void setup() { // mesh M7 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-BIG/") ; mesh_name = string("Voronoi (BIG)") ; vec_fname[0] = string("voro-05") ; vec_fname[1] = string("voro-10") ; vec_fname[2] = string("voro-15") ; vec_fname[3] = string("voro-20") ; vec_fname[4] = string("voro-25") ; vec_fname[5] = string("voro-30") ; } } ; // -------------------------------------------------------------------------------------------- // previous class : Mesh_M8 // previous version : Voronoi-SuperMesh/Voro-small-0 // current version : STANDARD_SET/Voronoi-SuperMesh/Voro-small-0 // mesh index: 5 class Mesh_VoronoiSmall : public MeshDirsBase { public: Mesh_VoronoiSmall() : MeshDirsBase(8) { setup() ; } ~Mesh_VoronoiSmall() {} virtual void setup() { // mesh M8 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-small-0/") ; mesh_name = string("Voronoi (small-0)") ; vec_fname[0] = string("voro-2") ; vec_fname[1] = string("voro-4") ; vec_fname[2] = string("voro-6") ; vec_fname[3] = string("voro-8") ; vec_fname[4] = string("voro-10") ; vec_fname[5] = string("voro-12") ; vec_fname[6] = string("voro-14") ; vec_fname[7] = string("voro-16") ; } } ; // this is the one of FVCA6 benchmark class Mesh_VoronoiSmall1 : public MeshDirsBase { public: Mesh_VoronoiSmall1() : MeshDirsBase(5) { setup() ; } ~Mesh_VoronoiSmall1() {} virtual void setup() { // mesh fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-small-1/") ; mesh_name = string("Voronoi (small-1)") ; vec_fname[0] = string("voro.2") ; vec_fname[1] = string("voro.3") ; vec_fname[2] = string("voro.4") ; vec_fname[3] = string("voro.5") ; vec_fname[4] = string("voro.6") ; } } ; class Mesh_VoronoiSmall2 : public MeshDirsBase { public: Mesh_VoronoiSmall2() : MeshDirsBase(7) { setup() ; } ~Mesh_VoronoiSmall2() {} virtual void setup() { // mesh fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-small-2/") ; mesh_name = string("Voronoi (small-2)") ; vec_fname[0] = string("voro.2") ; vec_fname[1] = string("voro.4") ; vec_fname[2] = string("voro.6") ; vec_fname[3] = string("voro.8") ; vec_fname[4] = string("voro.3") ; vec_fname[5] = string("voro.5") ; vec_fname[6] = string("voro.7") ; } } ; // -------------------------------------------------------------------------------- // -------------------------------------------------------------------------------- class Mesh_Voronoi_new_0 : public MeshDirsBase { public: Mesh_Voronoi_new_0() : MeshDirsBase(4) { setup() ; } ~Mesh_Voronoi_new_0() {} virtual void setup() { // mesh fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-Cube-0/") ; mesh_name = string("Voronoi (new-cube-0)") ; vec_fname[0] = string("voro.5") ; vec_fname[1] = string("voro.10") ; vec_fname[2] = string("voro.20") ; vec_fname[3] = string("voro.30") ; } } ; class Mesh_Voronoi_new_1 : public MeshDirsBase { public: Mesh_Voronoi_new_1() : MeshDirsBase(6) { setup() ; } ~Mesh_Voronoi_new_1() {} virtual void setup() { // mesh fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-Tets-1/") ; mesh_name = string("Voronoi (new-tets-1)") ; vec_fname[0] = string("voro.1") ; vec_fname[1] = string("voro.2") ; vec_fname[2] = string("voro.3") ; vec_fname[3] = string("voro.4") ; vec_fname[4] = string("voro.5") ; vec_fname[5] = string("voro.6") ; } } ; class Mesh_Voronoi_new_2 : public MeshDirsBase { public: Mesh_Voronoi_new_2() : MeshDirsBase(6) { setup() ; } ~Mesh_Voronoi_new_2() {} virtual void setup() { // mesh fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/Voro-Tets-2/") ; mesh_name = string("Voronoi (new-tets-2)") ; vec_fname[0] = string("voro.1") ; vec_fname[1] = string("voro.2") ; vec_fname[2] = string("voro.3") ; vec_fname[3] = string("voro.4") ; vec_fname[4] = string("voro.5") ; vec_fname[5] = string("voro.6") ; } } ; // -------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------- class Mesh_DoubleCubes_RandomHex : public MeshDirsBase { public: Mesh_DoubleCubes_RandomHex() : MeshDirsBase(7) { setup() ; } ~Mesh_DoubleCubes_RandomHex() {} virtual void setup() { // mesh M4 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/STANDARD-SET/DoubleCubes/") ; mesh_name = string("Double Cubes - Random Hexahedra") ; vec_fname[0] = string("gdouble_cube.1") ; vec_fname[1] = string("gdouble_cube.2") ; vec_fname[2] = string("gdouble_cube.3") ; vec_fname[3] = string("gdouble_cube.4") ; vec_fname[4] = string("gdouble_cube.5") ; vec_fname[5] = string("gdouble_cube.6") ; vec_fname[6] = string("gdouble_cube.7") ; } } ; class Mesh_TiltedCubicCells : public MeshDirsBase { public: Mesh_TiltedCubicCells() : MeshDirsBase(7) { setup() ; } ~Mesh_TiltedCubicCells() {} virtual void setup() { // mesh M1 fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/TiltedCubicMesh/") ; mesh_name = string("Tilted Cubic cells") ; vec_fname[0] = string("tgcube_1x1x1") ; // TESTING VERSION vec_fname[1] = string("tgcube_2x2x2") ; vec_fname[2] = string("tgcube_4x4x4") ; vec_fname[3] = string("tgcube_8x8x8") ; vec_fname[4] = string("tgcube_16x16x16") ; vec_fname[5] = string("tgcube_32x32x32") ; vec_fname[6] = string("tgcube_64x64x64") ; } } ; // class Mesh_G : public MeshDirsBase { public: Mesh_G() : MeshDirsBase(5) { setup() ; } ~Mesh_G() {} virtual void setup() { // mesh family G fmt_flag = REGN_FACE_FMT ; mesh_dir = string("./MeshDataSets/Mesh-3D/BENCHMARK-FVCA6/Mesh-G/") ; mesh_name = string("Cubic cells with corner refinement") ; vec_fname[0] = string("hexa_2x2x2_locraf_new") ; vec_fname[1] = string("hexa_4x4x4_locraf_new") ; vec_fname[2] = string("hexa_8x8x8_locraf_new") ; vec_fname[3] = string("hexa_16x16x16_locraf_new") ; vec_fname[4] = string("hexa_32x32x32_locraf_new") ; } } ; // -------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------- //---- set mesh dirs // -------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------- MeshDirsBase & set_mesh_dirs( int mesh_flag ) { MeshDirsBase * p_mdir ; switch ( mesh_flag ) { case 0 : p_mdir = new Mesh_Cube_Tetrahedra_0 ; break ; case 1 : p_mdir = new Mesh_CubicCells ; break ; case 2 : p_mdir = new Mesh_PrysmaticCells ; break ; case 3 : p_mdir = new Mesh_RandomHexahedra ; break ; case 4 : p_mdir = new Mesh_VoronoiBIG ; break ; case 5 : p_mdir = new Mesh_VoronoiSmall ; break ; case 6 : p_mdir = new Mesh_VoronoiSmall1 ; break ; //case 7 : p_mdir = new Mesh_VoronoiSmall2 ; break ; case 8 : p_mdir = new Mesh_Voronoi_new_0 ; break ; case 9 : p_mdir = new Mesh_Voronoi_new_1 ; break ; case 10 : p_mdir = new Mesh_Voronoi_new_2 ; break ; case 11 : p_mdir = new Mesh_DoubleCubes_RandomHex ; break ; case 12 : p_mdir = new Mesh_TiltedCubicCells ; break ; case 7 : p_mdir = new Mesh_G ; break ; default: assert( bool(false) ) ; } return *p_mdir ; } #endif // end of _MESH_DIRS
38.530516
95
0.581455
[ "mesh", "vector", "3d" ]
2b9bdc8a9f2034a1b58900bee780557e4a5851f2
479
cpp
C++
SVEngine/src/basesys/SVTransCPU.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/basesys/SVTransCPU.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/basesys/SVTransCPU.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVTransCPU.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVTransCPU.h" SVTransCPU::SVTransCPU(SVInst *_app) :SVTrans(_app){ } SVTransCPU::~SVTransCPU() { } void SVTransCPU::init(s32 _w, s32 _h,f32 _angle,PICFORMATE _picformate,SVTEXTYPE _tt){ SVTrans::init(_w, _h, _angle, _picformate,_tt); } void SVTransCPU::destroy(){ } void SVTransCPU::update(f32 dt) { } void SVTransCPU::render(){ }
15.966667
86
0.701461
[ "render" ]
2ba52e386bbe6e0cdef17d991ff06af6652cbd84
1,873
cpp
C++
example/read-scores.cpp
Watch-Later/tableprinter
b1c9ac73723dbc3a309f56b96293edcbbc5768a5
[ "MIT" ]
24
2021-12-05T19:43:56.000Z
2022-01-13T10:51:20.000Z
example/read-scores.cpp
Watch-Later/tableprinter
b1c9ac73723dbc3a309f56b96293edcbbc5768a5
[ "MIT" ]
1
2021-12-08T05:40:00.000Z
2021-12-08T17:04:21.000Z
example/read-scores.cpp
Watch-Later/tableprinter
b1c9ac73723dbc3a309f56b96293edcbbc5768a5
[ "MIT" ]
3
2021-12-06T02:02:17.000Z
2021-12-07T05:07:58.000Z
#include <fstream> #include <iostream> #include <iterator> #include <vector> #include <algorithm> #include <string> struct entry { int id; std::string name; std::string surname; int rank; float score; }; std::istream& operator>>( std::istream& is , entry& s ); void skip_echo_and_header( std::istream& is ); void print_max_score( const std::vector<entry>& ); int main() { std::ifstream scores_f { "scores.txt" }; if ( !scores_f ) { std::cerr << "'scores.txt' could not be read.\n" "Run 'print-scores' first." << std::endl; return 1; } std::cout << "A demonstration how " "table-like output is " "convenient to be read" << std::endl; skip_echo_and_header( scores_f ); std::istream_iterator<entry> scores_i_itr { scores_f }; std::istream_iterator<entry> eof; std::vector<entry> scores { scores_i_itr , eof }; print_max_score( scores ); } std::istream& operator>>( std::istream& is , entry& s ) { return is >> s.id >> s.name >> s.surname >> s.rank >> s.score; } void skip_echo_and_header( std::istream& is ) { std::string skipped_line; std::getline( is , skipped_line ); std::getline( is , skipped_line ); } void print_max_score( const std::vector<entry>& scores ) { auto by_score = []( const entry& lhs , const entry& rhs ){ return lhs.score < rhs.score; }; auto winner = std::max_element( std::begin( scores ) , std::end( scores ) , by_score ); std::cout << "Winner is " << winner->name << " " << winner->surname << " who has score " << winner->score << std::endl; }
22.297619
62
0.530166
[ "vector" ]
ad9e3654a751f09e25b2c9e9243d92be584f7e5a
45,413
cpp
C++
nssavoir/nspatho.cpp
prometheusorg/epiClassifier
8f3a41e1f68f713fcbcd6372d77ac6a0ed1d3347
[ "Apache-2.0" ]
3
2017-05-22T14:57:13.000Z
2018-02-08T15:47:37.000Z
nssavoir/nspatho.cpp
prometheusorg/epiClassifier
8f3a41e1f68f713fcbcd6372d77ac6a0ed1d3347
[ "Apache-2.0" ]
13
2017-01-24T16:28:22.000Z
2018-01-22T00:12:50.000Z
nssavoir/nspatho.cpp
prometheusorg/epiClassifier
8f3a41e1f68f713fcbcd6372d77ac6a0ed1d3347
[ "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // NSPERSON.CPP // KRZISCH PH. janvier 92 // Implémentation de objets NAUTILUS //--------------------------------------------------------------------------- #include <string> #include <cstring> //using namespace std; #ifdef _ENTERPRISE_DLL #include "enterpriseLus/nsdivfctForCgi.h" #include "enterpriseLus/superLus.h" #include "nsdatabaseLus/nsSQL.h" #include "mysql/mysql.h" #else #include "nautilus\nssuper.h" #include "partage\nsdivfct.h" #include "nautilus\nsrechdl.h" #endif #include "nssavoir/nspatho.h" // ----------------------------------------------------------------------------- // // Implémentation des méthodes NSPatholog // // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Description: Constructeur. // ----------------------------------------------------------------------------- NSPathologData::NSPathologData() { #ifndef _ENTERPRISE_DLL // Met les champs de données à zéro memset(libelle, 0, PATHO_LIBELLE_LEN + 1); memset(code, 0, PATHO_CODE_LEN + 1); memset(grammaire, 0, PATHO_GRAMMAIRE_LEN + 1); memset(freq, 0, PATHO_FREQ_LEN + 1); #else sLabel = string(""); sCode = string(""); sGrammar = string(""); sFrequency = string(""); #endif } // ----------------------------------------------------------------------------- // Description: Constructeur copie // ----------------------------------------------------------------------------- NSPathologData::NSPathologData(NSPathologData& rv) { #ifndef _ENTERPRISE_DLL strcpy(libelle, rv.libelle); strcpy(code, rv.code); strcpy(grammaire, rv.grammaire); strcpy(freq, rv.freq); #else sLabel = rv.sLabel; sCode = rv.sCode; sGrammar = rv.sGrammar; sFrequency = rv.sFrequency; #endif } // ----------------------------------------------------------------------------- // Description: Destructeur // ----------------------------------------------------------------------------- NSPathologData::~NSPathologData() { } // ----------------------------------------------------------------------------- // Description: Opérateur = // ----------------------------------------------------------------------------- NSPathologData& NSPathologData::operator=(NSPathologData src) { if (this == &src) return *this; #ifndef _ENTERPRISE_DLL strcpy(libelle, src.libelle); strcpy(code, src.code); strcpy(grammaire, src.grammaire); strcpy(freq, src.freq); #else sLabel = src.sLabel; sCode = src.sCode; sGrammar = src.sGrammar; sFrequency = src.sFrequency; #endif return *this; } // ----------------------------------------------------------------------------- // Description: Opérateur de comparaison // ----------------------------------------------------------------------------- int NSPathologData::operator==(const NSPathologData& o) { #ifndef _ENTERPRISE_DLL if ((strcmp(libelle, o.libelle) == 0) && (strcmp(code, o.code) == 0)) #else if ((sLabel == o.sLabel) && (sCode == o.sCode)) #endif return 1; else return 0; } // ----------------------------------------------------------------------------- // Description: Met à blanc les variables de la fiche // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL void NSPathologData::metABlanc() { // Met les champs de données à blanc memset(libelle, ' ', PATHO_LIBELLE_LEN); memset(code, ' ', PATHO_CODE_LEN); memset(grammaire, ' ', PATHO_GRAMMAIRE_LEN); memset(freq, ' ', PATHO_FREQ_LEN); } #endif // ----------------------------------------------------------------------------- // Function : NSPathologData::fabriqueNomLong() // Description : Initialise nom_long // Returns : Rien // ----------------------------------------------------------------------------- void NSPathologData::fabriqueLibelleLong() { // libelleLong = string(libelle); } // ----------------------------------------------------------------------------- // Function : NSPathologData::donneLibelleChoix(string* pLibelle) // Description : Donne le libellé affiché dans ChoixPathoDialogue // ----------------------------------------------------------------------------- void NSPathologData::donneLibelleChoix(string* pLibelle) { if ((string *) NULL == pLibelle) return; // le libellé est du type Crohn [maladie][de]{détails} // qui donne Crohn (maladie){détails} // // Les indications d'orthographe au pluriel sont entre ||, // il faut les enlever string sLibelle = string(""); bool dansPluriel = false; #ifndef _ENTERPRISE_DLL for (int k = 0; (k < PATHO_LIBELLE_LEN) && (libelle[k] != '\0'); k++) { if (libelle[k] == '|') { if (dansPluriel) dansPluriel = false; else dansPluriel = true; } else if (!dansPluriel) sLibelle += libelle[k]; } #else for (size_t k = 0; (k < strlen(sLabel.c_str())); k++) { if ('|' == sLabel[k]) { if (dansPluriel) dansPluriel = false; else dansPluriel = true; } else if (false == dansPluriel) sLibelle += sLabel[k]; } #endif int niveau_crochet = -1; string qualifiant[2]; string mot_debut = ""; string mot_fin = ""; qualifiant[0] = ""; qualifiant[1] = ""; // On sépare le libellé sous la forme : // mot_debut = "Crohn" // mot_fin = "{détails}" // qualifiant[0] = "maladie" // qualifiant[1] = "de" int iLibLen = strlen(sLibelle.c_str()); for (int k = 0; k < iLibLen; k++) { if (sLibelle[k] == '[') { niveau_crochet++; k++; while ((sLibelle[k] != ']') && (k < iLibLen)) { qualifiant[niveau_crochet] += sLibelle[k]; k++; } } else { if (niveau_crochet == -1) mot_debut += sLibelle[k]; else mot_fin += sLibelle[k]; } } // On assemble le nouveau libelle *pLibelle = mot_debut; if (qualifiant[0] != "") *pLibelle += "(" + qualifiant[0] + ")"; *pLibelle += mot_fin; // On s'assure qu'il fait encore PATHO_LIBELLE_LEN caractères if (strlen(pLibelle->c_str()) < PATHO_LIBELLE_LEN) *pLibelle += string(PATHO_LIBELLE_LEN - strlen(pLibelle->c_str()), ' '); else if (strlen(pLibelle->c_str()) > PATHO_LIBELLE_LEN) (*pLibelle)[PATHO_LIBELLE_LEN-1] = '\0'; // On supprime les blancs terminaux strip(*pLibelle, stripRight); // On vérifie qu'il n'existe pas plusieurs blancs contigus size_t positBlanc = pLibelle->find(" "); size_t debut, fin, taille; while (positBlanc != NPOS) { debut = positBlanc; taille = strlen(pLibelle->c_str()); if ((debut < taille - 1) && ((*pLibelle)[debut + 1] == ' ')) { fin = debut + 1; while ((fin < taille - 1) && ((*pLibelle)[fin + 1] == ' ')) fin++; *pLibelle = string(*pLibelle, 0, debut) + " " + string(*pLibelle, fin + 1, taille - fin - 1); } else fin = debut; debut++; positBlanc = pLibelle->find(" ", debut); } } // ----------------------------------------------------------------------------- // Function : NSPathologData::donneLibelleAffiche(string* pLibelle) // Description : Donne le "beau" libellé // La variable GenreMaitre sert à donner un genre aux adjectifs // ----------------------------------------------------------------------------- void NSPathologData::donneLibelleAffiche(string* pLibelle, int iDeclinaison) { if ((string *) NULL == pLibelle) return; *pLibelle = ""; // le libellé est du type "Crohn [maladie][de]{détails}" // qui donne "maladie de Crohn" // // Les indications de déclinaison sont entre ||, séparés par des / // ex : "disjoint|t/te/ts/tes|" // // Trois cas sont possibles : // 1) Pas de || : mot invariable // 2) Un seul élément entre || (ex test|s|) qui donne la première // déclinaison lorsque la racine est constituée du mot entier // 3) Plusieurs éléments entre || (ex animal|al/aux|), le premier // élément (0) permet de définir la racine, les autres donnent les // déclinaisons (1, 2...) int niveau_crochet = -1; string mot_debut = ""; string mot_fin = ""; string orthographe = ""; string qualifiant[2]; qualifiant[0] = ""; qualifiant[1] = ""; // On sépare le libellé sous la forme : // mot_debut = "Crohn" // mot_fin = "{détails}" // qualifiant[0] = "maladie" // qualifiant[1] = "de" #ifndef _ENTERPRISE_DLL for (int k = 0; (k < PATHO_LIBELLE_LEN) && (libelle[k] != '\0'); k++) { if (libelle[k] == '[') { niveau_crochet++; k++; while ((libelle[k] != ']') && (k < PATHO_LIBELLE_LEN) && (libelle[k] != '\0')) { if (libelle[k] == '|') { orthographe = ""; k++; while ((libelle[k] != '|') && (k < PATHO_LIBELLE_LEN) && (libelle[k] != '\0')) { orthographe += libelle[k]; k++; } if ((k < PATHO_LIBELLE_LEN) && (libelle[k] == '|')) traiteOrthographe(&qualifiant[niveau_crochet], &orthographe, iDeclinaison); else return; } else qualifiant[niveau_crochet] += libelle[k]; k++; } } else { if ((libelle[k] == '{') && (k < PATHO_LIBELLE_LEN + 1) && (libelle[k+1] == '|')) { while ((libelle[k] != '}') && (k < PATHO_LIBELLE_LEN) && (libelle[k] != '\0')) k++; } else if (libelle[k] == '|') { k++; orthographe = ""; while ((libelle[k] != '|') && (k < PATHO_LIBELLE_LEN) && (libelle[k] != '\0')) { orthographe += libelle[k]; k++; } if ((k < PATHO_LIBELLE_LEN) && (libelle[k] == '|')) { if (niveau_crochet == -1) traiteOrthographe(&mot_debut, &orthographe, iDeclinaison); else traiteOrthographe(&mot_fin, &orthographe, iDeclinaison); } else return; } else { if (niveau_crochet == -1) mot_debut += libelle[k]; else mot_fin += libelle[k]; } } } #else for (size_t k = 0; (k < strlen(sLabel.c_str())); k++) { if ('[' == sLabel[k]) { niveau_crochet++; k++; while ((k < strlen(sLabel.c_str())) && (']' != sLabel[k])) { if ('|' == sLabel[k]) { orthographe = ""; k++; while ((k < strlen(sLabel.c_str())) && ('|' != sLabel[k])) { orthographe += sLabel[k]; k++; } if ((k < strlen(sLabel.c_str())) && ('|' == sLabel[k])) traiteOrthographe(&qualifiant[niveau_crochet], &orthographe, iDeclinaison); else return; } else qualifiant[niveau_crochet] += sLabel[k]; k++; } } else { if ((k < strlen(sLabel.c_str()) - 1) && ('{' == sLabel[k]) && ('|' == sLabel[k+1])) { while ((k < strlen(sLabel.c_str())) && ('}' != sLabel[k])) k++; } else if ('|' == sLabel[k]) { k++; orthographe = ""; while ((k < strlen(sLabel.c_str())) && ('|' != sLabel[k])) { orthographe += sLabel[k]; k++; } if ((k < strlen(sLabel.c_str())) && ('|' == sLabel[k])) { if (-1 == niveau_crochet) traiteOrthographe(&mot_debut, &orthographe, iDeclinaison); else traiteOrthographe(&mot_fin, &orthographe, iDeclinaison); } else return; } else { if (-1 == niveau_crochet) mot_debut += sLabel[k]; else mot_fin += sLabel[k]; } } } #endif // On assemble le nouveau libelle char dernCar = '\0'; char premCar = '\0'; if (!(mot_debut == "")) strip(mot_debut, stripBoth); if (!(mot_fin == "")) strip(mot_fin, stripBoth); *pLibelle = qualifiant[0]; if (qualifiant[0] != "") dernCar = qualifiant[0][strlen(qualifiant[0].c_str())-1]; if (qualifiant[1] != "") { premCar = qualifiant[1][0]; if ((premCar != ' ') && (dernCar != '-') && (dernCar != '\'') && (dernCar != ' ')) *pLibelle += " "; *pLibelle += qualifiant[1]; dernCar = qualifiant[1][strlen(qualifiant[1].c_str()) - 1]; } if (mot_debut != "") { premCar = mot_debut[0]; if (*pLibelle != "" ) if ((premCar != ' ') && (dernCar != '-') && (dernCar != '\'') && (dernCar != ' ')) *pLibelle += " "; *pLibelle += mot_debut; } // On supprime les blancs terminaux strip(*pLibelle, stripRight); size_t positionAccolades = pLibelle->find("{"); size_t positionVideAccolades = pLibelle->find(" {"); if (positionVideAccolades != NPOS) *pLibelle = string(*pLibelle, 0, positionVideAccolades); else if (positionAccolades != NPOS) *pLibelle = string(*pLibelle, 0, positionAccolades); // On vérifie qu'il n'existe pas plusieurs blancs contigus size_t positBlanc = pLibelle->find(" "); size_t debut, fin, taille; while (positBlanc != NPOS) { debut = positBlanc; taille = strlen(pLibelle->c_str()); if ((debut < taille - 1) && ((*pLibelle)[debut + 1] == ' ')) { fin = debut + 1; while ((fin < taille - 1) && ((*pLibelle)[fin + 1] == ' ')) fin++; *pLibelle = string(*pLibelle, 0, debut) + " " + string(*pLibelle, fin + 1, taille - fin - 1); } else fin = debut; debut++; positBlanc = pLibelle->find(" ", debut); } // On supprime les blancs terminaux strip(*pLibelle, stripRight); } // ----------------------------------------------------------------------------- // NSPathologData::traiteOrthographe(string* pMot, string* pOrthographe, int GenreMaitre) // // Description : Donne le "beau" libellé // La variable GenreMaitre sert à donner un genre aux adjectifs // ----------------------------------------------------------------------------- void NSPathologData::traiteOrthographe(string* pMot, string* pOrthographe, int iDeclinaison) { if (NULL == pMot) return; // simple précaution strip(*pMot, stripRight, ' '); // Si on demande la déclinaison 0, il n'y a rien à faire if (iDeclinaison == 0) return; if (NULL == pOrthographe) return; int iLen = strlen(pOrthographe->c_str()); // Cas simple, pas de déclinaisons, on ne fait rien if (0 == iLen) return; // distribution des déclinaisons dans les différentes cases d'un vecteur vector<string> vOrthographe; vector<string>::iterator ivOrtho; int iNbElmnt = 0; string sOrtho = string(""); for (int i = 0; i < iLen; i++) { if ('/' == (*pOrthographe)[i]) { vOrthographe.push_back(string(sOrtho, 0, strlen(sOrtho.c_str()))); sOrtho = string(""); iNbElmnt++; } else sOrtho += (*pOrthographe)[i]; } vOrthographe.push_back(string(sOrtho, 0, strlen(sOrtho.c_str()))); iNbElmnt++; // Cas où il n'existe qu'une seule déclinaison : // // si iDeclinaison == 0, rien à faire // si iDeclinaison == 1, on ajoute la déclinaison au mot if (1 == iNbElmnt) { if (1 == iDeclinaison) *pMot = *pMot + *(vOrthographe.begin()); return; } // Cas où il existe plusieurs déclinaisons : // on détermine la racine à partir de la déclinaison 0 // puis on ajoute la déclinaison demandée // Recherche de la iDeclinaisonième déclinaison int i = 0; for (ivOrtho = vOrthographe.begin(); (i < iDeclinaison) && (ivOrtho != vOrthographe.end()); i++, ivOrtho++) ; // On vérifie quand même qu'elle existe if ((i < iDeclinaison) || (vOrthographe.end() == ivOrtho)) return; int iRaciLen = strlen(pMot->c_str()) - strlen(vOrthographe.begin()->c_str()); if (iRaciLen <= 0) { *pMot = *ivOrtho; return; } *pMot = string(*pMot, 0, iRaciLen) + *ivOrtho; } // ----------------------------------------------------------------------------- // Function: NSPathologData::donneGenre(int *pGenre) // // Description: Donne le "beau" libellé // ----------------------------------------------------------------------------- void NSPathologData::donneGenre(GENRE *pGenre) { if ((GENRE *) NULL == pGenre) return; #ifndef _ENTERPRISE_DLL string sGenre = string(grammaire); #else string sGenre = sGrammar; #endif strip(sGenre); if (string("FS") == sGenre) *pGenre = genreFS; else if (string("MS") == sGenre) *pGenre = genreMS; else if (string("NS") == sGenre) *pGenre = genreNS; else if (string("FP") == sGenre) *pGenre = genreFP; else if (string("MP") == sGenre) *pGenre = genreMP; else if (string("NP") == sGenre) *pGenre = genreNP; else *pGenre = genreNull; } void NSPathologData::donneGenrePluriel(GENRE *pGenre) { if ((GENRE *) NULL == pGenre) return; if (genreFS == *pGenre) *pGenre = genreFP; else if (genreMS == *pGenre) *pGenre = genreMP; else if (genreNS == *pGenre) *pGenre = genreNP; else *pGenre = genreNull; } void NSPathologData::donneGenreSingulier(GENRE *pGenre) { if ((GENRE *) NULL == pGenre) return; if (genreFP == *pGenre) *pGenre = genreFS; else if (genreMP == *pGenre) *pGenre = genreMS; else if (genreNP == *pGenre) *pGenre = genreNS; else *pGenre = genreNull; } // ----------------------------------------------------------------------------- // Function : NSPathologData::chercheGrammaire(string sAChercher) // // Cherche dans le libelle le commentaire grammatical ( {|__} ) commencant par // sAChercher, et le renvoie. // ----------------------------------------------------------------------------- string NSPathologData::chercheGrammaire(string sAChercher) { #ifndef _ENTERPRISE_DLL string sLibelleBrut = string(libelle); #else string sLibelleBrut = sLabel; #endif size_t positionAccolades = sLibelleBrut.find("{|"); if (positionAccolades == string::npos) return string(""); size_t finAccolades = sLibelleBrut.find("}", positionAccolades + 1); if ((finAccolades == string::npos) || (finAccolades-positionAccolades < 4)) return ""; // On recupere dans sGrammaire le contenu entre {| et } // On analysera par la suite sGrammaire string sGrammaire = string(sLibelleBrut, positionAccolades + 2, finAccolades-positionAccolades - 2); size_t pos = sGrammaire.find(sAChercher); // size_t len = strlen(sAChercher.c_str()); if (string::npos == pos) return(""); // On recherche la fin de la string cherchee // Puis on renvoie la string cherchee if (pos == strlen(sGrammaire.c_str())) return string(sGrammaire, pos, 1); size_t posfin = sGrammaire.find("/", pos + 1); if (string::npos == posfin) return string(sGrammaire, pos, strlen(sGrammaire.c_str()) - pos); return string(sGrammaire, pos, posfin - pos); } bool NSPathologData::estReel() { return true; } // ----------------------------------------------------------------------------- // Constructeur // ----------------------------------------------------------------------------- NSPatholog::NSPatholog(NSSuper* pSuper, string sLang) #ifndef _ENTERPRISE_DLL :NSFiche(pSuper) #else :NSSuperRoot(pSuper) #endif { _sLangue = sLang; #ifdef _ENTERPRISE_DLL if (string("") == _sLangue) _sTableName = "lexiq_fr"; else _sTableName = string("lexiq_") + _sLangue; #else if (_sLangue == "") sNomFichier = "LEXIQUE.DB"; else if (_sLangue == "fr") sNomFichier = "LEXIQUE.DB"; else sNomFichier = string("LEXIQ_") + _sLangue + string(".DB"); #endif } // ----------------------------------------------------------------------------- // Constructeur copie // ----------------------------------------------------------------------------- NSPatholog::NSPatholog(NSPatholog& rv) #ifndef _ENTERPRISE_DLL :NSFiche(rv._pSuper) #else :NSSuperRoot(rv._pSuper) #endif { // Copie les valeurs du NSPathologInfo d'origine _Donnees = rv._Donnees; _sLangue = rv._sLangue; #ifdef _ENTERPRISE_DLL _sTableName = rv._sTableName; #endif } // ----------------------------------------------------------------------------- // Destructeur // ----------------------------------------------------------------------------- NSPatholog::~NSPatholog() { } // ----------------------------------------------------------------------------- // Fonction : NSPatholog::alimenteFiche() // Description : Transfère le contenu de pRecBuff dans les variables de la fiche // ----------------------------------------------------------------------------- void NSPatholog::alimenteFiche() { #ifndef _ENTERPRISE_DLL alimenteChamp(_Donnees.libelle, PATHO_LIBELLE_FIELD, PATHO_LIBELLE_LEN); alimenteChamp(_Donnees.code, PATHO_CODE_FIELD, PATHO_CODE_LEN); alimenteChamp(_Donnees.grammaire, PATHO_GRAMMAIRE_FIELD, PATHO_GRAMMAIRE_LEN); alimenteChamp(_Donnees.freq, PATHO_FREQ_FIELD, PATHO_FREQ_LEN); _Donnees.fabriqueLibelleLong(); #endif } #ifdef _ENTERPRISE_DLL void NSPatholog::alimenteFiche(MYSQL_ROW *pRow) { _Donnees.setLabel((*pRow)[PATHO_LIBELLE_FIELD-1]); _Donnees.setCode((*pRow)[PATHO_CODE_FIELD-1]); _Donnees.setGrammar((*pRow)[PATHO_GRAMMAIRE_FIELD-1]); _Donnees.setFrequency((*pRow)[PATHO_FREQ_FIELD-1]); _Donnees.fabriqueLibelleLong(); } #endif // ----------------------------------------------------------------------------- // Fonction : NSPatholog::videFiche() // Description : Transfère le contenu des valeurs de la fiche dans pRecBuff // ----------------------------------------------------------------------------- void NSPatholog::videFiche() { #ifndef _ENTERPRISE_DLL videChamp(_Donnees.libelle, PATHO_LIBELLE_FIELD, PATHO_LIBELLE_LEN); videChamp(_Donnees.code, PATHO_CODE_FIELD, PATHO_CODE_LEN); videChamp(_Donnees.grammaire, PATHO_GRAMMAIRE_FIELD, PATHO_GRAMMAIRE_LEN); videChamp(_Donnees.freq, PATHO_FREQ_FIELD, PATHO_FREQ_LEN); #endif } // ----------------------------------------------------------------------------- // Fonction : NSPatholog::getRecord() // Description : Prend l'enregistrement en cours et assigne la valeur des // champs aux variables membres de la classe. // Returns : PXERR_, s'il y a lieu // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL DBIResult NSPatholog::getPatRecord() { // La table est-elle ouverte ? if (!isOpen) return(lastError = ERROR_TABLENOTOPEN); // Appel de la classe de base pour récupérer l'enregistrement. lastError = getDbiRecord(dbiWRITELOCK); return (lastError); } #endif #ifdef _ENTERPRISE_DLL string NSPatholog::getTableName(string sLanguage) { string sTableName = string("lexiq_fr"); if (string("") != _sLangue) sTableName = string("lexiq_") + _sLangue; return sTableName; } bool NSPatholog::executeQuery(string sQuery, bool bVerbose) { if (string("") == sQuery) return false; if (NULL == _pSuper->getDatabaseManager()) return false; MYSQL_RES *pResult = _pSuper->getDatabaseManager()->executeQuery(sQuery, bVerbose); if ((MYSQL_RES *) NULL == pResult) return false; if (mysql_num_rows(pResult) == 0) return false; bool bSucces = true; MYSQL_ROW Row = mysql_fetch_row(pResult); if (Row) alimenteFiche(&Row); else if (bVerbose) { string sErreurMsg = string("Error when fetching row for query [") + sQuery + string("] -> ") + mysql_error(_pSuper->getDatabaseManager()->getConnector()); error(sErreurMsg.c_str(), standardError); bSucces = false; } mysql_free_result(pResult); return bSucces; } #endif // ----------------------------------------------------------------------------- // Renvoie la fiche NSPathologData correspondant à ce code // ----------------------------------------------------------------------------- bool #ifndef _ENTERPRISE_DLL NSPatholog::trouvePathologData(string* pCode, NSPathologData* pData, bool afficheErreur) { if (((string *) NULL == pCode) || (string("") == *pCode) || ((NSPathologData *) NULL == pData)) return false; lastError = chercheClef(pCode, "CODE_INDEX", keySEARCHEQ, dbiWRITELOCK); if (lastError != DBIERR_NONE) { if (afficheErreur) { string sErreurMsg = string("Erreur à la recherche du code [") + *pCode + string("]"); error(sErreurMsg.c_str(), standardError, lastError); } return false; } lastError = getRecord(); if (lastError != DBIERR_NONE) { error("Erreur à la lecture du lexique.", standardError, lastError); return false; } *pData = _Donnees; #else NSPatholog::trouvePathologData(string sLang, string* pCode, NSPathologData* pData, bool afficheErreur) { if (((string *) NULL == pCode) || (string("") == *pCode) || ((NSPathologData *) NULL == pData)) return false; string sQuery = string("SELECT * FROM ") + getTableName(sLang) + string(" WHERE code = \"") + *pCode + string("\";"); if (false == executeQuery(sQuery, afficheErreur)) return false; *pData = _Donnees; #endif return true; } // ----------------------------------------------------------------------------- // Description : Trouve la première fiche dont le code convient // Transfère la fiche dans pDonnees // // Returns : PXERR_, s'il y a lieu // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL DBIResult NSPatholog::trouveCode(string* pCode, DBISearchCond searchMode, DBILockType Blocage, bool bErrMessage) { lastError = chercheClef(pCode, "CODE_INDEX", searchMode, Blocage); if (lastError != DBIERR_NONE) { char msg[255]; string sCode; if ((*pCode) == "") sCode = "vide"; else sCode = *pCode; if (bErrMessage) { sprintf(msg, "Erreur à la recherche du code : [%s]", sCode.c_str()); error(msg, standardError, lastError); } return lastError; } lastError = getRecord(); if (lastError != DBIERR_NONE) { if (bErrMessage) error("Erreur à la lecture du lexique.", standardError, lastError); return lastError; } return (lastError); } #else bool NSPatholog::trouveCode(string sLang, string* pCode, bool bVerbose) { if ((string *) NULL == pCode) return false; string sQuery = string("SELECT * FROM ") + getTableName(sLang) + string(" WHERE code = \"") + *pCode + string("\";"); if (false == executeQuery(sQuery, bVerbose)) return false; return true; } #endif // ----------------------------------------------------------------------------- // Description : Trouve la première fiche dont le libellé convient // Transfère la fiche dans pDonnees // Returns : PXERR_, s'il y a lieu // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL DBIResult NSPatholog::trouveLibelle(string* pLibelle, DBISearchCond searchMode, DBILockType Blocage) { lastError = chercheClef((unsigned char *)pLibelle->c_str(), "", 0, searchMode, Blocage); if (lastError != DBIERR_NONE) { error("Erreur à la recherche de l'ammorce.", standardError, lastError); return lastError; } lastError = getRecord(); if (lastError != DBIERR_NONE) { error("Erreur à la lecture du lexique.", standardError, lastError); return lastError; } return (lastError); } #else bool NSPatholog::trouveLibelle(string sLang, string* pLibelle) { if ((string *) NULL == pLibelle) return false; string sQuery = string("SELECT * FROM ") + getTableName(sLang) + string(" WHERE libelle = \"") + *pLibelle + string("\";"); if (false == executeQuery(sQuery, true)) return false; return true; } bool NSPatholog::trouveLibelleApproche(string sLang, string* pLibelle) { if ((string *) NULL == pLibelle) return false; string sQuery = string("SELECT * FROM ") + getTableName(sLang) + string(" WHERE libelle LIKE \"") + *pLibelle + string("%\";"); if (false == executeQuery(sQuery, true)) return false; return true; } #endif // ----------------------------------------------------------------------------- // Fonction : NSPatient::open() // Description : Ouvre la table primaire et les index secondaires // Returns : PXERR_, s'il y a lieu // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL DBIResult NSPatholog::open() { //char tableName[] = "LEXIQUE.DB"; // Appelle la fonction open() de la classe de base pour ouvrir // l'index primaire lastError = NSFiche::open(/*tableName*/sNomFichier.c_str(), NSF_GUIDES); return (lastError); } #endif // ----------------------------------------------------------------------------- // Function : NSPatholog::Create() // ----------------------------------------------------------------------------- bool NSPatholog::Create() { return true; } // ----------------------------------------------------------------------------- // Function : NSPatholog::Modify() // ----------------------------------------------------------------------------- bool NSPatholog::Modify() { return true; } // ----------------------------------------------------------------------------- // Opérateur d'affectation // ----------------------------------------------------------------------------- NSPatholog& NSPatholog::operator=(NSPatholog src) { if (this == &src) return *this; _Donnees = src._Donnees; _sLangue = src._sLangue; return *this; } // ----------------------------------------------------------------------------- // Opérateur de comparaison // ----------------------------------------------------------------------------- int NSPatholog::operator==(const NSPatholog& o) { return (_Donnees == o._Donnees); } // ----------------------------------------------------------------------------- // Fonction : NSPathologInfo::NSPathologInfo() // Description : Constructeur par défaut // ----------------------------------------------------------------------------- NSPathologInfo::NSPathologInfo() { } // ----------------------------------------------------------------------------- // Fonction : NSPathologInfo::NSPathologInfo(NSPatholog *) // Description : Constructeur à partir d'un NSPatient // ----------------------------------------------------------------------------- NSPathologInfo::NSPathologInfo(NSPatholog* pPatho) { if (NULL == pPatho) return; // Copie les valeurs du NSDocument _Donnees = pPatho->_Donnees; } // ----------------------------------------------------------------------------- // Constructeur copie // ----------------------------------------------------------------------------- NSPathologInfo::NSPathologInfo(NSPathologInfo& rv) { // Copie les valeurs du NSPathologInfo d'origine _Donnees = rv._Donnees; } // ----------------------------------------------------------------------------- // Destructeur // ----------------------------------------------------------------------------- NSPathologInfo::~NSPathologInfo() { } // ----------------------------------------------------------------------------- // Opérateur d'affectation // ----------------------------------------------------------------------------- NSPathologInfo& NSPathologInfo::operator=(NSPathologInfo src) { if (this == &src) return *this; _Donnees = src._Donnees; return *this; } // ----------------------------------------------------------------------------- // Opérateur de comparaison // ----------------------------------------------------------------------------- int NSPathologInfo::operator==(const NSPathologInfo& o) { return (_Donnees == o._Donnees); } // ----------------------------------------------------------------------------- // // Implémentation des méthodes NSSavoir // // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Function : NSSavoirData::NSSavoirData() // Description : Constructeur. // ----------------------------------------------------------------------------- NSSavoirData::NSSavoirData() { #ifndef _ENTERPRISE_DLL // Met les champs de données à zéro memset(code, 0, SAVOIR_CODE_LEN + 1); memset(qualifie, 0, SAVOIR_QUALIFIE_LEN + 1); memset(lien, 0, SAVOIR_LIEN_LEN + 1); memset(qualifiant, 0, SAVOIR_QUALIFIANT_LEN + 1); memset(classe, 0, SAVOIR_CLASSE_LEN + 1); memset(degre, 0, SAVOIR_DEGRE_LEN + 1); memset(scenario, 0, SAVOIR_SCENARIO_LEN + 1); #else _sCode = string(""); _sQualified = string(""); _sLink = string(""); _sQualifier = string(""); _sLevel = string(""); _sClass = string(""); _sScenario = string(""); #endif } // ----------------------------------------------------------------------------- // Fonction : NSPathologData::NSSavoirData(NSSavoirData& rv) // Description : Constructeur copie // Retour : Rien // ----------------------------------------------------------------------------- NSSavoirData::NSSavoirData(NSSavoirData& rv) { #ifndef _ENTERPRISE_DLL strcpy(code, rv.code); strcpy(qualifie, rv.qualifie); strcpy(lien, rv.lien); strcpy(qualifiant, rv.qualifiant); strcpy(degre, rv.degre); strcpy(classe, rv.classe); strcpy(scenario, rv.scenario); #else _sCode = rv._sCode; _sQualified = rv._sQualified; _sLink = rv._sLink; _sQualifier = rv._sQualifier; _sLevel = rv._sLevel; _sClass = rv._sClass; _sScenario = rv._sScenario; #endif } // ----------------------------------------------------------------------------- // Fonction : NSSavoirData::~NSSavoirData() // Description : Destructeur // ----------------------------------------------------------------------------- NSSavoirData::~NSSavoirData() { } // ----------------------------------------------------------------------------- // Fonction : NSSavoirData::operator=(NSSavoirData src) // Description : Opérateur = // Retour : Référence sur l'objet cible // ----------------------------------------------------------------------------- NSSavoirData& NSSavoirData::operator=(NSSavoirData rv) { if (&rv == this) return *this; #ifndef _ENTERPRISE_DLL strcpy(code, rv.code); strcpy(qualifie, rv.qualifie); strcpy(lien, rv.lien); strcpy(qualifiant, rv.qualifiant); strcpy(degre, rv.degre); strcpy(classe, rv.classe); strcpy(scenario, rv.scenario); #else _sCode = rv._sCode; _sQualified = rv._sQualified; _sLink = rv._sLink; _sQualifier = rv._sQualifier; _sLevel = rv._sLevel; _sClass = rv._sClass; _sScenario = rv._sScenario; #endif return *this; } // ----------------------------------------------------------------------------- // Fonction : NSSavoirData::operator=(NSSavoirData src) // Description : Opérateur de comparaison // Retour : 0 ou 1 // ----------------------------------------------------------------------------- int NSSavoirData::operator==(const NSSavoirData& o) { #ifndef _ENTERPRISE_DLL if ((strcmp(code, o.code) == 0)) #else if (_sCode == o._sCode) #endif return 1; else return 0; } // ----------------------------------------------------------------------------- // Function : NSSavoir::NSSavoir(NSSuper* pSuper) // Description : Constructeur. // ----------------------------------------------------------------------------- NSSavoir::NSSavoir(NSSuper* pSuper) #ifndef _ENTERPRISE_DLL :NSFiche(pSuper) #else :NSSuperRoot(pSuper) #endif { // Crée un objet de données pDonnees = new NSSavoirData(); } // ----------------------------------------------------------------------------- // Constructeur copie // ----------------------------------------------------------------------------- NSSavoir::NSSavoir(NSSavoir& rv) #ifndef _ENTERPRISE_DLL :NSFiche(rv._pSuper) #else :NSSuperRoot(rv._pSuper) #endif { // Crée l'objet de données pDonnees = new NSSavoirData(); // Copie les valeurs du NSSavoirInfo d'origine *pDonnees = *(rv.pDonnees); } // ----------------------------------------------------------------------------- // Function : NSSavoir::~NSSavoir() // Description : Destructeur. // ----------------------------------------------------------------------------- NSSavoir::~NSSavoir() { delete pDonnees; } // ----------------------------------------------------------------------------- // Fonction : NSSavoir::alimenteFiche() // Description : Transfère le contenu de pRecBuff dans les variables de la fiche // ----------------------------------------------------------------------------- void NSSavoir::alimenteFiche() { #ifndef _ENTERPRISE_DLL alimenteChamp(pDonnees->code, SAVOIR_CODE_FIELD, SAVOIR_CODE_LEN); alimenteChamp(pDonnees->qualifie, SAVOIR_QUALIFIE_FIELD, SAVOIR_QUALIFIE_LEN); alimenteChamp(pDonnees->lien, SAVOIR_LIEN_FIELD, SAVOIR_LIEN_LEN); alimenteChamp(pDonnees->qualifiant, SAVOIR_QUALIFIANT_FIELD, SAVOIR_QUALIFIANT_LEN); alimenteChamp(pDonnees->degre, SAVOIR_DEGRE_FIELD, SAVOIR_DEGRE_LEN); alimenteChamp(pDonnees->classe, SAVOIR_CLASSE_FIELD, SAVOIR_CLASSE_LEN); alimenteChamp(pDonnees->scenario, SAVOIR_SCENARIO_FIELD, SAVOIR_SCENARIO_LEN); #endif } #ifdef _ENTERPRISE_DLL void NSSavoir::alimenteFiche(MYSQL_ROW *pRow) { if ((MYSQL_ROW *) NULL == pRow) return; if ((*pRow)[SAVOIR_CODE_FIELD-1]) pDonnees->setCode((*pRow)[SAVOIR_CODE_FIELD-1]); if ((*pRow)[SAVOIR_QUALIFIE_FIELD-1]) pDonnees->setQualified((*pRow)[SAVOIR_QUALIFIE_FIELD-1]); if ((*pRow)[SAVOIR_LIEN_FIELD-1]) pDonnees->setLink((*pRow)[SAVOIR_LIEN_FIELD-1]); if ((*pRow)[SAVOIR_QUALIFIANT_FIELD-1]) pDonnees->setQualifier((*pRow)[SAVOIR_QUALIFIANT_FIELD-1]); if ((*pRow)[SAVOIR_DEGRE_FIELD-1]) pDonnees->setLevel((*pRow)[SAVOIR_DEGRE_FIELD-1]); if ((*pRow)[SAVOIR_CLASSE_FIELD-1]) pDonnees->setClass((*pRow)[SAVOIR_CLASSE_FIELD-1]); if ((*pRow)[SAVOIR_SCENARIO_FIELD-1]) pDonnees->setScenario((*pRow)[SAVOIR_SCENARIO_FIELD-1]); } #endif // ----------------------------------------------------------------------------- // Fonction : NSSavoir::videFiche() // Description : Transfère le contenu des valeurs de la fiche dans pRecBuff // ----------------------------------------------------------------------------- void NSSavoir::videFiche() { #ifndef _ENTERPRISE_DLL videChamp(pDonnees->code, SAVOIR_CODE_FIELD, SAVOIR_CODE_LEN); videChamp(pDonnees->qualifie, SAVOIR_QUALIFIE_FIELD, SAVOIR_QUALIFIE_LEN); videChamp(pDonnees->lien, SAVOIR_LIEN_FIELD, SAVOIR_LIEN_LEN); videChamp(pDonnees->qualifiant, SAVOIR_QUALIFIANT_FIELD, SAVOIR_QUALIFIANT_LEN); videChamp(pDonnees->degre, SAVOIR_DEGRE_FIELD, SAVOIR_DEGRE_LEN); videChamp(pDonnees->classe, SAVOIR_CLASSE_FIELD, SAVOIR_CLASSE_LEN); videChamp(pDonnees->scenario, SAVOIR_SCENARIO_FIELD, SAVOIR_SCENARIO_LEN); #endif } #ifdef _ENTERPRISE_DLL bool NSSavoir::executeQuery(string sQuery, bool bVerbose) { if (string("") == sQuery) return false; if (NULL == _pSuper->getDatabaseManager()) return false; MYSQL_RES *pResult = _pSuper->getDatabaseManager()->executeQuery(sQuery, bVerbose); if ((MYSQL_RES *) NULL == pResult) return false; if (mysql_num_rows(pResult) == 0) return false; bool bSucces = true; MYSQL_ROW Row = mysql_fetch_row(pResult); if (Row) alimenteFiche(&Row); else if (bVerbose) { string sErreurMsg = string("Error when fetching row for query [") + sQuery + string("] -> ") + mysql_error(_pSuper->getDatabaseManager()->getConnector()); error(sErreurMsg.c_str(), standardError); bSucces = false; } mysql_free_result(pResult); return bSucces; } #endif // ----------------------------------------------------------------------------- // Fonction : NSSavoir::getRecord() // Description : Prend l'enregistrement en cours et assigne la valeur des // champs aux variables membres de la classe. // Returns : PXERR_, s'il y a lieu // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL DBIResult NSSavoir::getPatRecord() { // La table est-elle ouverte ? if (!isOpen) return (lastError = ERROR_TABLENOTOPEN); // Appel de la classe de base pour récupérer l'enregistrement. lastError = getDbiRecord(dbiWRITELOCK); return (lastError); } #endif // ----------------------------------------------------------------------------- // Description : Ouvre la table primaire et les index secondaires // Returns : PXERR_, s'il y a lieu // ----------------------------------------------------------------------------- #ifndef _ENTERPRISE_DLL DBIResult NSSavoir::open() { char tableName[] = "SAVOIR.DB"; // Appelle la fonction open() de la classe de base pour ouvrir // l'index primaire lastError = NSFiche::open(tableName, NSF_GUIDES); return (lastError); } #endif // ----------------------------------------------------------------------------- // Function : NSSavoir::Create() // ----------------------------------------------------------------------------- bool NSSavoir::Create() { return true; } // ----------------------------------------------------------------------------- // Function : NSSavoir::Modify() // ----------------------------------------------------------------------------- bool NSSavoir::Modify() { return true; } // ----------------------------------------------------------------------------- // Opérateur d'affectation // ----------------------------------------------------------------------------- NSSavoir& NSSavoir::operator=(NSSavoir src) { if (this == &src) return *this; *pDonnees = *(src.pDonnees); return *this; } // ----------------------------------------------------------------------------- // Opérateur de comparaison // ----------------------------------------------------------------------------- int NSSavoir::operator==(const NSSavoir& o) { return (*pDonnees == *(o.pDonnees)); } // ----------------------------------------------------------------------------- // Constructeur par défaut // ----------------------------------------------------------------------------- NSSavoirInfo::NSSavoirInfo() { // Crée l'objet de données pDonnees = new NSSavoirData(); } // ----------------------------------------------------------------------------- // Constructeur à partir d'un NSPatient // ----------------------------------------------------------------------------- NSSavoirInfo::NSSavoirInfo(NSSavoir* pPatho) { // Crée l'objet de données pDonnees = new NSSavoirData(); // Copie les valeurs du NSDocument *pDonnees = *(pPatho->pDonnees); } // ----------------------------------------------------------------------------- // Constructeur copie // ----------------------------------------------------------------------------- NSSavoirInfo::NSSavoirInfo(NSSavoirInfo& rv) { // Crée l'objet de données pDonnees = new NSSavoirData(); // Copie les valeurs du NSSavoirInfo d'origine *pDonnees = *(rv.pDonnees); } // ----------------------------------------------------------------------------- // Destructeur. // ----------------------------------------------------------------------------- NSSavoirInfo::~NSSavoirInfo() { delete pDonnees; } // ----------------------------------------------------------------------------- // Opérateur d'affectation // ----------------------------------------------------------------------------- NSSavoirInfo& NSSavoirInfo::operator=(NSSavoirInfo src) { if (this == &src) return *this; *pDonnees = *(src.pDonnees); return *this; } // ----------------------------------------------------------------------------- // Opérateur de comparaison // ----------------------------------------------------------------------------- int NSSavoirInfo::operator==(const NSSavoirInfo& o) { return (*pDonnees == *(o.pDonnees)); } // ----------------------------------------------------------------------------- // // BASE DES MEDICAMENTS // // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // Constructeur // ----------------------------------------------------------------------------- NSLexiMed::NSLexiMed(NSSuper* pSuper, string sLangue) :NSPatholog(pSuper, sLangue) { } // ----------------------------------------------------------------------------- // Constructeur copie // ----------------------------------------------------------------------------- NSLexiMed::NSLexiMed(NSLexiMed& rv) :NSPatholog(rv._pSuper, rv._sLangue) { } // ----------------------------------------------------------------------------- // Destructeur // ----------------------------------------------------------------------------- NSLexiMed::~NSLexiMed() { } #ifndef _ENTERPRISE_DLL DBIResult NSLexiMed::open() { char tableName[] = "LEXI_MED.DB"; // Appelle la fonction open() de la classe de base pour ouvrir l'index primaire lastError = NSFiche::open(tableName, NSF_GUIDES); return (lastError); } #endif
28.365397
158
0.498932
[ "vector" ]
adabff6d1b260030365c7fd23e2defcd00e72b25
32,312
cpp
C++
draft/mf_player.cpp
smallsoft-rus/media-player
6217cb7c42b152ba0a4e410625ca86964e35f5b5
[ "BSD-3-Clause" ]
null
null
null
draft/mf_player.cpp
smallsoft-rus/media-player
6217cb7c42b152ba0a4e410625ca86964e35f5b5
[ "BSD-3-Clause" ]
9
2021-04-10T09:24:53.000Z
2022-03-26T15:35:02.000Z
draft/mf_player.cpp
smallsoft-rus/media-player
6217cb7c42b152ba0a4e410625ca86964e35f5b5
[ "BSD-3-Clause" ]
null
null
null
//https://docs.microsoft.com/en-us/windows/win32/medfound/media-session-playback-example #include <stdio.h> #include <windows.h> #include <shobjidl.h> #include <shlwapi.h> #include <strsafe.h> #include <assert.h> #include <new> // Media Foundation headers #include <mfapi.h> #include <mfidl.h> #include <mferror.h> #include <evr.h> #pragma comment(lib, "shlwapi") #pragma comment(lib, "Mf.lib") #pragma comment(lib, "Mfplat.lib") PWSTR pszFilePath = L"C:\\Media\\file.avi"; #define MY_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ EXTERN_C const GUID DECLSPEC_SELECTANY name \ = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } MY_DEFINE_GUID(MFMediaType_Audio, 0x73647561, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); MY_DEFINE_GUID(MFMediaType_Video, 0x73646976, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); MY_DEFINE_GUID(MF_EVENT_TOPOLOGY_STATUS, 0x30c5018d, 0x9a53, 0x454b, 0xad, 0x9e, 0x6d, 0x5f, 0x8f, 0xa7, 0xc4, 0x3b); MY_DEFINE_GUID(MR_VIDEO_RENDER_SERVICE, 0x1092a86c, 0xab1a, 0x459a, 0xa3, 0x36, 0x83, 0x1f, 0xbc, 0x4d, 0x11, 0xff ); const UINT WM_APP_PLAYER_EVENT = WM_APP + 1; // WPARAM = IMFMediaEvent*, WPARAM = MediaEventType template <class T> void SafeRelease(T **ppT) { if (*ppT) { (*ppT)->Release(); *ppT = NULL; } } enum PlayerState { Closed = 0, // No session. Ready, // Session was created, ready to open a file. OpenPending, // Session is opening a file. Started, // Session is playing a file. Paused, // Session is paused. Stopped, // Session is stopped (ready to play). Closing // Application has closed the session, but is waiting for MESessionClosed. }; HRESULT CreateMediaSource(PCWSTR pszURL, IMFMediaSource **ppSource); HRESULT CreatePlaybackTopology(IMFMediaSource *pSource, IMFPresentationDescriptor *pPD, HWND hVideoWnd,IMFTopology **ppTopology); class CPlayer : public IMFAsyncCallback { public: static HRESULT CreateInstance(HWND hVideo, HWND hEvent, CPlayer **ppPlayer); // IUnknown methods STDMETHODIMP QueryInterface(REFIID iid, void** ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IMFAsyncCallback methods STDMETHODIMP GetParameters(DWORD*, DWORD*) { // Implementation of this method is optional. return E_NOTIMPL; } STDMETHODIMP Invoke(IMFAsyncResult* pAsyncResult); // Playback HRESULT OpenURL(const WCHAR *sURL); HRESULT Play(); HRESULT Pause(); HRESULT Stop(); HRESULT Shutdown(); HRESULT HandleEvent(UINT_PTR pUnkPtr); PlayerState GetState() const { return m_state; } // Video functionality HRESULT Repaint(); HRESULT ResizeVideo(WORD width, WORD height); BOOL HasVideo() const { return (m_pVideoDisplay != NULL); } protected: // Constructor is private. Use static CreateInstance method to instantiate. CPlayer(HWND hVideo, HWND hEvent); // Destructor is private. Caller should call Release. virtual ~CPlayer(); HRESULT Initialize(); HRESULT CreateSession(); HRESULT CloseSession(); HRESULT StartPlayback(); // Media event handlers virtual HRESULT OnTopologyStatus(IMFMediaEvent *pEvent); virtual HRESULT OnPresentationEnded(IMFMediaEvent *pEvent); virtual HRESULT OnNewPresentation(IMFMediaEvent *pEvent); // Override to handle additional session events. virtual HRESULT OnSessionEvent(IMFMediaEvent*, MediaEventType) { return S_OK; } protected: long m_nRefCount; // Reference count. IMFMediaSession *m_pSession; IMFMediaSource *m_pSource; IMFVideoDisplayControl *m_pVideoDisplay; HWND m_hwndVideo; // Video window. HWND m_hwndEvent; // App window to receive events. PlayerState m_state; // Current state of the media session. HANDLE m_hCloseEvent; // Event to wait on while closing. }; template <class Q> HRESULT GetEventObject(IMFMediaEvent *pEvent, Q **ppObject) { *ppObject = NULL; // zero output PROPVARIANT var; HRESULT hr = pEvent->GetValue(&var); if (SUCCEEDED(hr)) { if (var.vt == VT_UNKNOWN) { hr = var.punkVal->QueryInterface(ppObject); } else { hr = MF_E_INVALIDTYPE; } PropVariantClear(&var); } return hr; } HRESULT CreateMediaSource(PCWSTR pszURL, IMFMediaSource **ppSource); HRESULT CreatePlaybackTopology(IMFMediaSource *pSource, IMFPresentationDescriptor *pPD, HWND hVideoWnd,IMFTopology **ppTopology); // Static class method to create the CPlayer object. HRESULT CPlayer::CreateInstance( HWND hVideo, // Video window. HWND hEvent, // Window to receive notifications. CPlayer **ppPlayer) // Receives a pointer to the CPlayer object. { if (ppPlayer == NULL) { return E_POINTER; } CPlayer *pPlayer = new (std::nothrow) CPlayer(hVideo, hEvent); if (pPlayer == NULL) { return E_OUTOFMEMORY; } HRESULT hr = pPlayer->Initialize(); if (SUCCEEDED(hr)) { *ppPlayer = pPlayer; } else { pPlayer->Release(); } return hr; } HRESULT CPlayer::Initialize() { // Start up Media Foundation platform. HRESULT hr = MFStartup(MF_VERSION); if (SUCCEEDED(hr)) { m_hCloseEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (m_hCloseEvent == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); } } return hr; } CPlayer::CPlayer(HWND hVideo, HWND hEvent) : m_pSession(NULL), m_pSource(NULL), m_pVideoDisplay(NULL), m_hwndVideo(hVideo), m_hwndEvent(hEvent), m_state(Closed), m_hCloseEvent(NULL), m_nRefCount(1) { } CPlayer::~CPlayer() { assert(m_pSession == NULL); // If FALSE, the app did not call Shutdown(). // When CPlayer calls IMediaEventGenerator::BeginGetEvent on the // media session, it causes the media session to hold a reference // count on the CPlayer. // This creates a circular reference count between CPlayer and the // media session. Calling Shutdown breaks the circular reference // count. // If CreateInstance fails, the application will not call // Shutdown. To handle that case, call Shutdown in the destructor. Shutdown(); } // IUnknown methods HRESULT CPlayer::QueryInterface(REFIID riid, void** ppv) { static const QITAB qit[] = { QITABENT(CPlayer, IMFAsyncCallback), { 0 } }; return QISearch(this, qit, riid, ppv); } ULONG CPlayer::AddRef() { return InterlockedIncrement(&m_nRefCount); } ULONG CPlayer::Release() { ULONG uCount = InterlockedDecrement(&m_nRefCount); if (uCount == 0) { delete this; } return uCount; } // Open a URL for playback. HRESULT CPlayer::OpenURL(const WCHAR *sURL) { // 1. Create a new media session. // 2. Create the media source. // 3. Create the topology. // 4. Queue the topology [asynchronous] // 5. Start playback [asynchronous - does not happen in this method.] IMFTopology *pTopology = NULL; IMFPresentationDescriptor* pSourcePD = NULL; // Create the media session. HRESULT hr = CreateSession(); if (FAILED(hr)) { goto done; } // Create the media source. hr = CreateMediaSource(sURL, &m_pSource); if (FAILED(hr)) { goto done; } // Create the presentation descriptor for the media source. hr = m_pSource->CreatePresentationDescriptor(&pSourcePD); if (FAILED(hr)) { goto done; } // Create a partial topology. hr = CreatePlaybackTopology(m_pSource, pSourcePD, m_hwndVideo, &pTopology); if (FAILED(hr)) { goto done; } // Set the topology on the media session. hr = m_pSession->SetTopology(0, pTopology); if (FAILED(hr)) { goto done; } m_state = OpenPending; // If SetTopology succeeds, the media session will queue an // MESessionTopologySet event. done: if (FAILED(hr)) { m_state = Closed; } SafeRelease(&pSourcePD); SafeRelease(&pTopology); return hr; } // Pause playback. HRESULT CPlayer::Pause() { if (m_state != Started) { return MF_E_INVALIDREQUEST; } if (m_pSession == NULL || m_pSource == NULL) { return E_UNEXPECTED; } HRESULT hr = m_pSession->Pause(); if (SUCCEEDED(hr)) { m_state = Paused; } return hr; } // Stop playback. HRESULT CPlayer::Stop() { if (m_state != Started && m_state != Paused) { return MF_E_INVALIDREQUEST; } if (m_pSession == NULL) { return E_UNEXPECTED; } HRESULT hr = m_pSession->Stop(); if (SUCCEEDED(hr)) { m_state = Stopped; } return hr; } // Repaint the video window. Call this method on WM_PAINT. HRESULT CPlayer::Repaint() { if (m_pVideoDisplay) { return m_pVideoDisplay->RepaintVideo(); } else { return S_OK; } } // Resize the video rectangle. // // Call this method if the size of the video window changes. HRESULT CPlayer::ResizeVideo(WORD width, WORD height) { if (m_pVideoDisplay) { // Set the destination rectangle. // Leave the default source rectangle (0,0,1,1). RECT rcDest = { 0, 0, width, height }; return m_pVideoDisplay->SetVideoPosition(NULL, &rcDest); } else { return S_OK; } } // Callback for the asynchronous BeginGetEvent method. HRESULT CPlayer::Invoke(IMFAsyncResult *pResult) { MediaEventType meType = MEUnknown; // Event type IMFMediaEvent *pEvent = NULL; // Get the event from the event queue. HRESULT hr = m_pSession->EndGetEvent(pResult, &pEvent); if (FAILED(hr)) { goto done; } // Get the event type. hr = pEvent->GetType(&meType); if (FAILED(hr)) { goto done; } if (meType == MESessionClosed) { // The session was closed. // The application is waiting on the m_hCloseEvent event handle. SetEvent(m_hCloseEvent); } else { // For all other events, get the next event in the queue. hr = m_pSession->BeginGetEvent(this, NULL); if (FAILED(hr)) { goto done; } } // Check the application state. // If a call to IMFMediaSession::Close is pending, it means the // application is waiting on the m_hCloseEvent event and // the application's message loop is blocked. // Otherwise, post a private window message to the application. if (m_state != Closing) { // Leave a reference count on the event. pEvent->AddRef(); PostMessage(m_hwndEvent, WM_APP_PLAYER_EVENT, (WPARAM)pEvent, (LPARAM)meType); } done: SafeRelease(&pEvent); return S_OK; } HRESULT CPlayer::HandleEvent(UINT_PTR pEventPtr) { HRESULT hrStatus = S_OK; MediaEventType meType = MEUnknown; IMFMediaEvent *pEvent = (IMFMediaEvent*)pEventPtr; if (pEvent == NULL) { return E_POINTER; } // Get the event type. HRESULT hr = pEvent->GetType(&meType); if (FAILED(hr)) { goto done; } // Get the event status. If the operation that triggered the event // did not succeed, the status is a failure code. hr = pEvent->GetStatus(&hrStatus); // Check if the async operation succeeded. if (SUCCEEDED(hr) && FAILED(hrStatus)) { hr = hrStatus; } if (FAILED(hr)) { goto done; } switch(meType) { case MESessionTopologyStatus: hr = OnTopologyStatus(pEvent); break; case MEEndOfPresentation: hr = OnPresentationEnded(pEvent); break; case MENewPresentation: hr = OnNewPresentation(pEvent); break; default: hr = OnSessionEvent(pEvent, meType); break; } done: SafeRelease(&pEvent); return hr; } // Release all resources held by this object. HRESULT CPlayer::Shutdown() { // Close the session HRESULT hr = CloseSession(); // Shutdown the Media Foundation platform MFShutdown(); if (m_hCloseEvent) { CloseHandle(m_hCloseEvent); m_hCloseEvent = NULL; } return hr; } /// Protected methods HRESULT CPlayer::OnTopologyStatus(IMFMediaEvent *pEvent) { UINT32 status; HRESULT hr = pEvent->GetUINT32(MF_EVENT_TOPOLOGY_STATUS, &status); if (SUCCEEDED(hr) && (status == MF_TOPOSTATUS_READY)) { SafeRelease(&m_pVideoDisplay); // Get the IMFVideoDisplayControl interface from EVR. This call is // expected to fail if the media file does not have a video stream. (void)MFGetService(m_pSession, MR_VIDEO_RENDER_SERVICE, IID_PPV_ARGS(&m_pVideoDisplay)); hr = StartPlayback(); } return hr; } // Handler for MEEndOfPresentation event. HRESULT CPlayer::OnPresentationEnded(IMFMediaEvent *pEvent) { // The session puts itself into the stopped state automatically. m_state = Stopped; return S_OK; } // Handler for MENewPresentation event. // // This event is sent if the media source has a new presentation, which // requires a new topology. HRESULT CPlayer::OnNewPresentation(IMFMediaEvent *pEvent) { IMFPresentationDescriptor *pPD = NULL; IMFTopology *pTopology = NULL; // Get the presentation descriptor from the event. HRESULT hr = GetEventObject(pEvent, &pPD); if (FAILED(hr)) { goto done; } // Create a partial topology. hr = CreatePlaybackTopology(m_pSource, pPD, m_hwndVideo,&pTopology); if (FAILED(hr)) { goto done; } // Set the topology on the media session. hr = m_pSession->SetTopology(0, pTopology); if (FAILED(hr)) { goto done; } m_state = OpenPending; done: SafeRelease(&pTopology); SafeRelease(&pPD); return S_OK; } // Create a new instance of the media session. HRESULT CPlayer::CreateSession() { // Close the old session, if any. HRESULT hr = CloseSession(); if (FAILED(hr)) { goto done; } assert(m_state == Closed); // Create the media session. hr = MFCreateMediaSession(NULL, &m_pSession); if (FAILED(hr)) { goto done; } // Start pulling events from the media session hr = m_pSession->BeginGetEvent((IMFAsyncCallback*)this, NULL); if (FAILED(hr)) { goto done; } m_state = Ready; done: return hr; } // Close the media session. HRESULT CPlayer::CloseSession() { // The IMFMediaSession::Close method is asynchronous, but the // CPlayer::CloseSession method waits on the MESessionClosed event. // // MESessionClosed is guaranteed to be the last event that the // media session fires. HRESULT hr = S_OK; SafeRelease(&m_pVideoDisplay); // First close the media session. if (m_pSession) { DWORD dwWaitResult = 0; m_state = Closing; hr = m_pSession->Close(); // Wait for the close operation to complete if (SUCCEEDED(hr)) { dwWaitResult = WaitForSingleObject(m_hCloseEvent, 5000); if (dwWaitResult == WAIT_TIMEOUT) { assert(FALSE); } // Now there will be no more events from this session. } } // Complete shutdown operations. if (SUCCEEDED(hr)) { // Shut down the media source. (Synchronous operation, no events.) if (m_pSource) { (void)m_pSource->Shutdown(); } // Shut down the media session. (Synchronous operation, no events.) if (m_pSession) { (void)m_pSession->Shutdown(); } } SafeRelease(&m_pSource); SafeRelease(&m_pSession); m_state = Closed; return hr; } // Start playback from the current position. HRESULT CPlayer::StartPlayback() { assert(m_pSession != NULL); PROPVARIANT varStart; PropVariantInit(&varStart); HRESULT hr = m_pSession->Start(&GUID_NULL, &varStart); if (SUCCEEDED(hr)) { // Note: Start is an asynchronous operation. However, we // can treat our state as being already started. If Start // fails later, we'll get an MESessionStarted event with // an error code, and we will update our state then. m_state = Started; } PropVariantClear(&varStart); return hr; } // Start playback from paused or stopped. HRESULT CPlayer::Play() { if (m_state != Paused && m_state != Stopped) { return MF_E_INVALIDREQUEST; } if (m_pSession == NULL || m_pSource == NULL) { return E_UNEXPECTED; } return StartPlayback(); } // Create a media source from a URL. HRESULT CreateMediaSource(PCWSTR sURL, IMFMediaSource **ppSource) { MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID; IMFSourceResolver* pSourceResolver = NULL; IUnknown* pSource = NULL; // Create the source resolver. HRESULT hr = MFCreateSourceResolver(&pSourceResolver); if (FAILED(hr)) { goto done; } // Use the source resolver to create the media source. // Note: For simplicity this sample uses the synchronous method to create // the media source. However, creating a media source can take a noticeable // amount of time, especially for a network source. For a more responsive // UI, use the asynchronous BeginCreateObjectFromURL method. hr = pSourceResolver->CreateObjectFromURL( sURL, // URL of the source. MF_RESOLUTION_MEDIASOURCE, // Create a source object. NULL, // Optional property store. &ObjectType, // Receives the created object type. &pSource // Receives a pointer to the media source. ); if (FAILED(hr)) { goto done; } // Get the IMFMediaSource interface from the media source. hr = pSource->QueryInterface(IID_PPV_ARGS(ppSource)); done: SafeRelease(&pSourceResolver); SafeRelease(&pSource); return hr; } // Create an activation object for a renderer, based on the stream media type. HRESULT CreateMediaSinkActivate( IMFStreamDescriptor *pSourceSD, // Pointer to the stream descriptor. HWND hVideoWindow, // Handle to the video clipping window. IMFActivate **ppActivate ) { IMFMediaTypeHandler *pHandler = NULL; IMFActivate *pActivate = NULL; // Get the media type handler for the stream. HRESULT hr = pSourceSD->GetMediaTypeHandler(&pHandler); if (FAILED(hr)) { goto done; } // Get the major media type. GUID guidMajorType; hr = pHandler->GetMajorType(&guidMajorType); if (FAILED(hr)) { goto done; } // Create an IMFActivate object for the renderer, based on the media type. if (MFMediaType_Audio == guidMajorType) { // Create the audio renderer. hr = MFCreateAudioRendererActivate(&pActivate); } else if (MFMediaType_Video == guidMajorType) { // Create the video renderer. hr = MFCreateVideoRendererActivate(hVideoWindow, &pActivate); } else { // Unknown stream type. hr = E_FAIL; // Optionally, you could deselect this stream instead of failing. } if (FAILED(hr)) { goto done; } // Return IMFActivate pointer to caller. *ppActivate = pActivate; (*ppActivate)->AddRef(); done: SafeRelease(&pHandler); SafeRelease(&pActivate); return hr; } // Add a source node to a topology. HRESULT AddSourceNode( IMFTopology *pTopology, // Topology. IMFMediaSource *pSource, // Media source. IMFPresentationDescriptor *pPD, // Presentation descriptor. IMFStreamDescriptor *pSD, // Stream descriptor. IMFTopologyNode **ppNode) // Receives the node pointer. { IMFTopologyNode *pNode = NULL; // Create the node. HRESULT hr = MFCreateTopologyNode(MF_TOPOLOGY_SOURCESTREAM_NODE, &pNode); if (FAILED(hr)) { goto done; } // Set the attributes. hr = pNode->SetUnknown(MF_TOPONODE_SOURCE, pSource); if (FAILED(hr)) { goto done; } hr = pNode->SetUnknown(MF_TOPONODE_PRESENTATION_DESCRIPTOR, pPD); if (FAILED(hr)) { goto done; } hr = pNode->SetUnknown(MF_TOPONODE_STREAM_DESCRIPTOR, pSD); if (FAILED(hr)) { goto done; } // Add the node to the topology. hr = pTopology->AddNode(pNode); if (FAILED(hr)) { goto done; } // Return the pointer to the caller. *ppNode = pNode; (*ppNode)->AddRef(); done: SafeRelease(&pNode); return hr; } // Add an output node to a topology. HRESULT AddOutputNode( IMFTopology *pTopology, // Topology. IMFActivate *pActivate, // Media sink activation object. DWORD dwId, // Identifier of the stream sink. IMFTopologyNode **ppNode) // Receives the node pointer. { IMFTopologyNode *pNode = NULL; // Create the node. HRESULT hr = MFCreateTopologyNode(MF_TOPOLOGY_OUTPUT_NODE, &pNode); if (FAILED(hr)) { goto done; } // Set the object pointer. hr = pNode->SetObject(pActivate); if (FAILED(hr)) { goto done; } // Set the stream sink ID attribute. hr = pNode->SetUINT32(MF_TOPONODE_STREAMID, dwId); if (FAILED(hr)) { goto done; } hr = pNode->SetUINT32(MF_TOPONODE_NOSHUTDOWN_ON_REMOVE, FALSE); if (FAILED(hr)) { goto done; } // Add the node to the topology. hr = pTopology->AddNode(pNode); if (FAILED(hr)) { goto done; } // Return the pointer to the caller. *ppNode = pNode; (*ppNode)->AddRef(); done: SafeRelease(&pNode); return hr; } //</SnippetPlayer.cpp> // Add a topology branch for one stream. // // For each stream, this function does the following: // // 1. Creates a source node associated with the stream. // 2. Creates an output node for the renderer. // 3. Connects the two nodes. // // The media session will add any decoders that are needed. HRESULT AddBranchToPartialTopology( IMFTopology *pTopology, // Topology. IMFMediaSource *pSource, // Media source. IMFPresentationDescriptor *pPD, // Presentation descriptor. DWORD iStream, // Stream index. HWND hVideoWnd) // Window for video playback. { IMFStreamDescriptor *pSD = NULL; IMFActivate *pSinkActivate = NULL; IMFTopologyNode *pSourceNode = NULL; IMFTopologyNode *pOutputNode = NULL; BOOL fSelected = FALSE; HRESULT hr = pPD->GetStreamDescriptorByIndex(iStream, &fSelected, &pSD); if (FAILED(hr)) { goto done; } if (fSelected) { // Create the media sink activation object. hr = CreateMediaSinkActivate(pSD, hVideoWnd, &pSinkActivate); if (FAILED(hr)) { goto done; } // Add a source node for this stream. hr = AddSourceNode(pTopology, pSource, pPD, pSD, &pSourceNode); if (FAILED(hr)) { goto done; } // Create the output node for the renderer. hr = AddOutputNode(pTopology, pSinkActivate, 0, &pOutputNode); if (FAILED(hr)) { goto done; } // Connect the source node to the output node. hr = pSourceNode->ConnectOutput(0, pOutputNode, 0); } // else: If not selected, don't add the branch. done: SafeRelease(&pSD); SafeRelease(&pSinkActivate); SafeRelease(&pSourceNode); SafeRelease(&pOutputNode); return hr; } // Create a playback topology from a media source. HRESULT CreatePlaybackTopology( IMFMediaSource *pSource, // Media source. IMFPresentationDescriptor *pPD, // Presentation descriptor. HWND hVideoWnd, // Video window. IMFTopology **ppTopology) // Receives a pointer to the topology. { IMFTopology *pTopology = NULL; DWORD cSourceStreams = 0; // Create a new topology. HRESULT hr = MFCreateTopology(&pTopology); if (FAILED(hr)) { goto done; } // Get the number of streams in the media source. hr = pPD->GetStreamDescriptorCount(&cSourceStreams); if (FAILED(hr)) { goto done; } // For each stream, create the topology nodes and add them to the topology. for (DWORD i = 0; i < cSourceStreams; i++) { hr = AddBranchToPartialTopology(pTopology, pSource, pPD, i, hVideoWnd); if (FAILED(hr)) { goto done; } } // Return the IMFTopology pointer to the caller. *ppTopology = pTopology; (*ppTopology)->AddRef(); done: SafeRelease(&pTopology); return hr; } //***** Application ********* PCWSTR szTitle = L"BasicPlayback"; PCWSTR szWindowClass = L"MFBASICPLAYBACK"; HINSTANCE g_hInstance; // current instance BOOL g_bRepaintClient = TRUE; // Repaint the application client area? CPlayer *g_pPlayer = NULL; // Global player object. HWND hWnd=NULL; // Note: After WM_CREATE is processed, g_pPlayer remains valid until the // window is destroyed. // Forward declarations of functions included in this code module: BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK OpenUrlDialogProc(HWND, UINT, WPARAM, LPARAM); void NotifyError(HWND hwnd, const WCHAR *sErrorMessage, HRESULT hr); void UpdateUI(HWND hwnd, PlayerState state); HRESULT AllocGetWindowText(HWND hwnd, WCHAR **pszText, DWORD *pcchLen); // Message handlers LRESULT OnCreateWindow(HWND hwnd); void OnFileOpen(HWND hwnd); void OnOpenURL(HWND hwnd); void OnPlayerEvent(HWND hwnd, WPARAM pUnkPtr); void OnPaint(HWND hwnd); void OnResize(WORD width, WORD height); void OnKeyPress(WPARAM key); // Create the application window. BOOL InitInstance(HINSTANCE hInst, int nCmdShow) { WNDCLASSEX wcex; g_hInstance = hInst; // Store the instance handle. // Register the window class. ZeroMemory(&wcex, sizeof(WNDCLASSEX)); wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.hInstance = hInst; wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.hCursor = LoadCursor(NULL,IDC_ARROW); wcex.lpszClassName = szWindowClass; if (RegisterClassEx(&wcex) == 0) { return FALSE; } // Create the application window. hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInst, NULL); if (hWnd == 0) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // Message handler for the main window. LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT res=0; switch (message) { case WM_CREATE: res= OnCreateWindow(hwnd); return res; case WM_PAINT: OnPaint(hwnd); break; case WM_SIZE: OnResize(LOWORD(lParam), HIWORD(lParam)); break; case WM_ERASEBKGND: // Suppress window erasing, to reduce flickering while the video is playing. return 1; case WM_DESTROY: PostQuitMessage(0); break; case WM_CHAR: OnKeyPress(wParam); break; case WM_APP_PLAYER_EVENT: OnPlayerEvent(hwnd, wParam); break; default: return DefWindowProc(hwnd, message, wParam, lParam); } return 0; } // Open an audio/video file. void OnFileOpen(PWSTR file) { // Display the file name to the user. HRESULT hr = g_pPlayer->OpenURL(file); if (SUCCEEDED(hr)) { UpdateUI(hWnd, OpenPending); } done: if (FAILED(hr)) { NotifyError(hWnd, L"Could not open the file.", hr); UpdateUI(hWnd, Closed); } } // Handler for WM_CREATE message. LRESULT OnCreateWindow(HWND hwnd) { // Initialize the player object. HRESULT hr = CPlayer::CreateInstance(hwnd, hwnd, &g_pPlayer); if (SUCCEEDED(hr)) { UpdateUI(hwnd, Closed); return 0; // Success. } else { NotifyError(NULL, L"Could not initialize the player object.", hr); return -1; // Destroy the window } } // Handler for WM_PAINT messages. void OnPaint(HWND hwnd) { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps); if (g_pPlayer && g_pPlayer->HasVideo()) { // Video is playing. Ask the player to repaint. g_pPlayer->Repaint(); } else { // The video is not playing, so we must paint the application window. RECT rc; GetClientRect(hwnd, &rc); FillRect(hdc, &rc, (HBRUSH) COLOR_WINDOW); } EndPaint(hwnd, &ps); } // Handler for WM_SIZE messages. void OnResize(WORD width, WORD height) { if (g_pPlayer) { g_pPlayer->ResizeVideo(width, height); } } // Handler for WM_CHAR messages. void OnKeyPress(WPARAM key) { switch (key) { // Space key toggles between running and paused case VK_SPACE: if (g_pPlayer->GetState() == Started) { g_pPlayer->Pause(); } else if (g_pPlayer->GetState() == Paused) { g_pPlayer->Play(); } break; } } // Update the application UI to reflect the current state. void UpdateUI(HWND hwnd, PlayerState state) { BOOL bWaiting = FALSE; BOOL bPlayback = FALSE; assert(g_pPlayer != NULL); switch (state) { case OpenPending: bWaiting = TRUE; break; case Started: bPlayback = TRUE; break; case Paused: bPlayback = TRUE; break; } if (bPlayback && g_pPlayer->HasVideo()) { g_bRepaintClient = FALSE; } else { g_bRepaintClient = TRUE; } } // Show a message box with an error message. void NotifyError(HWND hwnd, PCWSTR pszErrorMessage, HRESULT hrErr) { const size_t MESSAGE_LEN = 512; WCHAR message[MESSAGE_LEN]; if (SUCCEEDED(StringCchPrintf(message, MESSAGE_LEN, L"%s (HRESULT = 0x%X)", pszErrorMessage, hrErr))) { MessageBox(hwnd, message, NULL, MB_OK | MB_ICONERROR); } } // Handler for Media Session events. void OnPlayerEvent(HWND hwnd, WPARAM pUnkPtr) { HRESULT hr = g_pPlayer->HandleEvent(pUnkPtr); if (FAILED(hr)) { NotifyError(hwnd, L"OnPlayerEvent error", hr); } UpdateUI(hwnd, g_pPlayer->GetState()); } //******************************************************* int main() { // Perform application initialization. if (!InitInstance(GetModuleHandle(NULL), SW_SHOW)) { NotifyError(NULL, L"Could not initialize the application.", HRESULT_FROM_WIN32(GetLastError())); return FALSE; } OnFileOpen(pszFilePath); g_pPlayer->Play(); MSG msg; ZeroMemory(&msg, sizeof(msg)); // Main message loop. while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Clean up. if (g_pPlayer) { g_pPlayer->Shutdown(); SafeRelease(&g_pPlayer); } return 0; }
24.095451
96
0.613425
[ "object" ]
adb4ca52d2c6ce34e9b0d5d0895d8cf0075f358d
3,410
hpp
C++
src/nctx/topology/dijkstra_ctx.hpp
nctx/py3nctx
ee01aeaf675bbfd38dc4f37115d577a7796d2c80
[ "MIT" ]
2
2021-06-28T10:12:12.000Z
2021-07-12T04:04:30.000Z
src/nctx/topology/dijkstra_ctx.hpp
nctx/py3nctx
ee01aeaf675bbfd38dc4f37115d577a7796d2c80
[ "MIT" ]
null
null
null
src/nctx/topology/dijkstra_ctx.hpp
nctx/py3nctx
ee01aeaf675bbfd38dc4f37115d577a7796d2c80
[ "MIT" ]
null
null
null
// Authors: Mirco Schoenfeld #ifndef _ALG_CTX_DIJDP_H #define _ALG_CTX_DIJDP_H #include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp> using namespace boost; namespace nctx { // DocString: dijkstra_ctx /** * @brief Obtain shortest paths with dynamic contextual constraints. * * Single-source shortest paths using Dijkstra's algorithm taking into account contextual constraints. Enforcement of constraints is the task of the given user-defined function. * * The function enforcing contextual constraints is evaluated at each node during shortest path discovery. The function needs to evaluate to ``true`` or ``false`` allowing an edge to be visited or not. As parameters, the function needs to accept the starting node of path traversal, the current node, and the descending node in question. If the function returns False, the descending node is not being visited. Passing the start vertex is unnecessary here. However, the signature is the same as for the other functions for usability reasons. * * The three nodes are passed as indices allowing for access of (external) attribute and other associated information. * * Note that the decision function is evaluated more than once during path traversal. That means, there should not happen any resource-intense computation inside this function. Also, it does not allow to keep track of the status of calculation, e.g. by calculating the visited edges or something similar. * * If the decision function simply returns True all the time, the set of shortest paths is the unaltered set of shortest paths expected by the classical Dijkstra-implementation. * * @param g The graph object * @param s The source vertex * @param decision_fct A function enforcing constraints. The signature of the function is ``(vertex index, vertex index, vertex index) -> bool``, i.e. the function expects three vertex IDs for the start, the current, and the next vertex. It must evaluate to ``bool``. Passing the start vertex is unnecessary here. However, the signature is the same as for the other functions for usability reasons. * */ template <typename Graph, typename Param, typename Tag, typename Rest, typename DistanceMap, typename WeightMap, typename DecisionFunction, typename PredecessorMap, typename DistanceInfType> inline void dijkstra_ctx_dispatch(const Graph& g, typename graph_traits<Graph>::vertex_descriptor start, const bgl_named_params<Param,Tag,Rest>& params, DistanceMap &distancemap, WeightMap &weightmap, PredecessorMap &pred, typename property_traits<PredecessorMap>::value_type pred_undef, DecisionFunction &decision_fct, DistanceInfType distance_infinity){ typedef context_dijkstra_visitor<Graph, DistanceMap, WeightMap, PredecessorMap, DistanceInfType> visitor_type; visitor_type visitor(start, distancemap, weightmap, decision_fct, pred, pred_undef, distance_infinity); boost::dijkstra_shortest_paths_no_color_map(g, start, params .visitor(visitor)); } }// end namespace nctx #endif
57.79661
543
0.699707
[ "object" ]
adc11db7163316d39dd314944e411b50d648d3c6
15,420
cpp
C++
DynusTparser/computeVolumes.cpp
meitiv-tti/paths
36b4d8e2327a2914fb345afadf228e44b92d7083
[ "MIT" ]
null
null
null
DynusTparser/computeVolumes.cpp
meitiv-tti/paths
36b4d8e2327a2914fb345afadf228e44b92d7083
[ "MIT" ]
null
null
null
DynusTparser/computeVolumes.cpp
meitiv-tti/paths
36b4d8e2327a2914fb345afadf228e44b92d7083
[ "MIT" ]
1
2022-01-18T14:48:21.000Z
2022-01-18T14:48:21.000Z
#include "csv.h" #include <unordered_map> #include <map> #include <set> #include <list> #include <cmath> #include <vector> #include <string> #include <fstream> #include <iostream> #include <functional> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/bzip2.hpp> #include <boost/functional/hash.hpp> using namespace std; using namespace io; using namespace boost; using namespace boost::iostreams; struct VolumeBin { int intervalID; int speed; int vehType; int fromNodeID; int toNodeID; }; class volHash { public: size_t operator()(const VolumeBin& v) const { size_t result = 0; hash_combine(result,v.intervalID); hash_combine(result,v.speed); hash_combine(result,v.vehType); hash_combine(result,v.fromNodeID); hash_combine(result,v.toNodeID); return result; } }; class volEq { public: bool operator()(const VolumeBin& v1,const VolumeBin& v2) const { return v1.intervalID == v2.intervalID && v1.speed == v2.speed && \ v1.vehType == v2.vehType && v1.fromNodeID == v2.fromNodeID && \ v1.toNodeID == v2.toNodeID; } }; struct LinkBin { int fromNodeID; int toNodeID; int vehType; }; class linkHash { public: size_t operator()(const LinkBin& l) const { size_t result = 0; hash_combine(result,l.fromNodeID); hash_combine(result,l.toNodeID); hash_combine(result,l.vehType); return result; } }; class linkEq { public: bool operator()(const LinkBin& l1,const LinkBin& l2) const { return l1.fromNodeID == l2.fromNodeID && \ l1.toNodeID == l2.toNodeID && l1.vehType == l2.vehType; } }; typedef unordered_map<VolumeBin,double,volHash,volEq> volMap; typedef unordered_map<LinkBin,double,linkHash,linkEq> linkDataMap; typedef map<pair<int,int>,double> linkMap; string cut(string &line,int start,int length) { string text = line.substr(start,length); trim(text); return text; } class Vehicle { int upstreamNode; // A node of the origin link double originLinkFrac; vector<int> trajectory; // nodeIDs double startTime; // in min from midnight vector<double> nodeArrivalTimes,signalDelays,tolls; public: int vehType; int ID; string text; void parseVehicleHeader(string &line) { ID = lexical_cast<int>(cut(line,0,9)); originLinkFrac = lexical_cast<double>(cut(line,95,12)); vehType = lexical_cast<int>(cut(line,37,6)); startTime = lexical_cast<double>(cut(line,23,8)); upstreamNode = lexical_cast<int>(cut(line,9,7)); } void parseTrajBlock(list<string> &lines,bool incomplete) { // parser the header string line = lines.front(); lines.pop_front(); int traversedNodes = lexical_cast<int>(cut(line,161,4)); if (incomplete && traversedNodes == 1) return; // split the rest of the data -- the number of lines can be // variable; put all tokens into a single vector and discard the // unreached node if incomplete vector<string> allVals,tokens; for (auto line : lines) { trim(line); split(tokens,line,is_any_of("\t "),token_compress_on); // discard the empty string at the beginning allVals.insert(allVals.end(),tokens.begin(),tokens.end()); } // decrement traversedNodes by 1 and discard unreached node ID if // incomplete if (incomplete) { --traversedNodes; allVals.erase(allVals.begin() + traversedNodes); } // sanity check if (allVals.size() % traversedNodes != 0) { cerr << "Inconsistet block size " << allVals.size() << " traversedNodes = " << traversedNodes << " for vehicle " << ID << endl; } // assign the trajectory, nodeArrivalTimes, delay and tolls for (int i = 0; i < traversedNodes; ++i) { trajectory.push_back(lexical_cast<int>(allVals[i])); double time = lexical_cast<double>(allVals[i + traversedNodes]); nodeArrivalTimes.push_back(startTime + time); double delay = lexical_cast<double>(allVals[i + 3*traversedNodes]); double prevdelay; if (signalDelays.empty()) { signalDelays.push_back(delay); } else { signalDelays.push_back(delay - prevdelay); prevdelay = delay; } } // parse toll if exists if (allVals.size()/traversedNodes == 5) { for (int i = 0; i < traversedNodes; ++i) { double toll = lexical_cast<double>(allVals[i + 4*traversedNodes]); tolls.push_back(toll); } } } volMap mapToLinks(linkMap& lnkLen,double aggint,int speedBin) { VolumeBin bin; bin.vehType = vehType; volMap volumes; double frac = originLinkFrac; int Anode = upstreamNode; int Bnode; double start = startTime - 0.00001; // startTime is > 0 int startHourID = 1 + int(start/aggint); // cerr << "Mapping vehicle " << ID << endl; for (int i = 0; i < trajectory.size(); ++i) { Bnode = trajectory[i]; bin.fromNodeID = Anode; bin.toNodeID = Bnode; double end = nodeArrivalTimes[i] - 0.00001; double duration = end - start; // skip 0 duration traversals if (duration == 0) { Anode = Bnode; frac = 1.; continue; } int maxBin = 80/speedBin; bin.speed = ceil(60*frac*lnkLen[make_pair(Anode,Bnode)]/(speedBin*duration)); // because time resolution is limited, the speed can be very // wrong for short links, map to max speed bin if (bin.speed > maxBin) bin.speed = maxBin; int endHourID = 1 + int(end/aggint); // parse the volume into the intervalIDs that span it double lower = start; // cerr << Anode << " -> " << Bnode << " " // << start << " " << end << endl; for (int intervalID = startHourID; intervalID <= endHourID; ++intervalID) { double upper = min(end,intervalID*aggint); double volumeFraction = (upper - lower)/duration; lower = upper; bin.intervalID = intervalID; // cerr << bin.intervalID << " " // << bin.fromNodeID << " " // << bin.toNodeID << " " // << bin.speed << " " // << bin.vehType << " " // << frac*volumeFraction << endl; volumes[bin] += volumeFraction*frac; } // prepare for the next iteration start = end; Anode = Bnode; frac = 1.; startHourID = endHourID; } return volumes; } int numberOfLinks() { return trajectory.size(); } void output() { cerr << ID << " " << trajectory.size() << " " << upstreamNode << ":" << startTime; for (int i = 0; i < trajectory.size(); ++i) { cerr << " " << trajectory[i] << ":" << nodeArrivalTimes[i]; } cerr << endl; } linkDataMap mapVMT(linkMap& lnkLen) { linkDataMap vmt; double frac = originLinkFrac; int Anode = upstreamNode; LinkBin lb; lb.vehType = vehType; for (auto& Bnode : trajectory) { lb.fromNodeID = Anode; lb.toNodeID = Bnode; vmt[lb] += lnkLen[make_pair(Anode,Bnode)]*frac; frac = 1.; Anode = Bnode; } return vmt; } linkDataMap mapSignalDelay() { linkDataMap sigDelay; int Anode = upstreamNode; LinkBin lb; lb.vehType = vehType; for (int i = 0; i < trajectory.size(); ++i) { int Bnode = trajectory[i]; if (signalDelays[i] > 0.) { lb.fromNodeID = Anode; lb.toNodeID = Bnode; sigDelay[lb] = signalDelays[i]; } Anode = Bnode; } return sigDelay; } linkDataMap mapTolls() { linkDataMap toll; if (tolls.size() == trajectory.size()) { int Anode = upstreamNode; LinkBin lb; lb.vehType = vehType; for (int i = 0; i < trajectory.size(); ++i) { int Bnode = trajectory[i]; if (tolls[i] > 0.) { lb.fromNodeID = Anode; lb.toNodeID = Bnode; toll[lb] = tolls[i]; } Anode = Bnode; } } return toll; } linkDataMap mapDelay(linkMap& lnkFFT) { linkDataMap delay; double start = startTime; double frac = originLinkFrac; int Anode = upstreamNode; LinkBin lb; lb.vehType = vehType; for (int i = 0; i < trajectory.size(); ++i) { int Bnode = trajectory[i]; double end = nodeArrivalTimes[i]; double linkDelay = end - start - frac*lnkFFT[make_pair(Anode,Bnode)]; if (linkDelay > 0.) { lb.fromNodeID = Anode; lb.toNodeID = Bnode; delay[lb] = linkDelay; } start = end; Anode = Bnode; frac = 1.; } return delay; } }; class Scenario { map<int,Vehicle*> vehicles; // map from ID to Vehicle pointers volMap volumes; linkDataMap vmt,delay,signalDelay,toll; linkMap lnkLen,lnkFFT; set<int> electrifiedIDs; public: void readElecIDs() { ifstream elecIDfile; elecIDfile.open("elecIDs.txt"); int ID; while (elecIDfile >> ID) electrifiedIDs.insert(ID); elecIDfile.close(); } void removeElecVeh() { for (auto ID : electrifiedIDs) vehicles.erase(ID); } void parseVehicle() { // set up the bzip2 decompressor and parse vehicle.dat filtering_istream in; in.push(bzip2_decompressor()); ifstream vehFile("output_vehicle.dat.bz2",ios_base::binary); in.push(vehFile); // read lines and parse the vehicles int lineNumber = 0; string line; while (getline(in,line)) { // skip the first two lines and odd lines if (lineNumber < 2 || lineNumber % 2 == 1) { ++lineNumber; continue; } // make new vehicle and assign ID and originLinkFrac Vehicle* vehicle = new Vehicle(); vehicle->parseVehicleHeader(line); vehicles[vehicle->ID] = vehicle; ++lineNumber; } // close the ifstream vehFile.close(); } void parseVehTraj() { // set up the bzip2 decompressor and parse VehTrajectory.dat filtering_istream in; in.push(bzip2_decompressor()); ifstream trajFile("VehTrajectory.dat.bz2",ios_base::binary); in.push(trajFile); // read lines and parse the blocks list<string> lines; bool skipVehicle = false; bool incomplete = false; bool reachedIncomplete = false; string line; int lineNumber = 0; int vehID = 0; while (getline(in,line)) { // skip the first 5 lines if (lineNumber < 6) { ++lineNumber; continue; } // start of a new vehicle block if (line.compare(0,3,"Veh") == 0) { // parse the previous block if it has non-zero size and // skipVehicle is false if (vehID > 0 && !skipVehicle) { auto vehicle = vehicles[vehID]; vehicle->parseTrajBlock(lines,incomplete); } // set the incomplete flag if reached the "in the network" // section if (reachedIncomplete) { incomplete = true; reachedIncomplete = false; } // empty the block lines.clear(); // add the line to the block lines.push_back(line); // parse out the vehicleID and set skipVehicle based on // whether or not the ID is in the vehicles map vehID = lexical_cast<int>(cut(line,5,9)); if (vehicles.find(vehID) == vehicles.end()) { skipVehicle = true; } else { skipVehicle = false; } } else if (line.compare(1,3,"###") == 0) { reachedIncomplete = true; // don't add the line to the block } else { // add the line to the block lines.push_back(line); } } // parse the last block if (!skipVehicle) { auto vehicle = vehicles[vehID]; vehicle->parseTrajBlock(lines,incomplete); } trajFile.close(); } void readLinkInfo() { CSVReader<5, trim_chars<' '> > in("links.csv"); in.read_header(ignore_extra_column, "linkID","roadTypeID","countyID","length","speedLimit"); int roadType; int fips; double length,speed; string linkID; vector<string> tokens; while (in.read_row(linkID,roadType,fips,length,speed)) { split(tokens,linkID,is_any_of("-"),token_compress_on); int aNode = lexical_cast<int>(tokens[0]); int bNode = lexical_cast<int>(tokens[1]); lnkLen[make_pair(aNode,bNode)] = length; // miles lnkFFT[make_pair(aNode,bNode)] = length/speed*60; // min } } void computeVolumes(double aggint,int speedBin) { for (auto& [ID,vehicle] : vehicles) { // cerr << endl << ID << ":\n"; auto mappedVolumes = vehicle->mapToLinks(lnkLen,aggint,speedBin); for (auto [key,volume] : mappedVolumes) { // cerr << key.intervalID << " " << key.speed << " " << volume << endl; volumes[key] += volume; } } } void computeLinkData() { for (auto& [ID,vehicle] : vehicles) { auto vehvmt = vehicle->mapVMT(lnkLen); for (auto [key,val] : vehvmt) vmt[key] += val; auto vehdelay = vehicle->mapDelay(lnkFFT); for (auto [key,val] : vehdelay) delay[key] += val; auto vehsigdelay = vehicle->mapSignalDelay(); for (auto [key,val] : vehsigdelay) signalDelay[key] += val; auto vehtoll = vehicle->mapTolls(); for (auto [key,val] : vehtoll) toll[key] += val; } } void outputLinkData() { ofstream fh("linkData.csv"); fh << "linkID,vehType,metric,unit,value\n"; // vmt for (auto [lb,val] : vmt) { fh << lb.fromNodeID << "-" << lb.toNodeID << "," << lb.vehType << ",vmt,mile," << val << endl; } // delay for (auto [lb,val] : delay) { fh << lb.fromNodeID << "-" << lb.toNodeID << "," << lb.vehType << ",delay,min," << val << endl; } // signalDelay for (auto [lb,val] : signalDelay) { fh << lb.fromNodeID << "-" << lb.toNodeID << "," << lb.vehType << ",signalDelay,min," << val << endl; } for (auto [lb,val] : toll) { fh << lb.fromNodeID << "-" << lb.toNodeID << "," << lb.vehType << ",toll,dollar," << val << endl; } fh.close(); } void outputVolumes() { ofstream fh("linkVMT.csv"); // write the header fh << "linkID,vehType,timeIntervalID,avgSpeedBinID,vmt\n"; for (auto [bin,volume] : volumes) { fh << bin.fromNodeID << "-" << bin.toNodeID << "," << bin.vehType << "," << bin.intervalID << "," << bin.speed << "," << volume*lnkLen[make_pair(bin.fromNodeID,bin.toNodeID)] << endl; } fh.close(); } void outputNumberOfTrips() { map<int,int> numberOfTrips; for (auto& [ID,vehicle] : vehicles) { ++numberOfTrips[vehicle->vehType]; } ofstream fh; fh.open("numberOfTrips.csv"); fh << "vehType,numTrips\n"; for (auto [vehType,num] : numberOfTrips) { fh << vehType << "," << num << endl; } fh.close(); } }; int main(int argc,char **argv) { if (argc != 3) { cerr << "Usage: " << argv[0] << " aggInt speedBin\n"; return 1; } double aggInt = lexical_cast<double>(argv[1]); int speedBin = lexical_cast<int>(argv[2]); Scenario scenario; cerr << "Reading link attributes\n"; scenario.readLinkInfo(); cerr << "Parsing output_vehicle.dat\n"; scenario.parseVehicle(); cerr << "Parsing VehTrajectory.dat\n"; scenario.parseVehTraj(); // if elecIDs.txt is present, remove vehIDs listed in it if (boost::filesystem::exists(boost::filesystem::path("elecIDs.txt"))) { cerr << "Removing electrified vehicles\n"; scenario.readElecIDs(); scenario.removeElecVeh(); } cerr << "Computing link volumes\n"; scenario.computeVolumes(aggInt,speedBin); cerr << "Writing volumes\n"; scenario.outputVolumes(); cerr << "Writing number of trips\n"; scenario.outputNumberOfTrips(); cerr << "Computing link attributes\n"; scenario.computeLinkData(); cerr << "Writing link attributes\n"; scenario.outputLinkData(); }
29.371429
83
0.623087
[ "vector" ]
adc68e12103a6001bb10a5cc5ab51b275d947859
13,338
cpp
C++
src/dlvdb_src/input/DBInputBuilder.cpp
veltri/DLV2
944aaef803aa75e7ec51d7e0c2b0d964687fdd0e
[ "Apache-2.0" ]
null
null
null
src/dlvdb_src/input/DBInputBuilder.cpp
veltri/DLV2
944aaef803aa75e7ec51d7e0c2b0d964687fdd0e
[ "Apache-2.0" ]
null
null
null
src/dlvdb_src/input/DBInputBuilder.cpp
veltri/DLV2
944aaef803aa75e7ec51d7e0c2b0d964687fdd0e
[ "Apache-2.0" ]
null
null
null
/* * * Copyright 2014 Mario Alviano, Carmine Dodaro, Francesco Ricca and * Pierfrancesco Veltri. * * 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 "DBInputBuilder.h" #include "../../util/Utils.h" using namespace std; using namespace DLV2::DB; DBInputBuilder::DBInputBuilder( DBConnection& con ): currentAtom(NULL), isChoice(false), currentLiteral(NULL), query(NULL), nTermsForWeight(0), nTermsForLevel(0), nTermsAfterLevel(0), lowerGuard(NULL), upperGuard(NULL), hasNegation(false), hasAggregates(false), hasBuiltins(false), hasDisjunction(false) { program = new DBProgram(con); } DBInputBuilder::~DBInputBuilder() { } void DBInputBuilder::onRule() { program->createAndAddRule( head, body, hasNegation, hasAggregates, hasBuiltins, hasDisjunction); head.clear(); body.clear(); hasNegation = false; hasAggregates = false; hasBuiltins = false; hasDisjunction = false; } void DBInputBuilder::onConstraint() { assert_msg( 0, "At the moment, constraints are not supported" ); // TODO // How to handle constraints? body.clear(); } void DBInputBuilder::onWeakConstraint() { assert_msg( 0, "At the moment, weak constraints are not supported" ); // TODO // How to handle weak constraints? // At the moment we are simply deleting the terms which are // involved in the current weak constraint. assert_msg( nTermsForWeight + nTermsForLevel + nTermsAfterLevel <= termStack.size(), "The terms' stack has not a sufficient number of terms " "for building weight, level and terms of the current " "weak constraint."); // On top of the terms' stack there should be the list of terms // in the reverse order. if( nTermsAfterLevel > 0 ) { unsigned stackSize = termStack.size(); for( unsigned i=0; i<nTermsAfterLevel; i++ ) { delete termStack[stackSize-nTermsAfterLevel+i]; } termStack.erase(termStack.begin()+(stackSize-nTermsAfterLevel),termStack.end()); } // Then, we should have the level. if( nTermsForLevel ) { delete termStack.back(); termStack.pop_back(); } // Finally, the weight. if( nTermsForWeight ) { delete termStack.back(); termStack.pop_back(); } body.clear(); } void DBInputBuilder::onQuery() { assert_msg( currentAtom, "Trying to adding a null query atom" ); if( query != NULL ) { cout << "Query " << (*currentAtom) << " replaces " << query << endl; delete query; } query = currentAtom; } void DBInputBuilder::onHeadAtom() { assert_msg( currentAtom, "Trying to adding a null atom" ); head.push_back(currentAtom); } void DBInputBuilder::onHead() { if( head.size() > 1 ) hasDisjunction = true; } void DBInputBuilder::onBodyLiteral() { assert_msg( currentLiteral, "Trying to adding a null literal" ); body.push_back(currentLiteral); } void DBInputBuilder::onBody() { } void DBInputBuilder::onNafLiteral( bool naf ) { assert_msg( currentAtom, "Trying to finalize a literal without any atom" ); currentLiteral = program->createLiteral(currentAtom,naf); if( naf ) hasNegation = true; } void DBInputBuilder::onAtom( bool isStrongNeg ) { assert_msg( predName.length() > 0, "Trying to finalize an atom with a null predicate name" ); if( isStrongNeg ) currentAtom = program->createNegatedAtom(predName, termStack); else currentAtom = program->createAtom(predName, termStack); termStack.clear(); predName = ""; } void DBInputBuilder::onExistentialAtom() { assert_msg( 0, "At the moment, existential atoms are not supported" ); // TODO // REMINDER... add this statement to function createExistentialAtom // that you're going to add to the DBProgram interface: // pair< index_t, bool > res = program->addPredicate(predName,termStack.size()); } void DBInputBuilder::onPredicateName( char* name ) { assert_msg( name, "Trying to create an atom with a null predicate name" ); predName.assign(name); } void DBInputBuilder::onExistentialVariable( char* var ) { // TODO } void DBInputBuilder::onEqualOperator() { binop.assign("="); } void DBInputBuilder::onUnequalOperator() { binop.assign("<>"); } void DBInputBuilder::onLessOperator() { binop.assign("<"); } void DBInputBuilder::onLessOrEqualOperator() { binop.assign("<="); } void DBInputBuilder::onGreaterOperator() { binop.assign(">"); } void DBInputBuilder::onGreaterOrEqualOperator() { binop.assign(">="); } void DBInputBuilder::onTerm( char* value ) { newTerm(value,termStack); } void DBInputBuilder::onTerm( int value ) { DBTerm* currentTerm = NULL; currentTerm = program->createIntegerConstant(value); // Push currentTerm into the stack. if( currentTerm != NULL ) { termStack.push_back(currentTerm); } } void DBInputBuilder::onUnknownVariable() { DBTerm* currentTerm = NULL; currentTerm = program->createVariable(string("_")); // Push currentTerm into the stack. if( currentTerm != NULL ) { termStack.push_back(currentTerm); } } void DBInputBuilder::onFunction( char* functionSymbol, int nTerms ) { assert_msg( 0, "At the moment, functions are not supported" ); // TODO // How to handle functions? // Consume nTerms from the stack. unsigned newSize = termStack.size()-nTerms; termStack.erase(termStack.begin()+newSize,termStack.end()); } void DBInputBuilder::onTermDash() { assert_msg( 0, "At the moment, dashed terms are not supported" ); // TODO // How to handle dashed terms? // Consume one term from the stack. termStack.pop_back(); } void DBInputBuilder::onTermParams() { assert_msg( 0, "At the moment, parenthesized terms are not supported" ); // TODO // How to handle parametric terms? // Consume one term from the stack. termStack.pop_back(); } void DBInputBuilder::onTermRange( char* lowerBound, char* upperBound ) { assert_msg( 0, "At the moment, range facts are not supported" ); // TODO // How to handle a terms range? } void DBInputBuilder::onArithmeticOperation( char arithOperator ) { assert_msg( 0, "At the moment, arithmetic operations are not supported" ); // TODO // How to handle arithmetic operations? // The right and left operands are on top of the stack. termStack.pop_back(); termStack.pop_back(); } void DBInputBuilder::onWeightAtLevels( int nWeight, int nLevel, int nTerm ) { nTermsForWeight = nWeight; nTermsForLevel = nLevel; nTermsAfterLevel = nTerm; } void DBInputBuilder::onChoiceLowerGuard() { // TODO } void DBInputBuilder::onChoiceUpperGuard() { // TODO } void DBInputBuilder::onChoiceElementAtom() { // TODO // REMINDER... add this statement to function createExistentialAtom // that you're going to add to the DBProgram interface: // pair< index_t, bool > res = program->addPredicate(predName,termStack.size()); } void DBInputBuilder::onChoiceElementLiteral() { // TODO } void DBInputBuilder::onChoiceElement() { // TODO } void DBInputBuilder::onChoiceAtom() { // TODO assert_msg( 0, "At the moment, choice atoms are not supported" ); } void DBInputBuilder::onBuiltinAtom() { // FIXME : a builtin is likely to be composed of more than two terms. // The operands should be on top of the terms' stack. assert_msg( termStack.size() > 1, "Trying to create an invalid builtin atom" ); DBTerm* rightOperand = termStack.back(); termStack.pop_back(); DBTerm* leftOperand = termStack.back(); termStack.pop_back(); currentAtom = program->createBuiltinAtom(leftOperand,binop,rightOperand); termStack.clear(); predName = ""; hasBuiltins = true; } void DBInputBuilder::onAggregateLowerGuard() { // It should be on top of the stack. assert_msg( termStack.size() > 0, "Trying to create a null aggregate lower guard" ); lowerGuard = termStack.back(); termStack.pop_back(); lowerBinop.assign(binop); } void DBInputBuilder::onAggregateUpperGuard() { // It should be on top of the stack. assert_msg( termStack.size() > 0, "Trying to create a null choice-right term" ); upperGuard = termStack.back(); termStack.pop_back(); upperBinop.assign(binop); } void DBInputBuilder::onAggregateFunction( char* functionSymbol ) { assert_msg( functionSymbol, "Trying to create an aggregate with a null function" ); aggregateFunction.assign(functionSymbol); aggregateLabel << aggregateFunction << "{"; } void DBInputBuilder::onAggregateGroundTerm( char* value, bool dash ) { newTerm(value,aggregateElementTerms,dash); } void DBInputBuilder::onAggregateVariableTerm( char* value ) { newTerm(value,aggregateElementTerms); } void DBInputBuilder::onAggregateUnknownVariable() { aggregateElementTerms.push_back(program->createVariable(string("_"))); } void DBInputBuilder::onAggregateNafLiteral() { // The current literal should be pointed // by currentLiteral; assert_msg( currentLiteral, "Trying to adding a null literal" ); aggregateElementLiterals.push_back(currentLiteral); } void DBInputBuilder::onAggregateElement() { assert_msg( (aggregateElementTerms.size() > 0 && aggregateElementLiterals.size() > 0), "Invalid aggregate element."); DBAggregateElement* element = program->createAggregateElement(aggregateElementTerms,aggregateElementLiterals); aggregateElements.push_back(element); // Create the aggregate set string that will be used // during the creation of the dependency graph. if( aggregateLabel.str().at(aggregateLabel.str().length()-1) != '{' ) aggregateLabel << ";"; for( unsigned i=0; i<aggregateElementTerms.size(); i++ ) { assert_msg( aggregateElementTerms[i] != NULL, "Null term in an aggregate set." ); aggregateLabel << *aggregateElementTerms[i]; if( i < aggregateElementTerms.size()-1 ) aggregateLabel << ","; } aggregateLabel << ":"; for( unsigned i=0; i<aggregateElementLiterals.size(); i++ ) { assert_msg( aggregateElementLiterals[i] != NULL, "Null literal in an aggregate set." ); aggregateLabel << *aggregateElementLiterals[i]; if( i < aggregateElementLiterals.size()-1 ) aggregateLabel << ","; } aggregateElementTerms.clear(); aggregateElementLiterals.clear(); } void DBInputBuilder::onAggregate( bool naf ) { assert_msg( aggregateFunction.length() > 0, "Trying to finalize an aggregate with a null function symbol" ); assert_msg( aggregateElements.size() > 0, "Trying to finalize an aggregate without elements" ); assert_msg( lowerGuard || upperGuard, "Trying to finalize an aggregate without any guards" ); // Create the name that is going to be added to the depgraph for this aggregate atom. aggregateLabel << "}"; currentAtom = program->createAggregateAtom( lowerGuard, lowerBinop, upperGuard, upperBinop, aggregateFunction, aggregateElements, aggregateLabel.str()); currentLiteral = program->createLiteral(currentAtom,naf); aggregateLabel.clear(); aggregateElements.clear(); lowerBinop = ""; lowerGuard = NULL; upperBinop = ""; upperGuard = NULL; aggregateFunction = ""; hasAggregates = true; if( naf ) hasNegation = true; } void DBInputBuilder::newTerm( char* value, vector< DBTerm* >& target, bool dash ) { DBTerm* currentTerm = NULL; if( value[0] >= 'A' && value[0] <='Z' ) // Variable { currentTerm = program->createVariable(value); } else if( Utils::isNumeric(value,10) ) // Numeric constant { int val = atoi(value); if( dash ) val = 0 - val; currentTerm = program->createIntegerConstant(val); } else // String { currentTerm = program->createStringConstant(value); } // Push currentTerm into the stack. if( currentTerm != NULL ) { target.push_back(currentTerm); } }
23.482394
95
0.64305
[ "vector" ]
adca043ef54015529c6071827fc730e629f5b62f
2,805
hpp
C++
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/Log/Log.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/Log/Log.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/Log/Log.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2014 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_CORE_LOG #define SSVU_CORE_LOG namespace ssvu { namespace FileSystem { class Path; } namespace Internal { using CoutType = decltype(std::cout); using StdEndLine = CoutType&(CoutType&); /// @brief Returns a reference to the static `std::ostringstream` log stream. inline auto& getLogStream() noexcept { static std::ostringstream logStream; return logStream; } /// @brief Returns a reference to the static suppressed `bool` value. inline auto& getLogSuppressed() noexcept { static bool logSuppressed{false}; return logSuppressed; } /// @brief Log object that does nothing but can be used in place of `LOut`. struct NullLOut { inline void flush() const { } }; template<typename T> inline NullLOut& operator<<(NullLOut& mLOut, const T&) { return mLOut; } inline NullLOut& operator<<(NullLOut& mLOut, StdEndLine) { return mLOut; } } } #ifndef SSVU_LOG_DISABLE #include "SSVUtils/Core/Log/Internal/LogImplEnabled.hpp" #else #include "SSVUtils/Core/Log/Internal/LogImplDisabled.hpp" #endif namespace ssvu { /// @brief Returns a reference to the log stream. inline auto& getLogStream() noexcept { return Internal::getLogStream(); } /// @brief Returns a reference to the "log stream" singleton. (no title) inline auto& lo() noexcept { return Internal::lo(); } /// @brief Returns a reference to the "log stream" singleton. (sets title) /// @param mTitle Title of the next log message. template<typename T> inline auto& lo(const T& mTitle) { return Internal::lo(mTitle); } /// @brief Returns a const char* horizontal ruler C string. Intended to be used when printing to the console. inline const char* hr() noexcept { return Internal::hr(); } /// @brief Returns a std::string customized horizontal ruler. Intended to be used when printing to the console. /// @param mOffset Length offset of the ruler. /// @param mChar Character used to create the ruler. inline std::string hr(int mOffset, char mChar = '_') { return Internal::hr(mOffset, mChar); } /// @brief Starts or stops suppressing the log functionality. /// @details While the log is being suppressed, no output will be given to either `std::cout` or to the file log stream. inline void setLogSuppressed(bool mLogSuppressed) noexcept { Internal::getLogSuppressed() = mLogSuppressed; } /// @brief Returns a `LOut`-like log object that uses the same syntax but does nothing. inline auto loNull() noexcept { return Internal::NullLOut{}; } /// @brief Returns a `LOut`-like log object that uses the same syntax but does nothing. template<typename T> inline auto loNull(const T&) noexcept { return Internal::NullLOut{}; } } #endif
38.958333
121
0.727273
[ "object" ]
adca7ab3f072c7152ad617f1711be5450cfafcf8
50,498
cpp
C++
WiFi_MiMo_Test/WiFi_MiMo_Test_Internal.cpp
zfh1005/IQ_DualHead
350fa1774ca21fa64587a444261d9c54ef53d262
[ "MIT" ]
11
2017-06-07T09:07:23.000Z
2021-02-04T09:07:30.000Z
WiFi_MiMo_Test/WiFi_MiMo_Test_Internal.cpp
zfh1005/IQ_DualHead
350fa1774ca21fa64587a444261d9c54ef53d262
[ "MIT" ]
2
2017-10-09T08:51:52.000Z
2021-12-17T03:38:54.000Z
WiFi_MiMo_Test/WiFi_MiMo_Test_Internal.cpp
zfh1005/IQ_DualHead
350fa1774ca21fa64587a444261d9c54ef53d262
[ "MIT" ]
19
2015-02-07T10:30:35.000Z
2022-02-25T11:50:41.000Z
#include "stdafx.h" #include "WiFi_MiMo_Test.h" #include "IQlite_Logger.h" #include "IQmeasure.h" #include "math.h" //Move to stdafx.h //#include "lp_time.h" using namespace std; // global variable TM_ID g_WiFi_Test_ID = -1; vDUT_ID g_WiFi_Dut = -1; bool g_ReloadDutDll = false; bool g_vDutTxActived = false; bool g_vDutRxActived = false; bool g_dutConfigChanged = false; bool g_txCalibrationEnabled = false; int g_Logger_ID = -1; int g_WiFi_Test_timer = -1; int g_WiFi_Test_logger = -1; int g_Tester_Type = IQ_View; int g_Tester_Number = 0; int g_Tester_Reconnect = 0; double g_last_TxPower_dBm_Record = 0; // Record the Tx power used in last test item. const char *g_WiFi_Test_Version = "1.5.1 (2010-05-24)\n"; char g_defaultFilePath[MAX_BUFFER_SIZE] = {'\0'}; WIFI_RECORD_PARAM g_RecordedParam; // This global variable is declared in WiFi_Global_Setting.cpp // Input Parameter Container extern map<string, WIFI_SETTING_STRUCT> g_globalSettingParamMap; extern WIFI_GLOBAL_SETTING g_globalSettingParam; extern int g_iTesterName; // end global using namespace std; //! WiFi Test Internal Functions /*! * Input Parameters * * - None * * Return Values * -# A string for possible error message * * \return 0 No error occurred * \return -1 DUT failed to insert. Please see the returned error message for details */ int InitializeAllMIMOContainers(void) { InitializeConnectTesterContainers(); // Needed by WiFi_Connect_IQTester InitializeDisconnectTesterContainers(); // Needed by WiFi_Disconnect_IQTester InitializeInsertDutContainers(); // Needed by WiFi_Insert_Dut InitializeInitializeDutContainers(); // Needed by WiFi_Initialize_Dut InitializeRemoveDutContainers(); // Needed by WiFi_Remove_Dut InitializeGlobalSettingContainers(); // Needed by WiFi_Global_Setting InitializeTXVerifyEvmContainers(); // Needed by WiFi_TX_Verify_Evm InitializeRXVerifyPerContainers(); // Needed by WiFi_RX_Verify_Per InitializeTXVerifyMaskContainers(); // Needed by WiFi_TX_Verify_Mask InitializeTXVerifyPowerContainers(); // Needed by WiFi_TX_Verify_Power InitializeTXVerifyFlatnessContainers(); // Needed by WiFi_TX_Verify_Flatness InitializeReadEepromContainers(); // Needed by WiFi_Read_Eeprom InitializeWriteEepromContainers(); // Needed by WiFi_Write_Eeprom InitializeWriteBBRegisterContainers(); // Needed by WiFi_Write_BB_Register.cpp InitializeReadBBRegisterContainers(); // Needed by WiFi_Read_BB_Register.cpp InitializeWriteRFRegisterContainers(); // Needed by WiFi_Write_RF_Register.cpp InitializeReadRFRegisterContainers(); // Needed by WiFi_Read_RF_Register.cpp InitializeWriteMacRegisterContainers(); // Needed by WiFi_Write_Mac_Register.cpp InitializeReadMacRegisterContainers(); // Needed by WiFi_Read_Mac_Register.cpp InitializeWriteSocRegisterContainers(); // Needed by WiFi_Write_Soc_Register.cpp InitializeReadSocRegisterContainers(); // Needed by WiFi_Read_Soc_Register.cpp InitializeRunExternalProgramContainers(); // Needed by WiFi_Run_External_Program InitializeGetSerialNumberContainers(); // Needed by WiFi_Get_Serial_Number InitializeWriteMacAddressContainers(); // Needed by WiFi_Write_Mac_Address InitializeReadMacAddressContainers(); // Needed by WiFi_Read_Mac_Address InitializeTXCalContainers(); // Needed by WiFi_TX_Calibration InitializePowerModeDutContainers(); // Needed by WiFi Current test InitializeRunDutCommandContainers(); // Needed by WiFi_Run_Dut_Command InitializeloadPathLossTableContainers(); InitializeInternalParameters(); return 0; } void CleanupAllMIMOContainers(void) { // IQlite merge; Tracy Yu ; 2012-03-31 CleanupTXConnectIQTester(); // Needed by WiFi_Connect_IQTester CleanupTXDisconnectIQTester(); // Needed by WiFi_Disconnect_IQTester CleanupGetSerialNumber(); // Needed by WiFi_Get_Serial_Number CleanupGlobalSetting(); // Needed by WiFi_Global_Setting CleanupInitializeDut(); // Neede by WiFi_Initialize_Dut CleanupInsertDut(); // Needed by WiFi_Insert_Dut CleanupLoadPathLossTable(); // Needed by WiFi_Load_Path_Loss_Table CleanupPowerModeDut(); // Needed by WiFi_Power_Mode_Dut CleanupReadBBRegister(); // Needed by WiFi_Read_BB_Register CleanupReadEeprom(); // Needed by WiFi_Read_Eeprom CleanupReadMacAddress(); // Needed by WiFi_Read_Mac_Address CleanupReadMacRegister(); // Needed by WiFi_Read_Mac_Register CleanupReadRfRegister(); // Needed by WiFi_Read_RF_Register CleanupReadSocRegister(); // Needed by WiFi_Read_Soc_Register CleanupRemoveDut(); // Needed by WiFi_Remove_Dut CleanupRunExternalProgram(); // Needed by WiFi_Run_External_Program CleanupRXVerifyPer(); // Needed by WiFi_RX_Verify_Per CleanupTXCalibration(); // Needed by WiFi_TX_Calibration CleanupTXVerifyEvm(); // Needed by WiFi_TX_Verify_Evm CleanupTXVerifyMaskContainers(); // Needed by WiFi_TX_Verify_Mask CleanupTXVerifyPower(); // Needed by WiFi_TX_Verify_Power CleanupTXVerifySpectrum(); // Needed by WiFi_TX_Verify_Spectrum CleanupWriteBBRegister(); // Needed by WiFi_Write_BB_Register CleanupWriteEeprom(); // Needed by WiFi_Write_Eeprom CleanupWriteMacAddress(); // Needed by WiFi_Write_Mac_Address CleanupWriteMacRegister(); // Needed by WiFi_Write_Mac_Register CleanupWriteRFRegister(); // Needed by WiFi_Write_RF_Register CleanupWriteSocRegister(); // Needed by WiFi_Write_Soc_Register return; } int InitializeInternalParameters(void) { // Initial the internal parameters g_RecordedParam.ANT1 = NA_INTEGER; g_RecordedParam.ANT2 = NA_INTEGER; g_RecordedParam.ANT3 = NA_INTEGER; g_RecordedParam.ANT4 = NA_INTEGER; g_RecordedParam.CABLE_LOSS_DB[0] = NA_DOUBLE; g_RecordedParam.CABLE_LOSS_DB[1] = NA_DOUBLE; g_RecordedParam.CABLE_LOSS_DB[2] = NA_DOUBLE; g_RecordedParam.CABLE_LOSS_DB[3] = NA_DOUBLE; g_RecordedParam.FREQ_MHZ = NA_INTEGER; g_RecordedParam.POWER_DBM = NA_DOUBLE; g_RecordedParam.FRAME_COUNT = NA_INTEGER; g_RecordedParam.BANDWIDTH[0] = '\0'; g_RecordedParam.DATA_RATE[0] = '\0'; g_RecordedParam.PREAMBLE[0] = '\0'; g_RecordedParam.PACKET_FORMAT_11N[0] = '\0'; g_RecordedParam.GUARD_INTERVAL_11N[0] = '\0'; // IQlite merge; Tracy Yu ; 2012-03-31 return 0; } int AverageTestResult(double *resultArray, int averageTimes, int logType, double &averageResult, double &maxResult, double &minResult) { int err = ERR_OK; // Averaging after all measurements are done, by an averaging function int i = 0; averageResult = 0.0; maxResult = minResult = resultArray[0]; if (0==averageTimes) { return -1; // Error, can not divided by zero } else { if (logType==Linear) { for (i=0;i<averageTimes;i++) { maxResult = max(maxResult, resultArray[i]); minResult = min(minResult, resultArray[i]); averageResult = averageResult + resultArray[i]; } averageResult = averageResult / averageTimes; } else if (logType == Linear_Sum) { logType = LOG_10; for (i=0;i<averageTimes;i++) { //TODO: avoid unenabled VSA or streams maxResult = max(maxResult, resultArray[i]); minResult = min(minResult, resultArray[i]); averageResult = averageResult + pow( 10,(resultArray[i]/logType) ); } if (0!=averageResult) { averageResult = logType*(log10(averageResult)); } else { averageResult = NA_DOUBLE; } } else if (logType == LOG_20_EVM) // for EVM average { logType = LOG_20; for (i=0;i<averageTimes;i++) { maxResult = max(maxResult, resultArray[i]); minResult = min(minResult, resultArray[i]); averageResult = averageResult + pow(pow( 10,(resultArray[i]/logType)), 2); } averageResult = sqrt(averageResult / averageTimes); if (0!=averageResult) { averageResult = logType*(log10(averageResult)); } else { averageResult = NA_DOUBLE; } } else // LOG_10 and LOG_20 { for (i=0;i<averageTimes;i++) { maxResult = max(maxResult, resultArray[i]); minResult = min(minResult, resultArray[i]); averageResult = averageResult + pow( 10,(resultArray[i]/logType) ); } averageResult = averageResult / averageTimes; if (0!=averageResult) { averageResult = logType*(log10(averageResult)); } else { averageResult = NA_DOUBLE; } } } return err; } WIFI_MIMO_TEST_API int RespondToQueryInput( std::map<std::string, WIFI_SETTING_STRUCT>& inputMap) { int err = ERR_OK; map<string, WIFI_SETTING_STRUCT>::iterator inputMap_Iter; int *integerValue = NULL; double *doubleValue = NULL; char *stringValue = NULL; char logMessage[MAX_BUFFER_SIZE] = {'\0'}; ::TM_ClearReturns(g_WiFi_Test_ID); inputMap_Iter = inputMap.begin(); while( inputMap_Iter!=inputMap.end() ) { if( NULL!=inputMap_Iter->second.unit ) { ::TM_AddUnitReturn(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), (TM_STR)inputMap_Iter->second.unit); } if( NULL!=inputMap_Iter->second.helpText ) { ::TM_AddHelpTextReturn(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), (TM_STR)inputMap_Iter->second.helpText); } switch( inputMap_Iter->second.type ) { case WIFI_SETTING_TYPE_INTEGER: integerValue = reinterpret_cast<int *>(inputMap_Iter->second.value); ::TM_AddIntegerReturn(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), *integerValue); break; case WIFI_SETTING_TYPE_DOUBLE: doubleValue = reinterpret_cast<double *>(inputMap_Iter->second.value); ::TM_AddDoubleReturn(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), *doubleValue); break; case WIFI_SETTING_TYPE_STRING: stringValue = reinterpret_cast<char *>(inputMap_Iter->second.value); ::TM_AddStringReturn(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), stringValue); break; default: // Unknown type. Ignore it. break; } inputMap_Iter++; } LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] RespondToQueryInput() return OK.\n"); return err; } int RespondToQueryReturn( map<string, WIFI_SETTING_STRUCT>& returnMap) { int err = ERR_OK; map<string, WIFI_SETTING_STRUCT>::iterator returnMap_Iter; char logMessage[MAX_BUFFER_SIZE] = {'\0'}; ::TM_ClearReturns(g_WiFi_Test_ID); returnMap_Iter = returnMap.begin(); while( returnMap_Iter!=returnMap.end() ) { if( NULL!=returnMap_Iter->second.unit ) { ::TM_AddUnitReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), (TM_STR)returnMap_Iter->second.unit); } if( NULL!=returnMap_Iter->second.helpText ) { ::TM_AddHelpTextReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), (TM_STR)returnMap_Iter->second.helpText); } switch( returnMap_Iter->second.type ) { case WIFI_SETTING_TYPE_INTEGER: ::TM_AddIntegerReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), 0); break; case WIFI_SETTING_TYPE_DOUBLE: ::TM_AddDoubleReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), 0.0); break; case WIFI_SETTING_TYPE_STRING: ::TM_AddStringReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), ""); break; case WIFI_SETTING_TYPE_ARRAY_DOUBLE: ::TM_AddArrayDoubleReturn(g_WiFi_Test_ID,(TM_STR)returnMap_Iter->first.c_str(),NULL, 0); break; default: // Unknown type. Ignore it. break; } returnMap_Iter++; } LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] RespondToQueryReturn() return OK.\n"); return err; } int ReturnTestResults( map<string, WIFI_SETTING_STRUCT>& returnMap) { int err = ERR_OK; bool putTMReturnResult = false; map<string, WIFI_SETTING_STRUCT>::iterator returnMap_Iter; ::TM_ClearReturns(g_WiFi_Test_ID); returnMap_Iter = returnMap.begin(); while( returnMap_Iter!=returnMap.end() ) { if( NULL!=returnMap_Iter->second.unit ) { ::TM_AddUnitReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), (TM_STR)returnMap_Iter->second.unit); } if( NULL!=returnMap_Iter->second.helpText ) { ::TM_AddHelpTextReturn(g_WiFi_Test_ID, (TM_STR)returnMap_Iter->first.c_str(), (TM_STR)returnMap_Iter->second.helpText); } if( returnMap_Iter->second.type==WIFI_SETTING_TYPE_INTEGER ) { int *valueInteger = reinterpret_cast<int *>(returnMap_Iter->second.value); if ( (*valueInteger)>(NA_NUMBER+1) ) { err = ::TM_AddIntegerReturn(g_WiFi_Test_ID, (char*)returnMap_Iter->first.c_str(), *valueInteger); if (TM_ERR_OK!=err) { // If TM_AddIntegerReturn fails, no need to continue break; } } else { // do nothing } } else if(returnMap_Iter->second.type==WIFI_SETTING_TYPE_DOUBLE) { double *valueDouble = reinterpret_cast<double *>(returnMap_Iter->second.value); if ((*valueDouble)>(NA_NUMBER+1) ) { err = ::TM_AddDoubleReturn(g_WiFi_Test_ID, (char*)returnMap_Iter->first.c_str(), *valueDouble); if (TM_ERR_OK!=err) { // If TM_AddDoubleReturn fails, no need to continue break; } } else { // do nothing } } else if(returnMap_Iter->second.type==WIFI_SETTING_TYPE_STRING) { char *valueString = reinterpret_cast<char *>(returnMap_Iter->second.value); err = ::TM_AddStringReturn(g_WiFi_Test_ID, (char*)returnMap_Iter->first.c_str(), valueString); if (TM_ERR_OK!=err) { // If TM_AddStringReturn fails, no need to continue break; } } else //returnMap_Iter->second.type==WIFI_SETTING_TYPE_ARRAY_DOUBLE { vector<double> doubleVector = * reinterpret_cast<vector<double> *>(returnMap_Iter->second.value); if (0 != doubleVector.size()) { double *doubleArray = new double[(int) doubleVector.size()]; //Default doubleArray won't put into TM result container. (for Sweep functiion) putTMReturnResult = false; for (unsigned int i=0; i<doubleVector.size(); i++) { doubleArray[i] = doubleVector[i]; if(doubleArray[i] >(NA_NUMBER+1)) { putTMReturnResult = true; } else { //not put double array into TM result container } } if (putTMReturnResult) { err = TM_AddArrayDoubleReturn(g_WiFi_Test_ID, (char*)returnMap_Iter->first.c_str(), doubleArray, (int)doubleVector.size()); } else { //not put double array into TM result container } delete [] doubleArray; doubleVector.clear(); // IQlite merge; Tracy Yu ; 2012-03-31 if (TM_ERR_OK!=err) { // If TM_AddDoubleReturn fails, no need to continue break; } } else { // do nothing } doubleVector.clear(); // IQlite merge; Tracy Yu ; 2012-03-31 } returnMap_Iter++; } return err; } int ClearReturnParameters( map<string, WIFI_SETTING_STRUCT>& returnMap) { int err = ERR_OK; map<string, WIFI_SETTING_STRUCT>::iterator returnMap_Iter; // clear container ::TM_ClearReturns(g_WiFi_Test_ID); returnMap_Iter = returnMap.begin(); while( returnMap_Iter!=returnMap.end() ) { if( returnMap_Iter->second.type==WIFI_SETTING_TYPE_INTEGER ) { int *valueInteger = reinterpret_cast<int *>(returnMap_Iter->second.value); *valueInteger = NA_INTEGER; } else if(returnMap_Iter->second.type==WIFI_SETTING_TYPE_DOUBLE) { double *valueDouble = reinterpret_cast<double *>(returnMap_Iter->second.value); *valueDouble = NA_DOUBLE; } else // returnMap_Iter->second.type==WIFI_SETTING_TYPE_STRING { char *valueString = reinterpret_cast<char *>(returnMap_Iter->second.value); *valueString = '\0'; } returnMap_Iter++; } return err; } int ReturnErrorMessage(char *errParameter, const char *format, ...) { int err = ERR_OK; // Log message format ... variable argument list va_list ap; va_start(ap, format); vsprintf_s(errParameter, MAX_BUFFER_SIZE, format, ap); err = ::TM_AddStringReturn(g_WiFi_Test_ID, "ERROR_MESSAGE", errParameter); // Ignore error handling // IQlite merge; Tracy Yu ; 2012-03-31 err = ::vDUT_Run( g_WiFi_Dut, "FUNCTION_FAILED" ); // Ignore error handling va_end(ap); return err; } int LogReturnMessage(char *errMsg, int sizeOfBuf, LOGGER_LEVEL level, const char *format, ...) { int err = ERR_OK; // Log message format ... variable argument list va_list ap; va_start(ap, format); vsprintf_s(errMsg, sizeOfBuf, format, ap); va_end(ap); // Write error message to log file if (g_Logger_ID>=0) { err = ::LOGGER_Write(g_Logger_ID, level, errMsg); // TODO: if possible, must do the error handling here } else { // do nothing err = -1; sprintf_s(errMsg, sizeOfBuf, "[WiFi] LogReturnMessage() return error, Logger_ID < 0.\n"); } return err; } int GetInputParameters( map<string, WIFI_SETTING_STRUCT>& inputMap) { int err = ERR_OK; char stringParameter[MAX_BUFFER_SIZE] = {'\0'}; map<string, WIFI_SETTING_STRUCT>::iterator inputMap_Iter; inputMap_Iter = inputMap.begin(); while( inputMap_Iter!=inputMap.end() ) { int strError = ERR_OK; switch( inputMap_Iter->second.type ) { case WIFI_SETTING_TYPE_INTEGER: err += ::TM_GetIntegerParameter(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), (int*)inputMap_Iter->second.value); break; case WIFI_SETTING_TYPE_DOUBLE: err += ::TM_GetDoubleParameter(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), (double*)inputMap_Iter->second.value); break; case WIFI_SETTING_TYPE_STRING: stringParameter[0] = 0; strError = ::TM_GetStringParameter(g_WiFi_Test_ID, (TM_STR)inputMap_Iter->first.c_str(), stringParameter, MAX_BUFFER_SIZE); err += strError; if( ERR_OK==strError ) { if (0!=stringParameter[0]) // got input string { strcpy_s((char*)inputMap_Iter->second.value, MAX_BUFFER_SIZE, stringParameter); } else // got "NULL" input string { strcpy_s((char*)inputMap_Iter->second.value, MAX_BUFFER_SIZE, ""); } } else { // do nothing. Sometime, the Global_Setting's input parameters will get into this case. } break; default: // Unknown type. Ignore it. break; } inputMap_Iter++; } return err; } int CheckDutStatus(void) { int err = ERR_OK; int ant01 = 0, ant02 = 0, ant03 = 0, ant04 = 0; char vErrorMsg[MAX_BUFFER_SIZE] = {'\0'}; char logMessage[MAX_BUFFER_SIZE] = {'\0'}; ::TM_GetIntegerParameter(g_WiFi_Test_ID, "TX1", &ant01); ::TM_GetIntegerParameter(g_WiFi_Test_ID, "TX2", &ant02); ::TM_GetIntegerParameter(g_WiFi_Test_ID, "TX3", &ant03); ::TM_GetIntegerParameter(g_WiFi_Test_ID, "TX4", &ant04); if ( (ant01+ant02+ant03+ant04)>0 ) // This is a Tx function { // do nothing } else // This is NOT a Tx function { if ( g_vDutTxActived ) // If Dut still under Tx mode { /*-----------* * Tx Stop * *-----------*/ err = ::vDUT_Run(g_WiFi_Dut, "TX_STOP"); if ( ERR_OK!=err ) { // Check vDut return "ERROR_MESSAGE" or not, if "Yes", must handle it. err = ::vDUT_GetStringReturn(g_WiFi_Dut, "ERROR_MESSAGE", vErrorMsg, MAX_BUFFER_SIZE); if ( ERR_OK==err ) // Get "ERROR_MESSAGE" from vDut { err = -1; // set err to -1, means "Error". LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, vErrorMsg); return err; } else // Just return normal error message in this case { LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi] vDUT_Run(TX_STOP) return error.\n"); return err; } } else { g_vDutTxActived = false; LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] vDUT_Run(TX_STOP) return OK.\n"); } } else { // do nothing } } return err; } int CheckTesterConsistentStatus( std::map<std::string, std::string> &versionMap) { int err = ERR_OK; vector<string> testersFW; vector<string> testersVsaFpga; vector<string> testersVsgFpga; char version[MAX_BUFFER_SIZE]={'\0'}; testersFW.clear(); testersVsaFpga.clear(); testersVsgFpga.clear(); map<string, string>::iterator versionMapIter; versionMapIter = versionMap.begin(); while (versionMapIter != versionMap.end()) { if(string::npos != versionMapIter->first.find("FW") ) { testersFW.push_back(versionMapIter->second.c_str()); } else { //do nothing } if(string::npos != versionMapIter->first.find("VSAFPGA") ) { testersVsaFpga.push_back(versionMapIter->second.c_str()); } else { //do nothing } if(string::npos != versionMapIter->first.find("VSGFPGA") ) { testersVsgFpga.push_back(versionMapIter->second.c_str()); } else { //do nothing } versionMapIter ++; } //Check Tester consistent // 1. FW // 2. FPGA (VSA/VSG) std::vector<std::string>::iterator versionIter; if(testersFW.size() >0) { versionIter = testersFW.begin(); sprintf_s(version,MAX_BUFFER_SIZE, "%s", versionIter->c_str()); versionIter ++; while(versionIter != testersFW.end()) { if(strcmp(version,versionIter->c_str()) !=0) { err = -1; break; } versionIter ++; } } else { /*--------------------------------------------- Version Map didn't contain any FW version info. ----------------------------------------------*/ //TODO: define error code err = -1; } if(testersVsaFpga.size() >0) { versionIter = testersVsaFpga.begin(); sprintf_s(version,MAX_BUFFER_SIZE, "%s", versionIter->c_str()); versionIter ++; while(versionIter != testersVsaFpga.end()) { if(strcmp(version,versionIter->c_str()) !=0) { err = -1; break; } versionIter ++; } } else { /*--------------------------------------------- Version Map didn't contain any VSA FPGA version info. ----------------------------------------------*/ //TODO: define error code err = -1; } if(testersVsgFpga.size() >0) { versionIter = testersVsgFpga.begin(); sprintf_s(version,MAX_BUFFER_SIZE, "%s", versionIter->c_str()); versionIter ++; while(versionIter != testersVsgFpga.end()) { if(strcmp(version,versionIter->c_str()) !=0) { err = -1; break; } versionIter ++; } } else { /*--------------------------------------------- Version Map didn't contain any VSG FPGA version info. ----------------------------------------------*/ //TODO: define error code err = -1; } testersFW.clear(); testersVsaFpga.clear(); testersVsgFpga.clear(); return err; } int WiFiTestMode(char* strDataRate, char* strBandwidth, int* wifiMode, int* wifiStreamNum) { int err = ERR_OK; int dataRateIndex, dataRatePBCC22, dataRateOFDM6, dataRateOFDM54, dataRateMCS7, dataRateMCS15, dataRateMCS23, dataRateHALF3, dataRateQUAR13_5; err = ::TM_WiFiConvertDataRateNameToIndex(strDataRate, &dataRateIndex); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("PBCC-22", &dataRatePBCC22); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("OFDM-6", &dataRateOFDM6); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("OFDM-54", &dataRateOFDM54); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("MCS7", &dataRateMCS7); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("MCS15", &dataRateMCS15); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("MCS23", &dataRateMCS23); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("HALF-3", &dataRateHALF3); // Convert data rate name to index if (ERR_OK!=err) { return err; } err = ::TM_WiFiConvertDataRateNameToIndex("QUAR-13_5", &dataRateQUAR13_5); // Convert data rate name to index if (ERR_OK!=err) { return err; } if ( dataRateIndex<=dataRatePBCC22 ) { // [Case 01]: 802.11b *wifiMode = WIFI_11B; *wifiStreamNum = WIFI_ONE_STREAM; } else if ( (dataRateIndex>=dataRateOFDM6)&&(dataRateIndex<=dataRateOFDM54) ) { // [Case 02]: 802.11a/g *wifiMode = WIFI_11AG; *wifiStreamNum = WIFI_ONE_STREAM; } else if ( (dataRateIndex>=dataRateHALF3)&&(dataRateIndex<=dataRateQUAR13_5) ) { // [Case 03]: 802.11p *wifiMode = WIFI_11AG; *wifiStreamNum = WIFI_ONE_STREAM; } else // [Case 03]: 802.11n { if ( 0==strcmp(strBandwidth, "HT20") ) *wifiMode = WIFI_11N_HT20; else *wifiMode = WIFI_11N_HT40; if (dataRateIndex<=dataRateMCS7) *wifiStreamNum = WIFI_ONE_STREAM; else if (dataRateIndex<=dataRateMCS15) *wifiStreamNum = WIFI_TWO_STREAM; else if (dataRateIndex<=dataRateMCS23) *wifiStreamNum = WIFI_THREE_STREAM; else *wifiStreamNum = WIFI_FOUR_STREAM; } return err; } int WiFiSaveSigFile(char* fileName) { int err = ERR_OK; char logMessage[MAX_BUFFER_SIZE] = {'\0'}; char logInfoMessage[MAX_BUFFER_SIZE] = {'\0'}; // IQlite merge; Tracy Yu ; 2012-03-31 if (1==g_globalSettingParam.VSA_SAVE_CAPTURE_ALWAYS) { LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_WARNING, "[WiFi] The VSA_SAVE_CAPTURE_ALWAYS is set to ON, it may slow down the test time.\n"); } if ( (1==g_globalSettingParam.VSA_SAVE_CAPTURE_ON_FAILED)||(1==g_globalSettingParam.VSA_SAVE_CAPTURE_ALWAYS)) { //Get system time //CTime loggerTime = CTime::GetCurrentTime(); //CString cStr = loggerTime.Format(_T("%Y.%B.%d-%H.%M.%S")); char c_time[MAX_BUFFER_SIZE], c_path[MAX_BUFFER_SIZE]; //size_t i; //int sizeOfString = cStr.GetLength() + 1; //LPTSTR pStrTmp = new TCHAR[sizeOfString]; //_tcscpy_s( pStrTmp, sizeOfString, cStr ); //wcstombs_s( &i, c_time, sizeOfString , pStrTmp, sizeOfString ); //delete pStrTmp; #ifdef WIN32 // Get system time SYSTEMTIME sysTime; ::GetLocalTime(&sysTime); sprintf_s(c_time, "%d.%d.%d-%d.%d.%d.%d", sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds); #else time_t rawtime; struct tm timeInfo; time(&rawtime); localtime_s(&timeInfo, &rawtime); // Note this does not have milliseconds, as the win32 version does. strftime(c_time, MAX_BUFFER_SIZE, "%y.%m.%d-%H.%M.%S", &timeInfo); #endif char cFileExt[10] = {'\0'}; if( g_iTesterName == IQTYPE_2010 ) sprintf_s(cFileExt, 10, "%s", "sig"); else if( g_iTesterName == IQTYPE_XEL ) sprintf_s(cFileExt, 10, "%s", "iqvsa"); sprintf_s(c_path, MAX_BUFFER_SIZE, "./log/%s-%s.%s", fileName, c_time, cFileExt); err = ::LP_SaveVsaSignalFile(c_path); sprintf_s(logInfoMessage, "[WiFi] WiFiSaveSigFile(\"%s\") return OK.\n", c_path); LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, logInfoMessage); } else { // do nothing... } return err; } int GetWaveformFileName(char* perfix, char* postfix, int wifiMode, char* bandwidth, char* datarate, char* preamble, char* packetFormat11N, char* guardInterval11N, char* waveformFileName, int bufferSize) { int err = ERR_OK; char keyword[MAX_BUFFER_SIZE] = {'\0'}, datarateString[MAX_BUFFER_SIZE] = {'\0'}; int rateIndexBegin = 0, rateIndexEnd = 0; map<string, WIFI_SETTING_STRUCT>::iterator inputMap_Iter; // Find out the datarate index if ( (wifiMode==WIFI_11B)||(wifiMode==WIFI_11AG) ) { if ((strcmp(bandwidth,"HALF")==0) || (strcmp(bandwidth,"QUAR")==0)) { // 11p // do nothing } else { for (int i=0;i<MAX_BUFFER_SIZE;i++) { if (datarate[i] == '-') { rateIndexBegin = i+1; } else if (datarate[i] == '\0') { rateIndexEnd = i; break; } else { // do nothing, keep searching... } } // Copy the datarate int rateIndex = 0; for (int i=rateIndexBegin;i<=rateIndexEnd;i++) { datarateString[rateIndex] = datarate[i]; rateIndex++; } } } else // WIFI_11N_HT20 or WIFI_11N_HT40 { // do nothing } // Find out the keyword of the waveform file name if (wifiMode==WIFI_11B) { if (0==strcmp(preamble, "LONG")) { if (0==strcmp(datarateString, "1")) // Waveform name for 1 Mbps (Long Preamble only) { sprintf_s(keyword, MAX_BUFFER_SIZE, "%s_11B_%s_%s", perfix, datarateString, postfix); } else { sprintf_s(keyword, MAX_BUFFER_SIZE, "%s_11B_%sL_%s", perfix, datarateString, postfix); } } else // 802.11b preamble = SHORT { if (0==strcmp(datarateString, "1")) // Waveform name for 1 Mbps (Long Preamble only) { sprintf_s(keyword, MAX_BUFFER_SIZE, "%s_11B_%s_%s", perfix, datarateString, postfix); } else { sprintf_s(keyword, MAX_BUFFER_SIZE, "%s_11B_%sS_%s", perfix, datarateString, postfix); } } } else if (wifiMode==WIFI_11AG) { if ((strcmp(bandwidth,"HALF")==0) || (strcmp(bandwidth,"QUAR")==0)) { sprintf_s(keyword, MAX_BUFFER_SIZE, "%s_11P_%s_%s", perfix, datarate, postfix); } else { sprintf_s(keyword, MAX_BUFFER_SIZE, "%s_11AG_%s_%s", perfix, datarateString, postfix); } } else // WIFI_11N_HT20 or WIFI_11N_HT40 { /***************************************************************** * For backward compatibility, * *we use old waveform names for mixed, long guard interval format * * IQlite merge; Tracy Yu ; 2012-03-31 * ******************************************************************/ if (0==strcmp(guardInterval11N, "LONG") && 0==strcmp(packetFormat11N, "MIXED")) // 802.11n, mixed format, long preamble, use old default waveform name { sprintf_s(keyword, bufferSize, "%s_11N_%s_%s_%s_%s", perfix, bandwidth, packetFormat11N, datarate, postfix); } else if (0==strcmp(guardInterval11N, "LONG") && 0==strcmp(packetFormat11N, "GREENFIELD")) //802.11n long guard interval, greefield { sprintf_s(keyword, bufferSize, "%s_11N_%s_%s_L_GI_%s_%s", perfix, bandwidth, packetFormat11N, datarate, postfix); } else //802.11n short guard interval, mixed/greenfield { sprintf_s(keyword, bufferSize, "%s_11N_%s_%s_S_GI_%s_%s", perfix, bandwidth, packetFormat11N, datarate, postfix); } } // Searching the keyword in g_globalSettingParamMap inputMap_Iter = g_globalSettingParamMap.find(keyword); if( inputMap_Iter!=g_globalSettingParamMap.end() ) { char dummyString[MAX_BUFFER_SIZE]; strcpy_s (dummyString, MAX_BUFFER_SIZE, (char*)inputMap_Iter->second.value); if ( strlen(g_defaultFilePath)>0 ) // default waveform file path not empty { sprintf_s(waveformFileName, bufferSize, "%s/%s", g_defaultFilePath, dummyString); } else // default waveform file path is empty, then using g_globalSettingParam.PER_WAVEFORM_PATH { sprintf_s(waveformFileName, bufferSize, "%s/%s", g_globalSettingParam.PER_WAVEFORM_PATH, dummyString); } //if Tester is IQxel and file extension is .ref change file extension from .ref to .iqref if( g_iTesterName == IQTYPE_XEL ) { char *pch = NULL; pch = strstr(waveformFileName,".ref\0"); if(pch!= NULL) strncpy (pch,".iqref\0",7); } // Wave file checking FILE *waveFile; fopen_s(&waveFile, waveformFileName, "r"); if (!waveFile) { if ( strlen(g_defaultFilePath)>0 ) // Default waveform file path not empty, but still can't find the waveformfile, then return error. { err = TM_ERR_PARAM_DOES_NOT_EXIST; } else // Try to find the file in upper folder { char tempPath[MAX_BUFFER_SIZE] = {'\0'}; sprintf_s(tempPath, bufferSize, "../%s", waveformFileName); fopen_s(&waveFile, tempPath, "r"); if (!waveFile) { err = TM_ERR_PARAM_DOES_NOT_EXIST; } else { // Save the path to default path name sprintf_s(g_defaultFilePath, bufferSize, "../%s", g_globalSettingParam.PER_WAVEFORM_PATH); // And using the new path sprintf_s(waveformFileName, bufferSize, "%s", tempPath); fclose(waveFile); waveFile = NULL; } } } else { fclose(waveFile); waveFile = NULL; } } else { err = TM_ERR_PARAM_DOES_NOT_EXIST; } return err; } // IQlite merge; Tracy Yu ; 2012-03-31 int GetPacketNumber(int wifiMode, char* bandwidth, char* datarate, char* packetFormat11N, char* guardInterval11N, int *packetNumber) { int err = ERR_OK; char keyword[MAX_BUFFER_SIZE] = {'\0'}, datarateString[MAX_BUFFER_SIZE] = {'\0'}; int rateIndexBegin = 0, rateIndexEnd = 0; map<string, WIFI_SETTING_STRUCT>::iterator inputMap_Iter; // Find out the datarate index if ( (wifiMode==WIFI_11B)||(wifiMode==WIFI_11AG) ) { if ((strcmp(bandwidth,"HALF")==0) || (strcmp(bandwidth,"QUAR")==0)) { // 11p // do nothing } else { for (int i=0;i<MAX_BUFFER_SIZE;i++) { if (datarate[i] == '-') { rateIndexBegin = i+1; } else if (datarate[i] == '\0') { rateIndexEnd = i; break; } else { // do nothing, keep searching... } } // Copy the datarate int rateIndex = 0; for (int i=rateIndexBegin;i<=rateIndexEnd;i++) { datarateString[rateIndex] = datarate[i]; rateIndex++; } } } else // WIFI_11N_HT20 or WIFI_11N_HT40 { // do nothing } // Find out the keyword of the waveform file name if (wifiMode==WIFI_11B) { sprintf_s(keyword, MAX_BUFFER_SIZE, "PER_11B_%s_PACKETS_NUM", datarateString); } else if (wifiMode==WIFI_11AG) { if ((strcmp(bandwidth,"HALF")==0) || (strcmp(bandwidth,"QUAR")==0)) { sprintf_s(keyword, MAX_BUFFER_SIZE, "PER_11P_%s_PACKETS_NUM", datarate); } else { sprintf_s(keyword, MAX_BUFFER_SIZE, "PER_11AG_%s_PACKETS_NUM", datarateString); } } else // WIFI_11N_HT20 or WIFI_11N_HT40 { /***************************************************************** * For backward compatibility, * *we use old waveform names for mixed, long guard interval format * * IQlite merge; Tracy Yu ; 2012-03-31 * ******************************************************************/ if (0==strcmp(guardInterval11N, "LONG") && 0==strcmp(packetFormat11N, "MIXED")) // 802.11n, mixed format, long preamble, use old default waveform name { sprintf_s(keyword, MAX_BUFFER_SIZE, "PER_11N_%s_%s_%s_PACKETS_NUM", bandwidth, packetFormat11N, datarate); } else if (0==strcmp(guardInterval11N, "LONG") && 0==strcmp(packetFormat11N, "GREENFIELD")) //802.11n long guard interval, greefield { sprintf_s(keyword, MAX_BUFFER_SIZE, "PER_11N_%s_%s_L_GI_%s_PACKETS_NUM", bandwidth, packetFormat11N, datarate); } else //802.11n short guard interval, mixed/greenfield { sprintf_s(keyword, MAX_BUFFER_SIZE, "PER__11N_%s_%s_S_GI_%s_PACKETS_NUM", bandwidth, packetFormat11N, datarate); } } // Searching the keyword in g_globalSettingParamMap inputMap_Iter = g_globalSettingParamMap.find(keyword); if( inputMap_Iter!=g_globalSettingParamMap.end() ) { *packetNumber = *((int*)inputMap_Iter->second.value); } else { err = TM_ERR_PARAM_DOES_NOT_EXIST; } return err; } int CheckPathLossTable(int testID, int freqMHz, int ant01, int ant02, int ant03, int ant04, double *cableLoss, double *cableLossReturn, double *cableLossDb) { int err = ERR_OK; err = CheckPathLossTableExt(testID, freqMHz, ant01, ant02, ant03, ant04, cableLoss, cableLossReturn, cableLossDb, TX_TABLE); return err; } int CheckPathLossTableExt(int testID, int freqMHz, int ant01, int ant02, int ant03, int ant04, double *cableLoss, double *cableLossReturn, double *cableLossDb, int indicatorTxRx) { int err = ERR_OK; try { int ant[4] = { ant01, ant02, ant03, ant04 }; for ( int i=0;i<MAX_DATA_STREAM;i++) { if ( ant[i] ) // Path enabled // IQlite merge; Tracy Yu ; 2012-03-31 { if ( 0==cableLoss[i] ) // 0: means read path loss from TM_TABLE { err = TM_GetPathLossAtFrequency(testID, freqMHz, &cableLoss[i], i, indicatorTxRx); if (err!=ERR_OK) { cableLoss[i] = NA_NUMBER; cableLossReturn[i] = NA_NUMBER; throw (i+1); } else { cableLossReturn[i] = cableLoss[i]; } } else // using user_defined path loss value { cableLossReturn[i] = cableLoss[i]; } } else // This path not enabled; // IQlite merge; Tracy Yu ; 2012-03-31 { cableLoss[i] = NA_NUMBER; cableLossReturn[i] = NA_NUMBER; } } *cableLossDb = CalcCableLossDb( ant01, ant02, ant03, ant04, cableLoss[0], cableLoss[1], cableLoss[2], cableLoss[3]); } catch(int errReturn) { return errReturn; } catch(...) { return -1; } return err; } double CalcCableLossDb(int ant1, int ant2, int ant3, int ant4, double cableLoss1, double cableLoss2, double cableLoss3, double cableLoss4) { double resultDb = 0.0; int antNumber = ant1 + ant2 + ant3 + ant4; if (ant1==1) // antenna 1 is ON { resultDb = resultDb + pow( 10, (cableLoss1/10) ); } if (ant2==1) // antenna 2 is ON { resultDb = resultDb + pow( 10, (cableLoss2/10) ); } if (ant3==1) // antenna 3 is ON { resultDb = resultDb + pow( 10, (cableLoss3/10) ); } if (ant4==1) // antenna 4 is ON { resultDb = resultDb + pow( 10, (cableLoss4/10) ); } if ( (antNumber==0)||(resultDb==0) ) { resultDb = 0.0; } else { resultDb = 10 * log10(resultDb/antNumber); } return resultDb; } WIFI_MIMO_TEST_API int GetWiFiTestID(TM_ID* wifiTestID) { *wifiTestID = g_WiFi_Test_ID; return ERR_OK; } WIFI_MIMO_TEST_API int SetWiFiTestID(TM_ID wifiTestID) { g_WiFi_Test_ID = wifiTestID; return ERR_OK; } WIFI_MIMO_TEST_API int GetWiFiDutID(vDUT_ID* wifiDutID) { *wifiDutID = g_WiFi_Dut; return ERR_OK; } WIFI_MIMO_TEST_API int GetWiFiGlobalSetting(WIFI_GLOBAL_SETTING** wifiGlobleSetting) { *wifiGlobleSetting = &g_globalSettingParam; return ERR_OK; } WIFI_MIMO_TEST_API int SetTesterNumber(int testerNumber) { g_Tester_Number = testerNumber; return ERR_OK; } WIFI_MIMO_TEST_API int GetTesterNumber(int *testerNumber) { *testerNumber = g_Tester_Number; return ERR_OK; } WIFI_MIMO_TEST_API int SetTesterType(int testerType) { g_Tester_Type = testerType; return ERR_OK; } WIFI_MIMO_TEST_API int GetTesterType(int *testerType) { *testerType = g_Tester_Type; return ERR_OK; } WIFI_MIMO_TEST_API int SetTesterReconnect(int flag) { g_Tester_Reconnect = flag; return ERR_OK; } WIFI_MIMO_TEST_API int GetTesterReconnect(int *flag) { *flag = g_Tester_Reconnect; return ERR_OK; } WIFI_MIMO_TEST_API int SetDutConfigChanged(bool changed) { g_dutConfigChanged = changed; return ERR_OK; } WIFI_MIMO_TEST_API int GetDutConfigChanged(bool *changed) { *changed = g_dutConfigChanged; return ERR_OK; } WIFI_MIMO_TEST_API int GetDutTxActived(bool* vDutTxActived) { *vDutTxActived = g_vDutTxActived; return ERR_OK; } WIFI_MIMO_TEST_API int SetDutTxActived(bool vDutTxActived) { g_vDutTxActived = vDutTxActived; return ERR_OK; } WIFI_MIMO_TEST_API int GetTesterName(int *flag) { *flag = g_iTesterName; return ERR_OK; } WIFI_MIMO_TEST_API int SetTesterName(int flag) { g_iTesterName = flag; return ERR_OK; } int CheckConnectionVsaMasterAndAntennaPort( std::map<std::string, WIFI_SETTING_STRUCT>& inputMap) { int err = 0; char vsaValue[MAX_BUFFER_SIZE] ={'\0'}; int txEnabledCondition = 0; int *integerValue; std::map<std::string, WIFI_SETTING_STRUCT>::iterator inputMapIter; inputMapIter = inputMap.find("VSA1_CONNECTION"); if(inputMapIter != inputMap.end()) { if(!strcmp((char *)inputMapIter->second.value, "OFF")) { //FIRST CONDITION: VSAMASTER IS OFF err = -1; } else { sprintf_s(vsaValue, MAX_BUFFER_SIZE, "%s", inputMapIter->second.value); if(!strcmp(vsaValue, "TX1")) // match { inputMapIter = inputMap.find("TX1"); integerValue = reinterpret_cast<int *>(inputMapIter->second.value); txEnabledCondition = *integerValue; } else if(!strcmp(vsaValue, "TX2")) { inputMapIter = inputMap.find("TX2"); integerValue = reinterpret_cast<int *>(inputMapIter->second.value); txEnabledCondition = *integerValue; } else if(!strcmp(vsaValue, "TX3")) { inputMapIter = inputMap.find("TX3"); integerValue = reinterpret_cast<int *>(inputMapIter->second.value); txEnabledCondition = *integerValue; } else if(!strcmp(vsaValue, "TX4")) { inputMapIter = inputMap.find("TX4"); integerValue = reinterpret_cast<int *>(inputMapIter->second.value); txEnabledCondition = *integerValue; } else { txEnabledCondition = 0; } // 6: IQV_TRIG_TYPE_IF2_NO_CAL if(!txEnabledCondition && (6 == g_globalSettingParam.VSA_TRIGGER_TYPE)) { //MEANS: EXISTED CONNECTION BETWEEN VSAMASTER AND ANTENNA PORTS err = -1; } else { err = 0; } } } else { //CAN'T FIND "VSA1_CONNECTION" err = -1; } return err; } int CheckConnectionVsaAndAntennaPort( std::map<std::string, WIFI_SETTING_STRUCT>& inputMap, int *vsaMappingTx, int *portStatus) { int err = 0; char tmpStr[MAX_BUFFER_SIZE]; std::map<std::string, WIFI_SETTING_STRUCT>::iterator inputMapIter; for(int i=0;i<MAX_TESTER_NUM;i++)//get all valid/unvald tester connection { //find port status of vsg sprintf_s(tmpStr, MAX_BUFFER_SIZE, "VSA%d_PORT", i+1); inputMapIter = inputMap.find(tmpStr); if(!_stricmp((char *)inputMapIter->second.value, "LEFT")) { portStatus[i] = PORT_LEFT; } else if(!_stricmp((char *)inputMapIter->second.value, "RIGHT")) { portStatus[i] = PORT_RIGHT; } else { portStatus[i] = g_globalSettingParam.VSAs_PORT[i]; } //find connection between vsa and antenna port sprintf_s(tmpStr, MAX_BUFFER_SIZE, "VSA%d_CONNECTION", i+1); inputMapIter = inputMap.find(tmpStr); if(inputMapIter != inputMap.end()) { for(int j=0;j<MAX_CHAIN_NUM;j++) { sprintf_s(tmpStr, MAX_BUFFER_SIZE, "TX%d", j+1); if(!_stricmp((char *)inputMapIter->second.value, tmpStr)) { vsaMappingTx[i] = j+1; break; } else { continue; } } } else { continue; } } return err; } int CheckConnectionVsgAndAntennaPort( std::map<std::string, WIFI_SETTING_STRUCT>& inputMap, int *vsgMappingRx, int *portStatus) { int err = 0; char tmpStr[MAX_BUFFER_SIZE]; std::map<std::string, WIFI_SETTING_STRUCT>::iterator inputMapIter; std::map<std::string, WIFI_SETTING_STRUCT>::iterator rxChainIter; for(int i=0;i<MAX_TESTER_NUM;i++) { //find port status of vsg sprintf_s(tmpStr, MAX_BUFFER_SIZE, "VSG%d_PORT", i+1); inputMapIter = inputMap.find(tmpStr); if(!_stricmp((char *)inputMapIter->second.value, "LEFT")) { portStatus[i] = PORT_LEFT; } else if(!_stricmp((char *)inputMapIter->second.value, "RIGHT")) { portStatus[i] = PORT_RIGHT; } else { portStatus[i] = g_globalSettingParam.VSGs_PORT[i]; } //Find connection between vsg and antenna port sprintf_s(tmpStr, MAX_BUFFER_SIZE, "VSG%d_CONNECTION", i+1); inputMapIter = inputMap.find(tmpStr); if(inputMapIter != inputMap.end()) { for(int j=0;j<MAX_CHAIN_NUM;j++) { sprintf_s(tmpStr, MAX_BUFFER_SIZE, "RX%d", j+1); if(!_stricmp((char *)inputMapIter->second.value, tmpStr)) { // VSG[i]_CONNECTION = RX[j] vsgMappingRx[i] = j+1; //rxChainIter = inputMap.find(tmpStr); //if(rxChainIter != inputMap.end()) //{ // chainStatus = reinterpret_cast<int *>(rxChainIter->second.value); // if(0 == *chainStatus) // { // portStatus[i] = PORT_OFF; // } // else // { // //keep portStatus // } //} break; } else { continue; } } //how do we know VSG[i]_CONNECTION is set to // - either one of RX1, RX2, RX3 and RX4 // - or OFF // - or something else, which is invalid if( vsgMappingRx[i]>=1 && vsgMappingRx[i] <=4) { // - either one of RX1, RX2, RX3 and RX4 } else if(!_stricmp((char *)inputMapIter->second.value, "OFF")) { // We need to "disalbe" RF power of VSG vsgMappingRx[i] = 0; } else { //TODO: error needs to be generated // vsgMappingRx[i] remains -1 } } else { continue; } } return err; } int PassTestResultToDutInputContainer( map<string, WIFI_SETTING_STRUCT>& returnMap) { int err = ERR_OK; map<string, WIFI_SETTING_STRUCT>::iterator returnMap_Iter; ::vDUT_ClearParameters(g_WiFi_Dut); returnMap_Iter = returnMap.begin(); while( returnMap_Iter != returnMap.end() ) { if( returnMap_Iter->second.type==WIFI_SETTING_TYPE_INTEGER ) { int *valueInteger = reinterpret_cast<int *>(returnMap_Iter->second.value); err = ::vDUT_AddIntegerParameter(g_WiFi_Dut, (char*)returnMap_Iter->first.c_str(), *valueInteger); if (vDUT_ERR_OK!=err) { // If TM_AddIntegerReturn fails, no need to continue break; } } else if(returnMap_Iter->second.type==WIFI_SETTING_TYPE_DOUBLE) { double *valueDouble = reinterpret_cast<double *>(returnMap_Iter->second.value); err = ::vDUT_AddDoubleParameter(g_WiFi_Dut, (char*)returnMap_Iter->first.c_str(), *valueDouble); if (vDUT_ERR_OK!=err) { // If TM_AddDoubleReturn fails, no need to continue break; } } else if(returnMap_Iter->second.type==WIFI_SETTING_TYPE_STRING) { char *valueString = reinterpret_cast<char *>(returnMap_Iter->second.value); err = ::vDUT_AddStringParameter(g_WiFi_Dut, (char*)returnMap_Iter->first.c_str(), valueString); if (vDUT_ERR_OK!=err) { // If TM_AddStringReturn fails, no need to continue break; } } //else if( returnMap_Iter->second.type==WIFI_SETTING_TYPE_ARRAY_DOUBLE ) //{ // vector<double> doubleVector = * reinterpret_cast<vector<double> *>(returnMap_Iter->second.value); // if (0 != doubleVector.size()) // { // double *doubleArray = new double[(int) doubleVector.size()]; // for (unsigned int i=0; i<doubleVector.size(); i++) // { // doubleArray[i] = doubleVector[i]; // } // err = ::vDUT_AddDoubleParameters(g_WiFi_Test_ID, (char*)returnMap_Iter->first.c_str(), doubleArray, (int)doubleVector.size()); // delete [] doubleArray; // if (vDUT_ERR_OK!=err) // { // // If TM_AddDoubleReturn fails, no need to continue // break; // } // } // else // { // // do nothing // } //} else { // Unknown type //err = -1; } returnMap_Iter++; } return err; } double CalculateIQtoP(double data_i, double data_q) { return (data_i*data_i + data_q*data_q); }
29.845154
203
0.622718
[ "vector" ]
adcd99c30a9152c05c9160238fbe71e58695bb42
88,000
cpp
C++
lib/nes/tests/instruction-tests.cpp
beunprogrammeur/basic-nes-emulator
3a799e07c899857e9e07a13d3a500484347e874b
[ "MIT" ]
null
null
null
lib/nes/tests/instruction-tests.cpp
beunprogrammeur/basic-nes-emulator
3a799e07c899857e9e07a13d3a500484347e874b
[ "MIT" ]
null
null
null
lib/nes/tests/instruction-tests.cpp
beunprogrammeur/basic-nes-emulator
3a799e07c899857e9e07a13d3a500484347e874b
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <nes/cpu/instructions/iinstruction_error_handler.h> #include <nes/cpu/instructions/instructions.h> #include <nes/cpu/bus/ibus.h> #include <nes/cpu/registers.h> #include <vector> #include <nes/cpu/instructions/instructionset.h> #include <type_traits> #include <sstream> using namespace nes::cpu::instructions; using namespace nes::cpu; // Definition of mock types class MockInstructionErrorHandler : public IInstructionErrorHandler { private: bool _raised; AddressingMode _mode; public: virtual void invalidMode(IInstruction& instruction, AddressingMode mode) override { _raised = true; _mode = mode; } void reset() { _raised = false; } bool raised() const { return _raised; } AddressingMode mode() const { return _mode; } }; class MockBus : public nes::cpu::bus::IBus { private: static const int size = 0xffff; uint8_t _memory[size]; public: MockBus() { for(int i = 0; i < size; i++) _memory[i] = 0x77; } // never test againts 0x77. if that number is found the instruction is broken virtual uint8_t read(uint16_t address) const { return _memory[address]; } // or specific bus address is not inintialized properly virtual void write(uint16_t address, uint8_t value) { _memory[address] = value; } virtual void connect(nes::peripherals::IPeripheral& peripheral) { /* not used */ } }; // used for the LD[A,X,Y] and ST[A,X,Y] instructions enum class reg { a,x,y }; // Definition of test fixture class InstructionTestFixture : public testing::Test { protected: MockInstructionErrorHandler* handler; MockBus* bus; nes::cpu::Registers registers; void SetUp() override { handler = new MockInstructionErrorHandler; bus = new MockBus; registers.reset(); } void TearDown() override { delete handler; delete bus; handler = nullptr; bus = nullptr; } template<typename T> std::string hex(T number) { std::stringstream ss; ss << "0x"; constexpr char hx[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; for(int i = 1; i <= sizeof(T) * 2; i++) { ss << hx[number >> ((sizeof(T) * 2 - 1) * 4)]; number <<= 4; } return ss.str(); } void compare(const nes::cpu::Registers& expected) { EXPECT_EQ(expected.a , registers.a ) << "expected accumulator to be " << hex(expected.a ) << " but it was " << hex(registers.a ); EXPECT_EQ(expected.x , registers.x ) << "expected index x to be " << hex(expected.x ) << " but it was " << hex(registers.x ); EXPECT_EQ(expected.y , registers.y ) << "expected index y to be " << hex(expected.y ) << " but it was " << hex(registers.y ); EXPECT_EQ(expected.pc , registers.pc ) << "expected program counter to be " << hex(expected.pc ) << " but it was " << hex(registers.pc ); EXPECT_EQ(expected.sp , registers.sp ) << "expected stack pointer to be " << hex(expected.sp ) << " but it was " << hex(registers.sp ); EXPECT_EQ(expected.p.n, registers.p.n) << "expected negative flag to be " << expected.p.n << " but it was " << registers.p.n; EXPECT_EQ(expected.p.u, registers.p.u) << "expected unused flag to be " << expected.p.u << " but it was " << registers.p.u; EXPECT_EQ(expected.p.v, registers.p.v) << "expected overflow flag to be " << expected.p.v << " but it was " << registers.p.v; EXPECT_EQ(expected.p.b, registers.p.b) << "expected break flag to be " << expected.p.b << " but it was " << registers.p.b; EXPECT_EQ(expected.p.d, registers.p.d) << "expected decimal flag to be " << expected.p.d << " but it was " << registers.p.d; EXPECT_EQ(expected.p.i, registers.p.i) << "expected IRQ flag to be " << expected.p.i << " but it was " << registers.p.i; EXPECT_EQ(expected.p.z, registers.p.z) << "expected zero flag to be " << expected.p.z << " but it was " << registers.p.z; EXPECT_EQ(expected.p.c, registers.p.c) << "expected carry flag to be " << expected.p.c << " but it was " << registers.p.c; } void execute(IInstruction& instruction, int expectedTicks, bool handlerCalled = false) { EXPECT_EQ(expectedTicks, instruction.execute(registers, *bus)); EXPECT_EQ(handlerCalled, handler->raised()); } template<typename T> void run(AddressingMode mode, int ticks, Registers& expected, bool handlerCalled = false) { static_assert(std::is_base_of<IInstruction, T>::value, "T must be derived of IInstruction"); auto instruction = T(*handler); instruction.setMode(mode); execute(instruction, ticks, handlerCalled); compare(expected); } // loads a binary into the bus and preps the program counter void load(uint16_t startAddress, std::initializer_list<uint8_t> binary) { int i = 1; for(auto byte : binary) { bus->write(startAddress + i++, byte); } registers.pc = startAddress; } // stack value should be reverse order. newest stack entry first. void stackcmp(std::initializer_list<uint8_t> stack) { auto sp = registers.sp; for(auto expected : stack) { auto actual = bus->read(0x0100 | ++sp); EXPECT_EQ(expected, actual) << "Expected stack value at " << hex(sp) << " to be " << hex(expected) << " but was " << hex(actual); } } uint8_t lo(uint16_t value) { return static_cast<uint8_t>(value & 0xff); } uint8_t hi(uint16_t value) { return static_cast<uint8_t>(value >> 8); } // push value onto the stack void push(uint8_t value) { bus->write(0x0100 | registers.sp--, value); } void LDNImmediateTest(BaseInstruction& instruction, reg instructionReg) { instruction.setMode(AddressingMode::IMM); auto expected = registers; uint8_t* cmpreg = &expected.a; switch(instructionReg) { case reg::x: cmpreg = &expected.x; break; case reg::y: cmpreg = &expected.y; break; } load(0xFF00, {0x80}); *cmpreg = 0x80; expected.pc = registers.pc + 2; expected.p.n = true; execute(instruction, 2, false); compare(expected); load(0xFF00, {0x00}); *cmpreg = 0x00; expected.pc = registers.pc + 2; expected.p.n = false; expected.p.z = true; execute(instruction, 2, false); compare(expected); } void LDNZeroPageTest(BaseInstruction& instruction, reg instructionReg) { instruction.setMode(AddressingMode::ZP); auto expected = registers; uint8_t* cmpreg = &expected.a; switch(instructionReg) { case reg::x: cmpreg = &expected.x; break; case reg::y: cmpreg = &expected.y; break; } load(0xFF00, {0x40}); bus->write(0x40, 0x80); *cmpreg = 0x80; expected.pc = registers.pc + 2; expected.p.n = true; execute(instruction, 3, false); compare(expected); load(0xFF00, {0x40}); bus->write(0x40, 0x00); *cmpreg = 0x00; expected.pc = registers.pc + 2; expected.p.n = false; expected.p.z = true; execute(instruction, 3, false); compare(expected); } void LDNZeroPageXYTest(BaseInstruction& instruction, reg instructionReg, reg addReg) { auto expected = registers; auto mode = AddressingMode::ZPX; uint8_t* cmpreg = &expected.a; registers.x = -3; expected.x = -3; switch(instructionReg) { case reg::x: cmpreg = &expected.x; mode = AddressingMode::ZPY; registers.y = -3; expected.y = -3; break; case reg::y: cmpreg = &expected.y; mode = AddressingMode::ZPX; registers.x = -3; expected.x = -3; break; } instruction.setMode(mode); // also does a page boundary load(0xFF00, {0x02}); bus->write(0xFF, 0x80); // zeropage xy wraps around in page 0 *cmpreg = 0x80; expected.pc = registers.pc + 2; expected.p.n = true; execute(instruction, 4, false); compare(expected); load(0xFF00, {0x02}); bus->write(0xFF, 0x00); *cmpreg = 0x00; expected.pc = registers.pc + 2; expected.p.n = false; expected.p.z = true; execute(instruction, 4, false); compare(expected); } void LDNAbsoluteTest(BaseInstruction& instruction, reg instructionReg) { instruction.setMode(AddressingMode::ABS); auto expected = registers; uint8_t* cmpreg = &expected.a; switch(instructionReg) { case reg::x: cmpreg = &expected.x; break; case reg::y: cmpreg = &expected.y; break; } load(0xFF00, {0x20, 0x04}); bus->write(0x420, 0x80); *cmpreg = 0x80; expected.pc = registers.pc + 2; expected.p.n = true; execute(instruction, 4, false); compare(expected); load(0xFF00, {0x20, 0x04}); bus->write(0x420, 0x00); *cmpreg = 0x00; expected.pc = registers.pc + 2; expected.p.n = false; expected.p.z = true; execute(instruction, 4, false); compare(expected); } void LDNAbsoluteXYTest(BaseInstruction& instruction, reg instructionReg, reg addReg) { auto expected = registers; auto mode = AddressingMode::ABSX; uint8_t* cmpreg = &expected.a; registers.x = -1; expected.x = -1; switch(instructionReg) { case reg::x: cmpreg = &expected.x; mode = AddressingMode::ABSY; registers.y = -1; expected.y = -1; break; case reg::y: cmpreg = &expected.y; mode = AddressingMode::ABSX; registers.x = -1; expected.x = -1; break; } instruction.setMode(mode); // also does a page boundary load(0xFF00, {0x00, 0x04}); bus->write(0x3FF, 0x80); *cmpreg = 0x80; expected.pc = registers.pc + 3; expected.p.n = true; execute(instruction, 5, false); compare(expected); load(0xFF00, {0x21, 0x04}); bus->write(0x420, 0x00); *cmpreg = 0x00; expected.pc = registers.pc + 3; expected.p.n = false; expected.p.z = true; execute(instruction, 4, false); compare(expected); } void STNZPTest(BaseInstruction& instruction, uint8_t& source) { instruction.setMode(AddressingMode::ZP); load(0xFF00, {0x14}); source = 0xB0; // value to write to the above address auto expected = registers; expected.pc += 2; execute(instruction, 3, false); compare(expected); EXPECT_EQ(0xB0, bus->read(0x14)); } void STNABSTest(BaseInstruction& instruction, uint8_t& source) { instruction.setMode(AddressingMode::ABS); load(0xFF00, {0xBA, 0xAB}); source = 0xB0; // value to write to the above address auto expected = registers; expected.pc += 3; execute(instruction, 4, false); compare(expected); EXPECT_EQ(0xB0, bus->read(0xABBA)); } void STNZPXYTest(BaseInstruction& instruction, uint8_t& source, reg addReg) { switch(addReg) { case reg::x: instruction.setMode(AddressingMode::ZPX); registers.x = -1; break; case reg::y: instruction.setMode(AddressingMode::ZPY); registers.y = -1; break; } load(0xFF00, {0x02}); source = 0xB0; auto expected = registers; expected.pc += 2; execute(instruction, 4, false); compare(expected); EXPECT_EQ(0xB0, bus->read(0x01)); } void STNABSXYTest(BaseInstruction& instruction, uint8_t& source, reg addReg) { switch(addReg) { case reg::x: instruction.setMode(AddressingMode::ABSX); registers.x = -1; break; case reg::y: instruction.setMode(AddressingMode::ABSY); registers.y = -1; break; } load(0xFF00, {0xBB, 0xAB}); source = 0xB0; auto expected = registers; expected.pc += 3; execute(instruction, 5, false); compare(expected); EXPECT_EQ(0xB0, bus->read(0xABBA)); } }; // based on information found here: http://www.obelisk.me.uk/6502/reference.html TEST_F(InstructionTestFixture, NOPTest) { auto expected = registers; expected.pc++; run<NOPInstruction>(AddressingMode::IMP, 1, expected); } TEST_F(InstructionTestFixture, CLCTest) { registers.p.c = true; auto expected = registers; expected.pc++; expected.p.c = false; run<CLCInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, CLDTest) { registers.p.d = true; auto expected = registers; expected.pc++; expected.p.d = false; run<CLDInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, BRKTest) { registers.pc = 0xABBA; // a number that we can identify the first and second byte order with. registers.p.c = true; // set some flags that we want to read back from the stack. registers.p.n = true; auto expected = registers; expected.p.b = true; expected.pc = 0xfffe; // IRQ vector expected.sp -= 3; run<BRKInstruction>(AddressingMode::IMP, 7, expected); expected.p.b = false; // this one is set after it enters the stack. so it should be fase for the stack comparison expected.pc = 0xABBA; // same for the PC stackcmp({ // we check in reverse order expected.p.toByte(), lo(expected.pc), hi(expected.pc), }); } TEST_F(InstructionTestFixture, ORAImmediateTest) { load(0xFF00, {0xf0}); registers.a = 0x01; auto expected = registers; expected.pc += 2; expected.a = 0xf1; expected.p.n = true; run<ORAInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {0x00}); registers.a = 0x00; expected = registers; expected.pc += 2; expected.a = 0; expected.p.n = false; expected.p.z = true; run<ORAInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, ORAZeroPageTest) { load(0xFF00, {0xf0}); bus->write(0xf0, 0x80); registers.a = 0x01; auto expected = registers; expected.pc += 2; expected.a = 0x81; expected.p.n = true; run<ORAInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0xaa}); bus->write(0xaa, 0x00); registers.a = 0x00; expected = registers; expected.pc += 2; expected.a = 0; expected.p.n = false; expected.p.z = true; run<ORAInstruction>(AddressingMode::ZP, 3, expected); } TEST_F(InstructionTestFixture, ORAZeroPageXTest) { load(0xFF00, {0xf0}); bus->write(0xf1, 0x80); registers.a = 0x01; registers.x = 0x01; // added to the address auto expected = registers; expected.pc += 2; expected.a = 0x81; expected.p.n = true; run<ORAInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0xff}); bus->write(0x01, 0x44); registers.x = 0x02; registers.a = 0x11; expected = registers; expected.pc += 2; expected.a = 0x55; expected.p.n = false; expected.p.z = false; run<ORAInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0xff}); bus->write(0x02, 0x0); registers.x = 0x03; registers.a = 0x00; expected = registers; expected.pc += 2; expected.a = 0x00; expected.p.n = false; expected.p.z = true; run<ORAInstruction>(AddressingMode::ZPX, 4, expected); } TEST_F(InstructionTestFixture, ORAAbsoluteTest) { load(0xFF00, {0xef, 0xbe}); bus->write(0xbeef, 0x80); registers.a = 0x01; auto expected = registers; expected.pc += 3; expected.a = 0x81; expected.p.n = true; run<ORAInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0x0d, 0xd0}); bus->write(0xd00d, 0x00); bus->write(0x0dd0, 0xff); // to make sure this fails if the msb and lsd are swapped registers.a = 0x00; expected = registers; expected.pc += 3; expected.a = 0; expected.p.n = false; expected.p.z = true; run<ORAInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, ORAAbsoluteXTest) { load(0xFF00, {0xee, 0xbe}); bus->write(0xbeef, 0x80); registers.a = 0x01; registers.x = 0x01; auto expected = registers; expected.pc += 3; expected.a = 0x81; expected.p.n = true; run<ORAInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0x0e, 0xd0}); bus->write(0xd00d, 0x00); bus->write(0x0dd0, 0xff); // to make sure this fails if the msb and lsd are swapped registers.a = 0x00; registers.x = -1; expected = registers; expected.pc += 3; expected.a = 0; expected.p.n = false; expected.p.z = true; run<ORAInstruction>(AddressingMode::ABSX, 4, expected); // cross page load(0xFF00, {0x00, 0xAA}); // addr 0xAA00, -1 is 0xA9FF thus page boundary crossed bus->write(0xA9FF, 0x11); registers.a = 0x44; registers.x = -1; // addr - 1 = 0xa9ff expected = registers; expected.pc += 3; expected.a = 0x55; expected.p.z = false; run<ORAInstruction>(AddressingMode::ABSX, 5, expected); // page cross + 1 tick } TEST_F(InstructionTestFixture, ORAAbsoluteYTest) { load(0xFF00, {0xee, 0xbe}); bus->write(0xbeef, 0x80); registers.a = 0x01; registers.y = 0x01; auto expected = registers; expected.pc += 3; expected.a = 0x81; expected.p.n = true; run<ORAInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0x0e, 0xd0}); bus->write(0xd00d, 0x00); bus->write(0x0dd0, 0xff); // to make sure this fails if the msb and lsd are swapped registers.a = 0x00; registers.y = -1; expected = registers; expected.pc += 3; expected.a = 0; expected.p.n = false; expected.p.z = true; run<ORAInstruction>(AddressingMode::ABSY, 4, expected); // cross page load(0xFF00, {0x00, 0xAA}); // addr 0xAA00, -1 is 0xA9FF thus page boundary crossed bus->write(0xA9FF, 0x11); registers.a = 0x44; registers.y = -1; // addr - 1 = 0xa9ff expected = registers; expected.pc += 3; expected.a = 0x55; expected.p.z = false; run<ORAInstruction>(AddressingMode::ABSY, 5, expected); // page cross + 1 tick } TEST_F(InstructionTestFixture, ORAIndirectXTest) { load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0x50; bus->write(0x02, 0x05); auto expected = registers; expected.pc += 2; expected.a = 0x55; run<ORAInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0x00; bus->write(0x02, 0x00); expected = registers; expected.pc += 2; expected.a = 0x00; expected.p.z = true; run<ORAInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0x01; bus->write(0x02, 0x80); expected = registers; expected.pc += 2; expected.a = 0x81; expected.p.z = false; expected.p.n = true; run<ORAInstruction>(AddressingMode::IINDX, 6, expected); } TEST_F(InstructionTestFixture, ORAIndirectYTest) { load(0xFF00, {0x01}); bus->write(0x01, 0x05); bus->write(0x06, 0x80); registers.a = 0x01; registers.y = 0x01; auto expected = registers; expected.pc += 2; expected.p.n = true; expected.a = 0x81; run<ORAInstruction>(AddressingMode::IINDY, 5, expected); // page cross test load(0xFF00, {0x01}); bus->write(0x01, 0x05); bus->write(0xFFFF, 0x00); // wraparound registers.a = 0x00; registers.y = -6; expected = registers; expected.pc += 2; expected.p.z = true; expected.p.n = false; expected.a = 0x00; run<ORAInstruction>(AddressingMode::IINDY, 6, expected); } TEST_F(InstructionTestFixture, ASLAccumulatorTest) { registers.a = 0; auto expected = registers; expected.pc++; expected.p.z = true; run<ASLInstruction>(AddressingMode::ACC, 2, expected); registers.a = 10; expected = registers; expected.pc++; expected.a <<= 1; expected.p.z = false; run<ASLInstruction>(AddressingMode::ACC, 2, expected); registers.a = 64; expected = registers; expected.pc++; expected.a <<= 1; expected.p.n = true; run<ASLInstruction>(AddressingMode::ACC, 2, expected); registers.a = 129; expected = registers; expected.pc++; expected.a = 2; expected.p.c = true; expected.p.n = false; run<ASLInstruction>(AddressingMode::ACC, 2, expected); } TEST_F(InstructionTestFixture, ASLZeroPageTest) { load(0xFF00, {0xBA}); bus->write(0xBA, 0x80); auto expected = registers; expected.pc += 3; expected.p.z = true; expected.p.c = true; run<ASLInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x00, bus->read(0xBA)); load(0xFF00, {0xBA}); bus->write(0xBA, 0x40); expected = registers; expected.pc += 3; expected.p.z = false; expected.p.c = false; expected.p.n = true; run<ASLInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x80, bus->read(0xBA)); } TEST_F(InstructionTestFixture, ASLZeroPageXTest) { load(0xFF00, {0xBA}); bus->write(0xBA, 0x80); auto expected = registers; expected.pc += 2; expected.p.z = true; expected.p.c = true; run<ASLInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x00, bus->read(0xBA)); load(0xFF00, {0xBA}); bus->write(0xBA, 0x40); expected = registers; expected.pc += 2; expected.p.z = false; expected.p.c = false; expected.p.n = true; run<ASLInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x80, bus->read(0xBA)); } TEST_F(InstructionTestFixture, ASLAbsoluteTest) { load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x80); auto expected = registers; expected.pc += 3; expected.p.z = true; expected.p.c = true; run<ASLInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x00, bus->read(0xABBA)); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x40); expected = registers; expected.pc += 3; expected.p.z = false; expected.p.c = false; expected.p.n = true; run<ASLInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x80, bus->read(0xABBA)); } TEST_F(InstructionTestFixture, ASLAbsoluteXTest) { load(0xFF00, {0xB9, 0xAB}); bus->write(0xABBA, 0x80); registers.x = 0x01; auto expected = registers; expected.pc += 3; expected.p.z = true; expected.p.c = true; run<ASLInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x00, bus->read(0xABBA)); load(0xFF00, {0xB9, 0xAB}); bus->write(0xABBA, 0x40); registers.x = 0x01; expected = registers; expected.pc += 3; expected.p.z = false; expected.p.c = false; expected.p.n = true; run<ASLInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x80, bus->read(0xABBA)); } TEST_F(InstructionTestFixture, PHPTest) { registers.p.n = true; registers.p.z = true; registers.p.d = true; auto expected = registers; expected.pc++; expected.sp--; run<PHPInstruction>(AddressingMode::IMP, 3, expected); stackcmp({registers.p.toByte()}); } TEST_F(InstructionTestFixture, BPLTest) { load(0xFF00, {0x00}); // load a 0, we don't really need to do anything because the negative flag is true registers.p.n = true; auto expected = registers; expected.pc += 2; run<BPLInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {0x04}); registers.p.n = false; expected = registers; expected.pc = 0xFF04; run<BPLInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {static_cast<uint8_t>(-1)}); // jump -1 so we hop to the previous page registers.p.n = false; expected = registers; expected.pc = 0xFF00 -1; run<BPLInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, JSRTest) { load(0xFF00, {0xBA, 0xAB}); auto expected = registers; expected.pc = 0xABBA; expected.sp -= 2; run<JSRInstruction>(AddressingMode::ABS, 6, expected); stackcmp({0x02, 0xFF}); } TEST_F(InstructionTestFixture, ANDImmediateTest) { load(0xFF00, {0x80}); registers.a = 0x81; auto expected = registers; expected.pc +=2; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {0x80}); registers.a = 0x01; expected = registers; expected.a = 0x00; expected.pc +=2; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, ANDZeroPageTest) { load(0xFF00, {0x40}); bus->write(0x40, 0x80); registers.a = 0x81; auto expected = registers; expected.pc +=2; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x40}); bus->write(0x40, 0x80); registers.a = 0x01; expected = registers; expected.a = 0x00; expected.pc +=2; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ZP, 3, expected); } TEST_F(InstructionTestFixture, ANDZeroPageXTest) { load(0xFF00, {0x3f}); bus->write(0x40, 0x80); registers.a = 0x81; registers.x = 0x01; auto expected = registers; expected.pc +=2; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0x3f}); bus->write(0x40, 0x80); registers.a = 0x01; registers.x = 0x01; expected = registers; expected.a = 0x00; expected.pc +=2; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ZPX, 4, expected); } TEST_F(InstructionTestFixture, ANDAbsoluteTest) { load(0xFF00, {0x40, 0x02}); bus->write(0x0240, 0x80); registers.a = 0x81; auto expected = registers; expected.pc +=3; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0x40, 0x02}); bus->write(0x0240, 0x80); registers.a = 0x01; expected = registers; expected.a = 0x00; expected.pc +=3; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, ANDAbsoluteXTest) { load(0xFF00, {0x3f, 0x02}); bus->write(0x0240, 0x80); registers.a = 0x81; registers.x = 0x01; auto expected = registers; expected.pc +=3; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0x3f, 0x02}); bus->write(0x0240, 0x80); registers.a = 0x01; registers.x = 0x01; expected = registers; expected.a = 0x00; expected.pc +=3; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0xFF, 0x02}); bus->write(0x0300, 0x80); registers.a = 0x01; registers.x = 0x1; expected = registers; expected.a = 0x00; expected.pc +=3; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ABSX, 5, expected); } TEST_F(InstructionTestFixture, ANDAbsoluteYTest) { load(0xFF00, {0x3f, 0x02}); bus->write(0x0240, 0x80); registers.a = 0x81; registers.y = 0x01; auto expected = registers; expected.pc +=3; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0x3f, 0x02}); bus->write(0x0240, 0x80); registers.a = 0x01; registers.y = 0x01; expected = registers; expected.a = 0x00; expected.pc +=3; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0xFF, 0x02}); bus->write(0x0300, 0x80); registers.a = 0x01; registers.y = 0x1; expected = registers; expected.a = 0x00; expected.pc +=3; expected.p.n = false; expected.p.z = true; run<ANDInstruction>(AddressingMode::ABSY, 5, expected); } TEST_F(InstructionTestFixture, ANDIndirectXTest) { load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0xf5; bus->write(0x02, 0x05); auto expected = registers; expected.pc += 2; expected.a = 0x05; run<ANDInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0xf5; bus->write(0x02, 0x00); expected = registers; expected.pc += 2; expected.a = 0x00; expected.p.z = true; run<ANDInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0xef; bus->write(0x02, 0x80); expected = registers; expected.pc += 2; expected.a = 0x80; expected.p.z = false; expected.p.n = true; run<ANDInstruction>(AddressingMode::IINDX, 6, expected); } TEST_F(InstructionTestFixture, ANDIndirectYTest) { load(0xFF00, {0x01}); bus->write(0x01, 0x05); bus->write(0x06, 0x80); registers.a = 0x81; registers.y = 0x01; auto expected = registers; expected.pc += 2; expected.p.n = true; expected.a = 0x80; run<ANDInstruction>(AddressingMode::IINDY, 5, expected); // page cross test load(0xFF00, {0x01}); bus->write(0x01, 0x05); bus->write(0xFFFF, 0x00); // wraparound registers.a = 0x00; registers.y = -6; expected = registers; expected.pc += 2; expected.p.z = true; expected.p.n = false; expected.a = 0x00; run<ANDInstruction>(AddressingMode::IINDY, 6, expected); } TEST_F(InstructionTestFixture, BITZeroPageTest) { bus->write(0xABBA, 0x55); load(0xFF00, {0xBA, 0xAB}); registers.a = 0x00; auto expected = registers; expected.pc += 3; expected.p.z = true; run<BITInstruction>(AddressingMode::ABS, 4, expected); bus->write(0xAB, 0x81); load(0xFF00, {0xAB}); registers.a = 0xf0; expected = registers; expected.pc += 3; expected.p.z = false; expected.p.n = true; run<BITInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, BITAbsoluteTest) { bus->write(0xABBA, 0x55); load(0xFF00, {0xBA, 0xAB}); registers.a = 0x00; auto expected = registers; expected.pc += 3; expected.p.z = true; run<BITInstruction>(AddressingMode::ABS, 4, expected); bus->write(0xABBA, 0x81); load(0xFF00, {0xBA, 0xAB}); registers.a = 0xf0; expected = registers; expected.pc += 3; expected.p.z = false; expected.p.n = true; run<BITInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, RORAccummulatorTest) { registers.a = 0x80; auto expected = registers; expected.pc++; expected.a >>= 1; run<RORInstruction>(AddressingMode::ACC, 2, expected); registers.a |= 0x01; expected = registers; expected.pc++; expected.a >>= 1; expected.p.c = true; run<RORInstruction>(AddressingMode::ACC, 2, expected); registers.a = 0x00; registers.p.c = true; expected = registers; expected.pc++; expected.a = 0x80; expected.p.c = false; expected.p.n = true; expected.p.z = false; run<RORInstruction>(AddressingMode::ACC, 2, expected); registers.reset(); registers.a = 1; expected = registers; expected.pc++; expected.a = 0; expected.p.c = true; expected.p.n = false; expected.p.z = true; run<RORInstruction>(AddressingMode::ACC, 2, expected); } TEST_F(InstructionTestFixture, RORZeroPageTest) { load(0xFF00, {0x04}); bus->write(0x04, 0x00); auto expected = registers; registers.p.c = true; expected.pc += 2; expected.p.n = true; run<RORInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x80, bus->read(0x04)); load(0xFF00, {0x04}); bus->write(0x04, 0x01); expected = registers; expected.pc += 2; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<RORInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x00, bus->read(0x04)); } TEST_F(InstructionTestFixture, RORZeroPageXTest) { load(0xFF00, {0x03}); bus->write(0x04, 0x00); registers.x = 0x01; auto expected = registers; registers.p.c = true; expected.pc += 2; expected.p.n = true; run<RORInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x80, bus->read(0x04)); load(0xFF00, {0x03}); bus->write(0x04, 0x01); registers.x = 0x01; expected = registers; expected.pc += 2; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<RORInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x00, bus->read(0x04)); } TEST_F(InstructionTestFixture, RORAbsoluteTest) { load(0xFF00, {0x04, 0x04}); bus->write(0x0404, 0x00); auto expected = registers; registers.p.c = true; expected.pc += 3; expected.p.n = true; run<RORInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x80, bus->read(0x0404)); load(0xFF00, {0x04, 0x04}); bus->write(0x0404, 0x01); expected = registers; expected.pc += 3; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<RORInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x00, bus->read(0x0404)); } TEST_F(InstructionTestFixture, RORAbsoluteXTest) { load(0xFF00, {0x03, 0x04}); bus->write(0x0404, 0x00); registers.x = 0x01; auto expected = registers; registers.p.c = true; expected.pc += 3; expected.p.n = true; run<RORInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x80, bus->read(0x0404)); load(0xFF00, {0x03, 0x04}); bus->write(0x0404, 0x01); registers.x = 0x01; expected = registers; expected.pc += 3; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<RORInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x00, bus->read(0x0404)); } TEST_F(InstructionTestFixture, ROLAccumulatorTest) { registers.a = 0x01; auto expected = registers; expected.pc++; expected.a <<= 1; run<ROLInstruction>(AddressingMode::ACC, 2, expected); registers.p.c = true; expected = registers; expected.pc++; expected.a <<= 1; expected.a |= 1; // the carry flag is now in bit 0 expected.p.c = false; run<ROLInstruction>(AddressingMode::ACC, 2, expected); registers.reset(); registers.a = 0x80; expected = registers; expected.pc++; expected.a = 0; expected.p.z = true; expected.p.c = true; run<ROLInstruction>(AddressingMode::ACC, 2, expected); registers.reset(); registers.a = 0x40; expected = registers; expected.pc++; expected.p.n = true; expected.a <<= 1; run<ROLInstruction>(AddressingMode::ACC, 2, expected); } TEST_F(InstructionTestFixture, ROLZeroPageTest) { load(0xFF00, {0x04}); bus->write(0x04, 0x40); auto expected = registers; expected.pc += 2; expected.p.n = true; run<ROLInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x80, bus->read(0x04)); load(0xFF00, {0x04}); bus->write(0x04, 0x80); expected = registers; expected.pc += 2; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<ROLInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x00, bus->read(0x04)); } TEST_F(InstructionTestFixture, ROLZeroPageXTest) { load(0xFF00, {0x03}); bus->write(0x04, 0x40); registers.x = 0x01; auto expected = registers; expected.pc += 2; expected.p.n = true; run<ROLInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x80, bus->read(0x04)); load(0xFF00, {0x03}); bus->write(0x04, 0x80); registers.x = 0x01; expected = registers; expected.pc += 2; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<ROLInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x00, bus->read(0x04)); } TEST_F(InstructionTestFixture, ROLAbsoluteTest) { load(0xFF00, {0x04, 0x04}); bus->write(0x0404, 0x40); auto expected = registers; expected.pc += 3; expected.p.n = true; run<ROLInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x80, bus->read(0x0404)); load(0xFF00, {0x04, 0x04}); bus->write(0x0404, 0x80); expected = registers; expected.pc += 3; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<ROLInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x00, bus->read(0x0404)); } TEST_F(InstructionTestFixture, ROLAbsoluteXTest) { load(0xFF00, {0x03, 0x04}); bus->write(0x0404, 0x40); registers.x = 0x01; auto expected = registers; expected.pc += 3; expected.p.n = true; run<ROLInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x80, bus->read(0x0404)); load(0xFF00, {0x03, 0x04}); bus->write(0x0404, 0x80); registers.x = 0x01; expected = registers; expected.pc += 3; expected.p.n = false; expected.p.c = true; expected.p.z = true; run<ROLInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x00, bus->read(0x0404)); } TEST_F(InstructionTestFixture, PLPTest) { auto expected = registers; expected.p.n = true; expected.p.c = true; expected.p.d = true; expected.pc++; push(expected.p.toByte()); // we push, the opcode pulls, so the sp is as it was run<PLPInstruction>(AddressingMode::IMP, 4, expected); } TEST_F(InstructionTestFixture, BMITest) { load(0xFF00, {0x00}); // load a 0, we don't really need to do anything because the negative flag is false registers.p.n = false; auto expected = registers; expected.pc += 2; run<BMIInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {0x04}); registers.p.n = true; expected = registers; expected.pc = 0xFF04; run<BMIInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {static_cast<uint8_t>(-1)}); // jump -1 so we hop to the previous page registers.p.n = true; expected = registers; expected.pc = 0xFF00 -1; run<BMIInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, SECTest) { auto expected = registers; expected.p.c = true; expected.pc++; run<SECInstruction>(AddressingMode::IMP, 2, expected); expected.p.c = true; expected.pc++; run<SECInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, RTITest) { auto expected = registers; // set some recognizable flags expected.p.c = true; expected.p.v = true; expected.p.n = true; expected.pc = 0xABBA; push(hi(expected.pc)); push(lo(expected.pc)); push(expected.p.toByte()); run<RTIInstruction>(AddressingMode::IMP, 6, expected); } TEST_F(InstructionTestFixture, EORImmediateTest) { load(0xFF00, {0xff}); registers.a = 0x7f; auto expected = registers; expected.pc += 2; expected.a = 0x80; expected.p.n = true; run<EORInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {0xff}); registers.a = 0xff; expected = registers; expected.pc += 2; expected.a = 0; expected.p.n = false; expected.p.z = true; run<EORInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, EORZeroPageTest) { load(0xFF00, {0xf0}); bus->write(0xf0, 0xff); registers.a = 0x7f; auto expected = registers; expected.pc += 2; expected.a = 0x80; expected.p.n = true; run<EORInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0xaa}); bus->write(0xaa, 0xff); registers.a = 0xff; expected = registers; expected.pc += 2; expected.a = 0; expected.p.n = false; expected.p.z = true; run<EORInstruction>(AddressingMode::ZP, 3, expected); } TEST_F(InstructionTestFixture, EORZeroPageXTest) { load(0xFF00, {0xf0}); bus->write(0xf1, 0xfe); registers.a = 0x7f; registers.x = 0x01; // added to the address auto expected = registers; expected.pc += 2; expected.a = 0x81; expected.p.n = true; run<EORInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0xff}); bus->write(0x01, 0xaa); registers.x = 0x02; registers.a = 0xff; expected = registers; expected.pc += 2; expected.a = 0x55; expected.p.n = false; expected.p.z = false; run<EORInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0xff}); bus->write(0x02, 0x0f); registers.x = 0x03; registers.a = 0x0f; expected = registers; expected.pc += 2; expected.a = 0x00; expected.p.n = false; expected.p.z = true; run<EORInstruction>(AddressingMode::ZPX, 4, expected); } TEST_F(InstructionTestFixture, EORAbsoluteTest) { load(0xFF00, {0xef, 0xbe}); bus->write(0xbeef, 0x80); registers.a = 0x01; auto expected = registers; expected.pc += 3; expected.a = 0x81; expected.p.n = true; run<EORInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0x0d, 0xd0}); bus->write(0xd00d, 0x00); registers.a = 0x00; expected = registers; expected.pc += 3; expected.a = 0; expected.p.n = false; expected.p.z = true; run<EORInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, EORAbsoluteXTest) { load(0xFF00, {0xee, 0xbe}); bus->write(0xbeef, 0x80); registers.a = 0x01; registers.x = 0x01; auto expected = registers; expected.pc += 3; expected.a = 0x81; expected.p.n = true; run<EORInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0x0e, 0xd0}); bus->write(0xd00d, 0x00); bus->write(0x0dd0, 0xff); // to make sure this fails if the msb and lsd are swapped registers.a = 0x00; registers.x = -1; expected = registers; expected.pc += 3; expected.a = 0; expected.p.n = false; expected.p.z = true; run<EORInstruction>(AddressingMode::ABSX, 4, expected); // cross page load(0xFF00, {0x00, 0xAA}); // addr 0xAA00, -1 is 0xA9FF thus page boundary crossed bus->write(0xA9FF, 0x11); registers.a = 0x44; registers.x = -1; // addr - 1 = 0xa9ff expected = registers; expected.pc += 3; expected.a = 0x55; expected.p.z = false; run<EORInstruction>(AddressingMode::ABSX, 5, expected); // page cross + 1 tick } TEST_F(InstructionTestFixture, EORAbsoluteYTest) { load(0xFF00, {0xee, 0xbe}); bus->write(0xbeef, 0x80); registers.a = 0x01; registers.y = 0x01; auto expected = registers; expected.pc += 3; expected.a = 0x81; expected.p.n = true; run<EORInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0x0e, 0xd0}); bus->write(0xd00d, 0x00); bus->write(0x0dd0, 0xff); // to make sure this fails if the msb and lsd are swapped registers.a = 0x00; registers.y = -1; expected = registers; expected.pc += 3; expected.a = 0; expected.p.n = false; expected.p.z = true; run<EORInstruction>(AddressingMode::ABSY, 4, expected); // cross page load(0xFF00, {0x00, 0xAA}); // addr 0xAA00, -1 is 0xA9FF thus page boundary crossed bus->write(0xA9FF, 0x11); registers.a = 0x44; registers.y = -1; // addr - 1 = 0xa9ff expected = registers; expected.pc += 3; expected.a = 0x55; expected.p.z = false; run<EORInstruction>(AddressingMode::ABSY, 5, expected); // page cross + 1 tick } TEST_F(InstructionTestFixture, EORIndirectXTest) { load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0x50; bus->write(0x02, 0x05); auto expected = registers; expected.pc += 2; expected.a = 0x55; run<EORInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0x00; bus->write(0x02, 0x00); expected = registers; expected.pc += 2; expected.a = 0x00; expected.p.z = true; run<EORInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); registers.x = 0x01; registers.a = 0x01; bus->write(0x02, 0x80); expected = registers; expected.pc += 2; expected.a = 0x81; expected.p.z = false; expected.p.n = true; run<EORInstruction>(AddressingMode::IINDX, 6, expected); } TEST_F(InstructionTestFixture, EORIndirectYTest) { load(0xFF00, {0x01}); bus->write(0x01, 0x05); bus->write(0x06, 0x80); registers.a = 0x01; registers.y = 0x01; auto expected = registers; expected.pc += 2; expected.p.n = true; expected.a = 0x81; run<EORInstruction>(AddressingMode::IINDY, 5, expected); // page cross test load(0xFF00, {0x01}); bus->write(0x01, 0x05); bus->write(0xFFFF, 0x00); // wraparound registers.a = 0x00; registers.y = -6; expected = registers; expected.pc += 2; expected.p.z = true; expected.p.n = false; expected.a = 0x00; run<EORInstruction>(AddressingMode::IINDY, 6, expected); } TEST_F(InstructionTestFixture, LSRAccumulatorTest) { registers.a = 0x08; auto expected = registers; expected.pc++; expected.a >>= 1; run<LSRInstruction>(AddressingMode::ACC, 2, expected); registers.a = 0x09; expected = registers; expected.pc++; expected.a >>=1; expected.p.c = true; run<LSRInstruction>(AddressingMode::ACC, 2, expected); registers.a = 0x00; expected = registers; expected.pc++; expected.p.c = false; expected.p.z = true; run<LSRInstruction>(AddressingMode::ACC, 2, expected); registers.a = 0x01; expected = registers; expected.pc++; expected.a >>=1; expected.p.c = true; expected.p.z = true; run<LSRInstruction>(AddressingMode::ACC, 2, expected); // we don't have to test the negative flag. shifting to the right will never result in // a negative flag. if it actually does (it shouldn't) then one of the above tests will fail for us. } TEST_F(InstructionTestFixture, LSRZPTest) { load(0xFF00, {0xAB}); bus->write(0xAB, 0x08); auto expected = registers; expected.pc+= 3; run<LSRInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(bus->read(0xAB), 0x08 >> 1); load(0xFF00, {0xAB}); bus->write(0xAB, 0x09); expected = registers; expected.pc+= 3; expected.p.c = true; run<LSRInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(bus->read(0xAB), 0x09 >> 1); load(0xFF00, {0xAB}); bus->write(0xAB, 0x00); expected = registers; expected.pc+= 3; expected.p.c = false; expected.p.z = true; run<LSRInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(bus->read(0xAB), 0x00); load(0xFF00, {0xAB}); bus->write(0xAB, 0x01); expected = registers; expected.pc+= 3; expected.p.c = true; expected.p.z = true; run<LSRInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(bus->read(0xAB), 0x00); } TEST_F(InstructionTestFixture, LSRAbsTest) { load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x08); auto expected = registers; expected.pc+= 3; run<LSRInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(bus->read(0xABBA), 0x08 >> 1); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x09); expected = registers; expected.pc+= 3; expected.p.c = true; run<LSRInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(bus->read(0xABBA), 0x09 >> 1); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x00); expected = registers; expected.pc+= 3; expected.p.c = false; expected.p.z = true; run<LSRInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(bus->read(0xABBA), 0x00); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x01); expected = registers; expected.pc+= 3; expected.p.c = true; expected.p.z = true; run<LSRInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(bus->read(0xABBA), 0x00); } TEST_F(InstructionTestFixture, LSRAbsXTest) { registers.x = -1; load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 0x08); auto expected = registers; expected.pc+= 3; run<LSRInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(bus->read(0xABBA), 0x08 >> 1); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 0x09); expected = registers; expected.pc+= 3; expected.p.c = true; run<LSRInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(bus->read(0xABBA), 0x09 >> 1); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 0x00); expected = registers; expected.pc+= 3; expected.p.c = false; expected.p.z = true; run<LSRInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(bus->read(0xABBA), 0x00); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 0x01); expected = registers; expected.pc+= 3; expected.p.c = true; expected.p.z = true; run<LSRInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(bus->read(0xABBA), 0x00); } TEST_F(InstructionTestFixture, LSRZPXTest) { registers.x = -1; load(0xFF00, {0xBB}); bus->write(0xBA, 0x08); auto expected = registers; expected.pc+= 2; run<LSRInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(bus->read(0xBA), 0x08 >> 1); load(0xFF00, {0xBB}); bus->write(0xBA, 0x09); expected = registers; expected.pc+= 2; expected.p.c = true; run<LSRInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(bus->read(0xBA), 0x09 >> 1); load(0xFF00, {0xBB}); bus->write(0xBA, 0x00); expected = registers; expected.pc+= 2; expected.p.c = false; expected.p.z = true; run<LSRInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(bus->read(0xBA), 0x00); load(0xFF00, {0xBB}); bus->write(0xBA, 0x01); expected = registers; expected.pc+= 2; expected.p.c = true; expected.p.z = true; run<LSRInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(bus->read(0xBA), 0x00); } TEST_F(InstructionTestFixture, PHATest) { registers.a = 37; auto expected = registers; expected.pc++; expected.sp--; run<PHAInstruction>(AddressingMode::IMP, 3, expected); stackcmp({37}); } TEST_F(InstructionTestFixture, JMPIndirectTest) { // from http://www.obelisk.me.uk/6502/reference.html#JMP // An original 6502 has does not correctly fetch the target address if the indirect vector falls on a page boundary (e.g. $xxFF where xx is any value from $00 to $FF). // In this case fetches the LSB from $xxFF as expected but takes the MSB from $xx00. // This is fixed in some later chips like the 65SC02 so for compatibility always ensure the indirect vector is not at the end of the page. auto expected = registers; load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 0x0D); bus->write(0xABBB, 0xD0); expected.pc = 0xD00D; run<JMPInstruction>(AddressingMode::IABS, 5, expected); // quirk on 6502: if the LSB of an indirect address e.g. pointer is on the upper boundary of a page // (basically, if the LSB is 255) then (normally) the MSB would be on address 0 from the first next page. // but instead it reads address 0 from the current page. bus->write(0xAAFF, 0xEF); // lsb; bus->write(0xAA00, 0xBE); // msb; load(0xFF00, {0xFF, 0xAA}); // write pointer 0xAAFF to address 0xFF01 (simulate 0xFF00 is the current instruction) expected.pc = 0xBEEF; run<JMPInstruction>(AddressingMode::IABS, 5, expected); } TEST_F(InstructionTestFixture, JMPAbsoluteTest) { load(0xFF00, {0xBA, 0xAB}); // LSBFirst auto expected = registers; expected.pc = 0xABBA; run<JMPInstruction>(AddressingMode::ABS, 3, expected); } TEST_F(InstructionTestFixture, BVCTest) { registers.p.v = true; // do not branch if true load(0xFF00, {10}); auto expected = registers; expected.pc += 2; run<BVCInstruction>(AddressingMode::REL, 2, expected); registers.p.v = false; load(0xFF00, {10}); expected = registers; expected.pc = registers.pc + 10; run<BVCInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {static_cast<uint8_t>(-1)}); expected = registers; expected.pc = registers.pc -1; run<BVCInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, CLITest) { auto expected = registers; registers.p.i = true; expected.p.i = false; expected.pc++; run<CLIInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, RTSTest) { auto expected = registers; expected.pc = 0xABBA -1; push(hi(0xABBA)); push(lo(0xABBA)); run<RTSInstruction>(AddressingMode::IMP, 6, expected); } TEST_F(InstructionTestFixture, ADCTest) { // the implementation of all ADC opcodes is the same. reading method is standardized. // It's a lot of work, maybe we'll add those tests at some point load(0xFF00, {0x01}); registers.a = -1; auto expected = registers; expected.a = 0; expected.pc += 2; expected.p.z = true; expected.p.c = true; run<ADCInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {0xFF}); registers.a = -127; expected = registers; expected.pc += 2; expected.p.z = false; expected.p.n = true; run<ADCInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, SBCTest) { // same story as ADCTest load(0xFF00, {0x01}); registers.a = 1; auto expected = registers; expected.a = 0xff; expected.pc += 2; expected.p.n = true; expected.p.c = true; run<SBCInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {0xFF}); registers.a = 127; expected = registers; expected.pc += 2; expected.a = 0x80; expected.p.z = false; expected.p.n = true; expected.p.v = true; run<SBCInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, PLATest) { auto expected = registers; expected.a = 15; expected.pc++; push(15); run<PLAInstruction>(AddressingMode::IMP, 4, expected); expected.a = 128; expected.p.n = true; expected.pc++; push(128); run<PLAInstruction>(AddressingMode::IMP, 4, expected); expected.p.n = false; expected.p.z = true; expected.a = 0; expected.pc++; push(0); run<PLAInstruction>(AddressingMode::IMP, 4, expected); } TEST_F(InstructionTestFixture, SEITest) { auto expected = registers; registers.p.i = false; expected.p.i = true; expected.pc++; run<SEIInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, STAZeroPageTest) { STAInstruction instruction(*handler); STNZPTest(instruction, registers.a); } TEST_F(InstructionTestFixture, STAAbsoluteTest) { STAInstruction instruction(*handler); STNABSTest(instruction, registers.a); } TEST_F(InstructionTestFixture, STAZeroPageXTest) { STAInstruction instruction(*handler); STNZPXYTest(instruction, registers.a, reg::x); } TEST_F(InstructionTestFixture, STAIndirectXTest) { load(0xFF00, {0x02}); registers.x = -1; registers.a = 0xB0; auto expected = registers; expected.pc += 2; run<STAInstruction>(AddressingMode::IINDX, 6, expected); EXPECT_EQ(0xB0, bus->read(0x01)); } TEST_F(InstructionTestFixture, STAIndirectYTest) { load(0xFF00, {0x02}); bus->write(0x02, 0x05); registers.y = -1; registers.a = 0xB0; auto expected = registers; expected.pc += 2; run<STAInstruction>(AddressingMode::IINDY, 6, expected); EXPECT_EQ(0xB0, bus->read(0x04)); } TEST_F(InstructionTestFixture, STAAbsoluteYTest) { STAInstruction instruction(*handler); STNABSXYTest(instruction, registers.a, reg::y); } TEST_F(InstructionTestFixture, STAAbsoluteXTest) { STAInstruction instruction(*handler); STNABSXYTest(instruction, registers.a, reg::x); } TEST_F(InstructionTestFixture, STYZeroPageTest) { STYInstruction instruction(*handler); STNZPTest(instruction, registers.y); } TEST_F(InstructionTestFixture, STYAbsoluteTest) { STYInstruction instruction(*handler); STNABSTest(instruction, registers.y); } TEST_F(InstructionTestFixture, STYZeroPageXTest) { STYInstruction instruction(*handler); STNZPXYTest(instruction, registers.y, reg::x); } TEST_F(InstructionTestFixture, STXZeroPageTest) { STXInstruction instruction(*handler); STNZPTest(instruction, registers.x); } TEST_F(InstructionTestFixture, STXAbsoluteTest) { STXInstruction instruction(*handler); STNABSTest(instruction, registers.x); } TEST_F(InstructionTestFixture, STXZeroPageYTest) { STXInstruction instruction(*handler); STNZPXYTest(instruction, registers.x, reg::y); } TEST_F(InstructionTestFixture, DEYTest) { registers.y = 15; auto expected = registers; expected.y--; expected.pc++; run<DEYInstruction>(AddressingMode::IMP, 2, expected); registers.y = 1; expected.y = 0; expected.p.z = true; expected.p.n = false; expected.pc++; run<DEYInstruction>(AddressingMode::IMP, 2, expected); expected.p.z = false; expected.p.n = true; expected.y = 255; expected.pc++; run<DEYInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, TXATest) { registers.x = 15; auto expected = registers; expected.a = registers.x; expected.pc++; run<TXAInstruction>(AddressingMode::IMP, 2, expected); registers.x = 0; expected = registers; expected.pc++; expected.a = registers.x; expected.p.z = true; run<TXAInstruction>(AddressingMode::IMP, 2, expected); registers.x = 128; expected = registers; expected.pc++; expected.a = registers.x; expected.p.z = false; expected.p.n = true; run<TXAInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, TYATest) { registers.y = 15; auto expected = registers; expected.a = registers.y; expected.pc++; run<TYAInstruction>(AddressingMode::IMP, 2, expected); registers.y = 0; expected = registers; expected.pc++; expected.a = registers.y; expected.p.z = true; run<TYAInstruction>(AddressingMode::IMP, 2, expected); registers.y = 128; expected = registers; expected.pc++; expected.a = registers.y; expected.p.z = false; expected.p.n = true; run<TYAInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, TXSTest) { registers.x = 15; auto expected = registers; expected.pc++; expected.sp = registers.x; run<TXSInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, LDYImmediateTest) { LDYInstruction instruction(*handler); reg ireg = reg::y; LDNImmediateTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDYZeroPageTest) { LDYInstruction instruction(*handler); reg ireg = reg::y; LDNZeroPageTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDYZeroPageXTest) { LDYInstruction instruction(*handler); reg ireg = reg::y; LDNZeroPageXYTest(instruction, ireg, reg::x); } TEST_F(InstructionTestFixture, LDYAbsoluteTest) { LDYInstruction instruction(*handler); reg ireg = reg::y; LDNAbsoluteTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDYAbsoluteXTest) { LDYInstruction instruction(*handler); reg ireg = reg::y; LDNAbsoluteXYTest(instruction, ireg, reg::x); } TEST_F(InstructionTestFixture, LDAIndirectXTest) { load(0xFF00, {0x01}); bus->write(0x02, 0x80); registers.x = 0x01; // 1 + 1 = 2, load bus->read(2) into registers.a auto expected = registers; expected.a = 0x80; expected.p.n = true; expected.pc += 2; run<LDAInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x01}); bus->write(0x02, 0x00); expected = registers; expected.a = 0x00; expected.p.n = false; expected.p.z = true; expected.pc += 2; run<LDAInstruction>(AddressingMode::IINDX, 6, expected); } TEST_F(InstructionTestFixture, LDAIndirectYTest) { load(0xFF00, {0x01}); bus->write(0x01,0x02); bus->write(0xFFFF, 0x80); registers.y = -3; // 0 - 1 = 0xffff (16bit addressing, 2 - 3 = '-1' aka 0xffff.) auto expected = registers; expected.a = 0x80; expected.p.n = true; expected.pc += 2; run<LDAInstruction>(AddressingMode::IINDY, 6, expected); // page crossed load(0xFF00, {0x01}); registers.y = 1; expected = registers; bus->write(0x01, 0x05); bus->write(0x06, 0x00); registers.a = 0x01; // addr 5 + 1 expected.a = 0x00; expected.p.n = false; expected.p.z = true; expected.pc += 2; run<LDAInstruction>(AddressingMode::IINDY, 5, expected); } TEST_F(InstructionTestFixture, LDAZeroPageTest) { LDAInstruction instruction(*handler); reg ireg = reg::a; LDNZeroPageTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDAZeroPageXTest) { LDAInstruction instruction(*handler); reg ireg = reg::a; LDNZeroPageXYTest(instruction, ireg, reg::x); } TEST_F(InstructionTestFixture, LDAImmediateTest) { LDAInstruction instruction(*handler); reg ireg = reg::a; LDNImmediateTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDAAbsoluteTest) { LDAInstruction instruction(*handler); reg ireg = reg::a; LDNAbsoluteTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDAAbsoluteXTest) { LDAInstruction instruction(*handler); reg ireg = reg::a; LDNAbsoluteXYTest(instruction, ireg, reg::x); } TEST_F(InstructionTestFixture, LDAAbsoluteYTest) { LDAInstruction instruction(*handler); reg ireg = reg::a; LDNAbsoluteXYTest(instruction, ireg, reg::y); } TEST_F(InstructionTestFixture, LDXImmediateTest) { LDXInstruction instruction(*handler); reg ireg = reg::x; LDNImmediateTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDXZeroPageTest) { LDXInstruction instruction(*handler); reg ireg = reg::x; LDNZeroPageTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDXZeroPageYTest) { LDXInstruction instruction(*handler); reg ireg = reg::x; LDNZeroPageXYTest(instruction, ireg, reg::y); } TEST_F(InstructionTestFixture, LDXAbsoluteTest) { LDXInstruction instruction(*handler); reg ireg = reg::x; LDNAbsoluteTest(instruction, ireg); } TEST_F(InstructionTestFixture, LDXAbsoluteYTest) { LDXInstruction instruction(*handler); reg ireg = reg::x; LDNAbsoluteXYTest(instruction, ireg, reg::y); } TEST_F(InstructionTestFixture, TAYTest) { registers.a = 15; auto expected = registers; expected.pc++; expected.y = expected.a; run<TAYInstruction>(AddressingMode::IMP, 2, expected); registers.a = 255; expected = registers; expected.pc++; expected.a = 255; expected.y = 255; expected.p.n = true; run<TAYInstruction>(AddressingMode::IMP, 2, expected); registers.a = 0; expected = registers; expected.pc++; expected.y = 0; expected.p.n = false; expected.p.z = true; run<TAYInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, TAXTest) { registers.a = 15; auto expected = registers; expected.pc++; expected.x = expected.a; run<TAXInstruction>(AddressingMode::IMP, 2, expected); registers.a = 255; expected = registers; expected.pc++; expected.a = 255; expected.x = 255; expected.p.n = true; run<TAXInstruction>(AddressingMode::IMP, 2, expected); registers.a = 0; expected = registers; expected.pc++; expected.x = 0; expected.p.n = false; expected.p.z = true; run<TAXInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, CLVTest) { auto expected = registers; registers.p.v = true; expected.p.v = false; expected.pc++; run<CLVInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, TSXTest) { registers.sp = 15; auto expected = registers; expected.pc++; expected.x = registers.sp; run<TSXInstruction>(AddressingMode::IMP, 2, expected); registers.sp = 0; expected = registers; expected.pc++; expected.x = registers.sp; expected.p.z = true; run<TSXInstruction>(AddressingMode::IMP, 2, expected); registers.sp = 128; expected = registers; expected.pc++; expected.x = registers.sp; expected.p.n = true; expected.p.z = false; run<TSXInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, CPXImmediateTest) { load(0xFF00, {16}); registers.x = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CPXInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {16}); registers.x = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CPXInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {17}); registers.x = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CPXInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, CPXZeroPageTest) { load(0xFF00, {0x01}); bus->write(0x01, 16); registers.x = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CPXInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x01}); bus->write(0x01, 16); registers.x = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CPXInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x01}); bus->write(0x01, 17); registers.x = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CPXInstruction>(AddressingMode::ZP, 3, expected); } TEST_F(InstructionTestFixture, CPXAbsoluteTest) { load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 16); registers.x = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 3; run<CPXInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 16); registers.x = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 3; run<CPXInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 17); registers.x = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CPXInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, CPYImmediateTest) { load(0xFF00, {16}); registers.y = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CPYInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {16}); registers.y = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CPYInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {17}); registers.y = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CPYInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, CPYZeroPageTest) { load(0xFF00, {0x01}); bus->write(0x01, 16); registers.y = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CPYInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x01}); bus->write(0x01, 16); registers.y = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CPYInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x01}); bus->write(0x01, 17); registers.y = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CPYInstruction>(AddressingMode::ZP, 3, expected); } TEST_F(InstructionTestFixture, CPYAbsoluteTest) { load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 16); registers.y = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 3; run<CPYInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 16); registers.y = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 3; run<CPYInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 17); registers.y = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CPYInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, CMPImmediateTest) { load(0xFF00, {16}); registers.a = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {16}); registers.a = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IMM, 2, expected); load(0xFF00, {17}); registers.a = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IMM, 2, expected); } TEST_F(InstructionTestFixture, CMPZeroPageTest) { load(0xFF00, {0x01}); bus->write(0x01, 16); registers.a = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x01}); bus->write(0x01, 16); registers.a = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::ZP, 3, expected); load(0xFF00, {0x01}); bus->write(0x01, 17); registers.a = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::ZP, 3, expected); } TEST_F(InstructionTestFixture, CMPAbsoluteTest) { load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 16); registers.a = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 16); registers.a = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABS, 4, expected); load(0xFF00, {0xBA, 0xAB}); bus->write(0xABBA, 17); registers.a = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABS, 4, expected); } TEST_F(InstructionTestFixture, CMPZeroPageXTest) { load(0xFF00, {0x02}); bus->write(0x01, 16); registers.x = -1; registers.a = 16; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0x02}); bus->write(0x01, 16); registers.x = -1; registers.a = 17; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::ZPX, 4, expected); load(0xFF00, {0x02}); bus->write(0x01, 17); registers.x = -1; registers.a = 16; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::ZPX, 4, expected); } TEST_F(InstructionTestFixture, CMPAbsoluteXTest) { load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 16); registers.a = 16; registers.x = -1; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 16); registers.a = 17; registers.x = -1; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 17); registers.a = 16; registers.x = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSX, 4, expected); load(0xFF00, {0x00, 0xAB}); bus->write(0xAAFF, 17); registers.a = 16; registers.x = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSX, 5, expected); } TEST_F(InstructionTestFixture, CMPAbsoluteYTest) { load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 16); registers.a = 16; registers.y = -1; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 16); registers.a = 17; registers.y = -1; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0xBB, 0xAB}); bus->write(0xABBA, 17); registers.a = 16; registers.y = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSY, 4, expected); load(0xFF00, {0x00, 0xAB}); bus->write(0xAAFF, 17); registers.a = 16; registers.y = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 3; run<CMPInstruction>(AddressingMode::ABSY, 5, expected); } TEST_F(InstructionTestFixture, CMPIndirectXTest) { load(0xFF00, {0x02}); bus->write(0x01, 16); registers.a = 16; registers.x = -1; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x02}); bus->write(0x01, 16); registers.a = 17; registers.x = -1; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x02}); bus->write(0x01, 17); registers.a = 16; registers.x = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDX, 6, expected); load(0xFF00, {0x00}); bus->write(0xFF, 17); // wrap-around within the same page registers.a = 16; registers.x = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDX, 6, expected); } TEST_F(InstructionTestFixture, CMPIndirectYTest) { load(0xFF00, {0x02}); bus->write(0x02, 0x04); bus->write(0x03, 16); registers.a = 16; registers.y = -1; auto expected = registers; expected.p.z = true; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDY, 5, expected); load(0xFF00, {0x02}); bus->write(0x02, 0x04); bus->write(0x03, 16); registers.a = 17; registers.y = -1; expected = registers; expected.p.z = false; expected.p.c = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDY, 5, expected); load(0xFF00, {0x02}); bus->write(0x02, 0x04); bus->write(0x03, 17); registers.a = 16; registers.y = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDY, 5, expected); load(0xFF00, {0x10}); bus->write(0x010, 0x00); bus->write(0xFFFF, 17); registers.a = 16; registers.y = -1; expected = registers; expected.p.z = false; expected.p.c = false; expected.p.n = true; expected.pc += 2; run<CMPInstruction>(AddressingMode::IINDY, 6, expected); } TEST_F(InstructionTestFixture, DECZeroPageTest) { load(0xFF00, {0x01}); bus->write(0x01, 0x00); auto expected = registers; expected.p.n = true; expected.pc += 2; run<DECInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0xff, bus->read(0x01)); load(0xFF00, {0x01}); bus->write(0x01, 0x1); expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 2; run<DECInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x00, bus->read(0x01)); } TEST_F(InstructionTestFixture, DECZeroPageXTest) { load(0xFF00, {0x02}); bus->write(0x01, 0x00); registers.x = -1; auto expected = registers; expected.p.n = true; expected.pc += 2; run<DECInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0xff, bus->read(0x01)); load(0xFF00, {0x02}); bus->write(0x01, 0x1); registers.x = -1; expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 2; run<DECInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x00, bus->read(0x01)); } TEST_F(InstructionTestFixture, DECAbsoluteTest) { load(0xFF00, {0x01, 0x0B}); bus->write(0x0B01, 0x00); auto expected = registers; expected.p.n = true; expected.pc += 3; run<DECInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0xff, bus->read(0x0B01)); load(0xFF00, {0x01, 0x0B}); bus->write(0x0B01, 0x1); expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 3; run<DECInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x00, bus->read(0x0B01)); } TEST_F(InstructionTestFixture, DECAbsoluteXTest) { load(0xFF00, {0x02, 0x0B}); bus->write(0x0B01, 00); registers.x = -1; auto expected = registers; expected.p.n = true; expected.pc += 3; run<DECInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0xff, bus->read(0x0B01)); load(0xFF00, {0x02, 0x0B}); bus->write(0x0B01, 0x01); registers.x = -1; expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 3; run<DECInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x00, bus->read(0x0B01)); } TEST_F(InstructionTestFixture, INYTest) { registers.y = 15; // test normal behaviour. x should be incremented auto expected = registers; expected.y++; expected.pc++; run<INYInstruction>(AddressingMode::IMP, 2, expected); // negative flag should be set if bit 7 is high registers.y = 127; expected.y = 128; expected.p.n = true; expected.pc++; run<INYInstruction>(AddressingMode::IMP, 2, expected); // zero flag should be set if the entire value of x is zero registers.y = 255; expected.y = 0; expected.p.n = false; expected.p.z = true; expected.pc++; run<INYInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, DEXTest) { registers.x = 15; auto expected = registers; expected.x--; expected.pc++; run<DEXInstruction>(AddressingMode::IMP, 2, expected); registers.x = 1; expected.x = 0; expected.p.z = true; expected.p.n = false; expected.pc++; run<DEXInstruction>(AddressingMode::IMP, 2, expected); expected.p.z = false; expected.p.n = true; expected.x = 255; expected.pc++; run<DEXInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, BEQTest) { load(0xFF00, {5}); auto expected = registers; expected.p.z = false; expected.pc += 2; run<BEQInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {5}); registers.p.z = true; expected = registers; expected.pc = 0xFF05; run<BEQInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {(uint8_t)-1}); expected = registers; expected.pc = 0xFEFF; run<BEQInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, BNETest) { load(0xFF00, {5}); registers.p.z = true; auto expected = registers; expected.pc += 2; run<BNEInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {5}); registers.p.z = false; expected = registers; expected.pc = 0xFF05; run<BNEInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {(uint8_t)-1}); expected = registers; expected.pc = 0xFEFF; run<BNEInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, BCCTest) { load(0xFF00, {5}); registers.p.c = true; auto expected = registers; expected.pc += 2; run<BCCInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {5}); registers.p.c = false; expected = registers; expected.pc = 0xFF05; run<BCCInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {(uint8_t)-1}); expected = registers; expected.pc = 0xFEFF; run<BCCInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, BCSTest) { load(0xFF00, {5}); auto expected = registers; expected.p.c = false; expected.pc += 2; run<BCSInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {5}); registers.p.c = true; expected = registers; expected.pc = 0xFF05; run<BCSInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {(uint8_t)-1}); expected = registers; expected.pc = 0xFEFF; run<BCSInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, BVSTest) { load(0xFF00, {5}); registers.p.v = false; auto expected = registers; expected.pc += 2; run<BVSInstruction>(AddressingMode::REL, 2, expected); load(0xFF00, {5}); registers.p.v = true; expected = registers; expected.pc = 0xFF05; run<BVSInstruction>(AddressingMode::REL, 3, expected); load(0xFF00, {(uint8_t)-1}); expected = registers; expected.pc = 0xFEFF; run<BVSInstruction>(AddressingMode::REL, 4, expected); } TEST_F(InstructionTestFixture, INCZeroPageTest) { load(0xFF00, {0x01}); bus->write(0x01, 0x7f); auto expected = registers; expected.p.n = true; expected.pc += 2; run<INCInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x80, bus->read(0x01)); load(0xFF00, {0x01}); bus->write(0x01, 0xff); expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 2; run<INCInstruction>(AddressingMode::ZP, 5, expected); EXPECT_EQ(0x00, bus->read(0x01)); } TEST_F(InstructionTestFixture, INCZeroPageXTest) { load(0xFF00, {0x02}); bus->write(0x01, 0x7f); registers.x = -1; auto expected = registers; expected.p.n = true; expected.pc += 2; run<INCInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x80, bus->read(0x01)); load(0xFF00, {0x02}); bus->write(0x01, 0xff); registers.x = -1; expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 2; run<INCInstruction>(AddressingMode::ZPX, 6, expected); EXPECT_EQ(0x00, bus->read(0x01)); } TEST_F(InstructionTestFixture, INCAbsoluteTest) { load(0xFF00, {0x01, 0x0B}); bus->write(0x0B01, 0x7f); auto expected = registers; expected.p.n = true; expected.pc += 3; run<INCInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x80, bus->read(0x0B01)); load(0xFF00, {0x01, 0x0B}); bus->write(0x0B01, 0xff); expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 3; run<INCInstruction>(AddressingMode::ABS, 6, expected); EXPECT_EQ(0x00, bus->read(0x0B01)); } TEST_F(InstructionTestFixture, INCAbsoluteXTest) { load(0xFF00, {0x02, 0x0B}); bus->write(0x0B01, 0x7f); registers.x = -1; auto expected = registers; expected.p.n = true; expected.pc += 3; run<INCInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x80, bus->read(0x0B01)); load(0xFF00, {0x02, 0x0B}); bus->write(0x0B01, 0xff); registers.x = -1; expected = registers; expected.p.n = false; expected.p.z = true; expected.pc += 3; run<INCInstruction>(AddressingMode::ABSX, 7, expected); EXPECT_EQ(0x00, bus->read(0x0B01)); } TEST_F(InstructionTestFixture, INXTest) { registers.x = 15; // test normal behaviour. x should be incremented auto expected = registers; expected.x++; expected.pc++; run<INXInstruction>(AddressingMode::IMP, 2, expected); // negative flag should be set if bit 7 is high registers.x = 127; expected.x = 128; expected.p.n = true; expected.pc++; run<INXInstruction>(AddressingMode::IMP, 2, expected); // zero flag should be set if the entire value of x is zero registers.x = 255; expected.x = 0; expected.p.n = false; expected.p.z = true; expected.pc++; run<INXInstruction>(AddressingMode::IMP, 2, expected); } TEST_F(InstructionTestFixture, SEDTest) { auto expected = registers; expected.p.d = true; expected.pc++; run<SEDInstruction>(AddressingMode::IMP, 2, expected); expected.p.d = true; expected.pc++; run<SEDInstruction>(AddressingMode::IMP, 2, expected); }
26.537998
201
0.624386
[ "vector" ]
add1aad0cd7f3c417d54c275b5a8597d8fc39569
983
cc
C++
cpp/leetcode/1310.xor-queries-of-a-subarray.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
3
2021-03-03T13:18:23.000Z
2022-02-09T07:49:24.000Z
cpp/leetcode/1310.xor-queries-of-a-subarray.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
null
null
null
cpp/leetcode/1310.xor-queries-of-a-subarray.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
1
2021-03-29T15:21:42.000Z
2021-03-29T15:21:42.000Z
#include <gtest/gtest.h> #include <vector> namespace { class Solution { public: std::vector<int> xorQueries(const std::vector<int>& arr, const std::vector<std::vector<int>>& queries) { std::vector<int> preprocess; int num = 0; for (auto a : arr) { num ^= a; preprocess.push_back(num); } std::vector<int> ret; for (auto& pair : queries) { int l = pair[0], r = pair[1]; if (l == 0) { ret.push_back(preprocess[r]); } else { ret.push_back(preprocess[r] ^ preprocess[l - 1]); } } return ret; } }; } // namespace TEST(Leetcode, xor_queries_of_a_subarray) { Solution s; { std::vector<int> exp = {2, 7, 14, 8}; EXPECT_EQ(exp, s.xorQueries({1, 3, 4, 8}, {{0, 1}, {1, 2}, {0, 3}, {3, 3}})); } { std::vector<int> exp = {8, 0, 4, 4}; EXPECT_EQ(exp, s.xorQueries({4, 8, 2, 10}, {{2, 3}, {1, 3}, {0, 0}, {0, 3}})); } }
22.340909
77
0.496439
[ "vector" ]
add2f67aef6aad4679df04a4c8da471f6131e8d1
2,705
cxx
C++
Tracing/SuperEllipsoidTracer/XMLtest.cxx
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
Tracing/SuperEllipsoidTracer/XMLtest.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
Tracing/SuperEllipsoidTracer/XMLtest.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
// vector::begin #include <iostream> #include <vector> #include "tinyxml.h" //using namespace std; int main () { //std::vector<int> myvector; // for (int i=1; i<=5; i++) myvector.push_back(i); // std::vector<int>::iterator it; // std::cout << "myvector contains:"; // for ( it=myvector.begin() ; it < myvector.end(); it++ ) // std::cout << " " << *it; // std::cout << std::endl; // return 0; TiXmlDocument doc("test.xml"); if (!doc.LoadFile()) { return false; } TiXmlElement* root = doc.FirstChildElement( "SuperElliposoidTracing" ); while ( root ) { TiXmlAttribute* rAttrib = root->FirstAttribute(); while (rAttrib) { if (!strcmp(rAttrib->Name(),"InputFileName")) { std::cout << "Input file name: " << rAttrib->Value() <<std::endl; } else if (!strcmp(rAttrib->Name(),"OutputFileName")) { std::cout << "Output file name: " << rAttrib->Value() <<std::endl; } rAttrib=rAttrib->Next(); } TiXmlElement* param = root->FirstChildElement( "Parameter" ); while ( param ) { TiXmlAttribute* pAttrib = param->FirstAttribute(); if (pAttrib){ if (!strcmp(pAttrib->Name(),"GridSpacing")) { std::cout << "GridSpacing: " << pAttrib->Value() << std::endl; } else if (!strcmp(pAttrib->Name(),"StepRatio")) { std::cout << "StepRatio: " << pAttrib->Value() << std::endl; } else if (!strcmp(pAttrib->Name(),"AspectRatio")) { std::cout << "AspectRatio: " << pAttrib->Value() << std::endl; } else if (!strcmp(pAttrib->Name(),"THRESHOLD")) { std::cout << "THRESHOLD: " << pAttrib->Value() << std::endl; } else if(!strcmp(pAttrib->Name(),"minContrast")) { std::cout << "minContrast: " << pAttrib->Value() << std::endl; } else if(!strcmp(pAttrib->Name(),"MaximumVesselWidth")) { std::cout << "MaximumVesselWidth: " << pAttrib->Value() << std::endl; } else if(!strcmp(pAttrib->Name(),"MinimumVesselWidth")) { std::cout << "MinimumVesselWidth: " << pAttrib->Value() << std::endl; } else if(!strcmp(pAttrib->Name(),"MinimumVesselLength")) { std::cout << "MinimumVesselLength: " << pAttrib->Value() << std::endl; } else if(!strcmp(pAttrib->Name(),"StartTHRESH")) { std::cout << "StartTHRESH: " << pAttrib->Value() << std::endl; } else if(!strcmp(pAttrib->Name(),"StartIterations")) { int temp = -1; if (pAttrib->QueryIntValue(&temp)==TIXML_SUCCESS) n->ID = temp; std::cout << "StartIterations: " << pAttrib->Value() << std::endl; } else { std::cout << "UNRECOGNIZED TAG: " << pAttrib->Value() << std::endl; } } param = param->NextSiblingElement(); } root = root->NextSiblingElement(); } }
31.453488
76
0.582255
[ "vector" ]
add72f114e0d6a6c11fcac3263db9cf8949c4cc8
4,447
hpp
C++
dakota-6.3.0.Windows.x86/include/Teuchos_XMLParameterListWriter.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/Teuchos_XMLParameterListWriter.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/Teuchos_XMLParameterListWriter.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
// @HEADER // *********************************************************************** // // Teuchos: Common Tools Package // Copyright (2004) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // 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 Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Michael A. Heroux (maherou@sandia.gov) // // *********************************************************************** // @HEADER #ifndef Teuchos_XMLPARAMETERLISTWRITER_H #define Teuchos_XMLPARAMETERLISTWRITER_H /*! \file Teuchos_XMLParameterListWriter.hpp * * \brief Writes a ParameterList to an XML object */ #include "Teuchos_ParameterList.hpp" #include "Teuchos_XMLObject.hpp" #include "Teuchos_Utils.hpp" #include "Teuchos_DependencySheet.hpp" #include "Teuchos_ValidatorMaps.hpp" namespace Teuchos { /** \ingroup XML * \brief Writes a ParameterList to an XML object */ class TEUCHOS_LIB_DLL_EXPORT XMLParameterListWriter { public: /** \name Public Types */ //@{ /** \brief . */ typedef std::map<RCP<const ParameterEntry>, ParameterEntry::ParameterEntryID, RCPConstComp> EntryIDsMap; //@} //! @name Constructors //@{ /** Construct a writer */ XMLParameterListWriter(); //@} /** Write the given list to an XML object */ XMLObject toXML( const ParameterList& p, RCP<const DependencySheet> depSheet = null) const; /** \brief . */ static const std::string& getParameterListTagName(){ static const std::string parameterListTagName = "ParameterList"; return parameterListTagName; } /** \brief . */ static const std::string& getNameAttributeName(){ static const std::string nameAttributeName = "name"; return nameAttributeName; } /** \brief . */ static const std::string& getValidatorsTagName(){ static const std::string validatorsTagName = "Validators"; return validatorsTagName; } /** \brief . */ static const std::string& getDependenciesTagName(){ static const std::string dependenciesTagName = "Dependencies"; return dependenciesTagName; } private: /** \brief Write the given list to an XML object. */ XMLObject convertParameterList( const ParameterList& p, ParameterEntry::ParameterEntryID& idCounter, EntryIDsMap& entryIDsMap, const ValidatortoIDMap& validatorIDsMap) const; /** \brief Convert all the validators. */ XMLObject convertValidators( const ParameterList& p, ValidatortoIDMap& validatorIDsMap) const; /** \brief Convert all the dependencies. */ XMLObject convertDependencies( RCP<const DependencySheet> depSheet, const EntryIDsMap& entryIDsMap, ValidatortoIDMap& validatorIDsMap) const; /** \brief Builds up the list of validators to be converted */ void buildInitialValidatorMap( const ParameterList& p, ValidatortoIDMap& validatorIDsMap) const; }; } // namespace teuchos #endif
31.097902
74
0.703171
[ "object" ]
add926ea6feeecf3c7c066dde80c8585b98963f8
3,707
cpp
C++
unit_tests/geometry/line_strip.cpp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
null
null
null
unit_tests/geometry/line_strip.cpp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
3
2020-10-26T18:45:47.000Z
2020-10-26T18:46:06.000Z
unit_tests/geometry/line_strip.cpp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
null
null
null
#include <boost/assign/std/vector.hpp> #include <cradle/geometry/line_strip.hpp> #include <cradle/test.hpp> double const tolerance = 0.00001; using namespace boost::assign; using namespace cradle; TEST_CASE("actual_poly_test") { std::vector<vertex2> vertices; vertices += make_vector<double>(-1, 0), make_vector<double>(1, 0), make_vector<double>(0, 1); polygon2 original; initialize(&original.vertices, vertices); std::vector<line_strip> strips; std::vector<line_segment<2, double>> segments; for (polygon2_edge_view ev(original); !ev.done(); ev.advance()) segments.push_back(line_segment<2, double>(ev.p0(), ev.p1())); strips = connect_line_segments(segments, tolerance); REQUIRE(is_polygon(strips, tolerance)); REQUIRE(as_polygon(strips, tolerance)); optional<polygon2> poly; as_polygon(&poly, strips, tolerance); REQUIRE(poly); REQUIRE(almost_equal(original, poly.get())); } TEST_CASE("not_connected_test") { std::vector<vertex2> vertices; vertices += make_vector<double>(-1, 0), make_vector<double>(1, 0), make_vector<double>(0, 1); polygon2 original; initialize(&original.vertices, vertices); std::vector<line_strip> strips; std::vector<line_segment<2, double>> segments; polygon2_edge_view ev(original); ev.advance(); for (; !ev.done(); ev.advance()) segments.push_back(line_segment<2, double>(ev.p0(), ev.p1())); strips = connect_line_segments(segments, tolerance); REQUIRE(!is_polygon(strips, tolerance)); REQUIRE(!as_polygon(strips, tolerance)); optional<polygon2> poly; as_polygon(&poly, strips, tolerance); REQUIRE(!poly); } TEST_CASE("extraneous_segments_test") { std::vector<vertex2> vertices; vertices += make_vector<double>(-1, 0), make_vector<double>(1, 0), make_vector<double>(0, 1); polygon2 original; initialize(&original.vertices, vertices); std::vector<line_strip> strips; std::vector<line_segment<2, double>> segments; for (polygon2_edge_view ev(original); !ev.done(); ev.advance()) segments.push_back(line_segment<2, double>(ev.p0(), ev.p1())); segments.push_back(line_segment<2, double>( make_vector<double>(2, 0), make_vector<double>(2, 1))); strips = connect_line_segments(segments, tolerance); REQUIRE(!is_polygon(strips, tolerance)); REQUIRE(!as_polygon(strips, tolerance)); optional<polygon2> poly; as_polygon(&poly, strips, tolerance); REQUIRE(!poly); } TEST_CASE("multiple_polys_test") { polygon2 original; { std::vector<vertex2> vertices; vertices += make_vector<double>(-1, 0), make_vector<double>(1, 0), make_vector<double>(0, 1); initialize(&original.vertices, vertices); } std::vector<line_strip> strips; std::vector<line_segment<2, double>> segments; for (polygon2_edge_view ev(original); !ev.done(); ev.advance()) segments.push_back(line_segment<2, double>(ev.p0(), ev.p1())); strips = connect_line_segments(segments, tolerance); polygon2 other; { std::vector<vertex2> vertices; vertices += make_vector<double>(2, 0), make_vector<double>(3, 0), make_vector<double>(0, 1); initialize(&other.vertices, vertices); } for (polygon2_edge_view ev(other); !ev.done(); ev.advance()) segments.push_back(line_segment<2, double>(ev.p0(), ev.p1())); strips = connect_line_segments(segments, tolerance); REQUIRE(!is_polygon(strips, tolerance)); REQUIRE(!as_polygon(strips, tolerance)); optional<polygon2> poly; as_polygon(&poly, strips, tolerance); REQUIRE(!poly); }
29.188976
74
0.669274
[ "geometry", "vector" ]
ade4b43730386da7a7c70fa6c788fcc02269578f
10,947
hpp
C++
src/DeBruijnGraph.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
267
2018-07-31T16:12:24.000Z
2022-03-29T13:57:53.000Z
src/DeBruijnGraph.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
140
2018-08-10T14:14:19.000Z
2022-02-18T22:05:05.000Z
src/DeBruijnGraph.hpp
AustinHartman/shasta
105b8e85e272247f72ced59005c88879631931c0
[ "BSD-3-Clause" ]
47
2018-09-28T18:29:37.000Z
2022-02-21T02:45:40.000Z
#if 0 // This is currently not used but left here in case it becomes useful. #ifndef SHASTA_DEBRUIJN_GRAPH_HPP #define SHASTA_DEBRUIJN_GRAPH_HPP // A general purpose templated class representing a De Bruijn graph. // Each vertex represents a sequence of k symbols occurring in // sequences of symbols. // Template arguments: // - Symbol: the symbols that the sequences are made of. // - k: the number of symbols in the sequence represented by a vertex. // - SequenceId: the type used to identify the sequences. // Boost libraries. #include <boost/graph/adjacency_list.hpp> #include <boost/graph/iteration_macros.hpp> // Standard library. #include "fstream.hpp" #include <set> #include "string.hpp" #include "utility.hpp" #include "vector.hpp" namespace shasta { template<class Symbol, uint64_t k, class SequenceId> class DeBruijnGraph; template<class Symbol, uint64_t k, class SequenceId> class DeBruijnGraphVertex; template<class Symbol, uint64_t k, class SequenceId> class DeBruijnGraphEdge; template<class Symbol, uint64_t k, class SequenceId> using DeBruijnGraphBaseClass = boost::adjacency_list< boost::listS, boost::listS, boost::bidirectionalS, DeBruijnGraphVertex<Symbol, k, SequenceId>, DeBruijnGraphEdge<Symbol, k, SequenceId> >; } template<class Symbol, uint64_t k, class SequenceId> class shasta::DeBruijnGraphVertex { public: // The sequence of k symbols represented by this vertex. using VertexSequence = array<Symbol, k>; VertexSequence vertexSequence; // The occurrences of the k symbols represented by this vertex // in the input sequences. // The second element of each pair is the position in the sequence // of the first of the k symbols. vector< pair<SequenceId, uint64_t > > occurrences; uint64_t vertexId; DeBruijnGraphVertex( const VertexSequence& vertexSequence, uint64_t vertexId) : vertexSequence(vertexSequence), vertexId(vertexId) {} }; template<class Symbol, uint64_t k, class SequenceId> class shasta::DeBruijnGraphEdge { public: // The k-1 symbols associated with this edge. // This are the last k-1 symbols of the source vertex // and also the first k-1 symbols of the target vertex. using EdgeSequence = array<Symbol, k-1>; EdgeSequence edgeSequence; DeBruijnGraphEdge(const EdgeSequence& edgeSequence) : edgeSequence(edgeSequence) {} }; template<class Symbol, uint64_t k, class SequenceId> class shasta::DeBruijnGraph : public DeBruijnGraphBaseClass<Symbol, k, SequenceId> { public: using Graph = DeBruijnGraph; using Vertex = DeBruijnGraphVertex<Symbol, k, SequenceId>; using Edge = DeBruijnGraphEdge<Symbol, k, SequenceId>; using BaseClass = DeBruijnGraphBaseClass<Symbol, k, SequenceId>; using vertex_descriptor = typename BaseClass::vertex_descriptor; using edge_descriptor = typename BaseClass::edge_descriptor; using Sequence = vector<Symbol>; using VertexSequence = array<Symbol, k>; using EdgeSequence = array<Symbol, k-1>; // The vertices, keyed by the sequence they contain. std::map<VertexSequence, vertex_descriptor> vertexMap; uint64_t nextVertexId = 0; // Add a sequence to the graph. void addSequence( SequenceId sequenceId, const Sequence& sequence) { Graph& graph = *this; // Loop over possible starting positions. for(uint64_t startPosition=0; startPosition + k <= sequence.size(); startPosition++) { // Extract the k symbols starting here. VertexSequence vertexSequence; for(uint64_t i=0; i<k; i++) { vertexSequence[i] = sequence[startPosition + i]; } // Get the corresponding vertex, creating it if necessary. vertex_descriptor v; auto it = vertexMap.find(vertexSequence); if(it == vertexMap.end()) { v = add_vertex(Vertex(vertexSequence, nextVertexId++), graph); vertexMap.insert(make_pair(vertexSequence, v)); } else { v = it->second; } // Store this occurrence of the k symbols. graph[v].occurrences.push_back(make_pair(sequenceId, startPosition)); } } void removeLowCoverageVertices(uint64_t minCoverage) { Graph& graph = *this; vector<vertex_descriptor> verticesTobeRemoved; BGL_FORALL_VERTICES_T(v, graph, Graph) { if(graph[v].occurrences.size() < minCoverage) { verticesTobeRemoved.push_back(v); } } for(const vertex_descriptor v: verticesTobeRemoved) { clear_vertex(v, graph); remove_vertex(v, graph); } } // This remove vertices with more than one occurrences of the same sequence. void removeAmbiguousVertices() { Graph& graph = *this; vector<vertex_descriptor> verticesTobeRemoved; vector<SequenceId> sequenceIds; BGL_FORALL_VERTICES_T(v, graph, Graph) { const auto& occurrences = graph[v].occurrences; sequenceIds.clear(); for(const auto& p: occurrences) { sequenceIds.push_back(p.first); } sort(sequenceIds.begin(), sequenceIds.end()); for(uint64_t i=1; i<sequenceIds.size(); i++) { if(sequenceIds[i-1] == sequenceIds[i]) { verticesTobeRemoved.push_back(v); break; } } } for(const vertex_descriptor v: verticesTobeRemoved) { clear_vertex(v, graph); remove_vertex(v, graph); } } // Create the edges of the De Bruijn graph. // This should be called after all sequences are added. void createEdges() { Graph& graph = *this; // Index the vertices by their first k-1 symbols. std::map<EdgeSequence, vector<vertex_descriptor> > vertexIndex; BGL_FORALL_VERTICES_T(v, graph, Graph) { const VertexSequence& vertexSequence = graph[v].vertexSequence; EdgeSequence edgeSequence; const auto begin = vertexSequence.begin(); const auto end = begin + (k-1); copy(begin, end, edgeSequence.begin()); vertexIndex[edgeSequence].push_back(v); } // Use the index to create the edges. BGL_FORALL_VERTICES_T(v0, graph, Graph) { const VertexSequence& vertexSequence0 = graph[v0].vertexSequence; EdgeSequence edgeSequence; const auto begin = vertexSequence0.begin() + 1; const auto end = vertexSequence0.end(); copy(begin, end, edgeSequence.begin()); for(const vertex_descriptor v1: vertexIndex[edgeSequence]) { edge_descriptor e; tie(e, ignore) = add_edge(v0, v1, Edge(edgeSequence), graph); } } } // Find sets of incompatible vertices. // A set of incompatible vertex can be described as the vertices // immediately preceding or following a branch in the graph. // In a set of incompatible vertices, at least one of the following is true: // - All vertices in the set have in-degree 1, and the same parent. // - OR: All vertices in the set have out-degree 1, and the same child. void findIncompatibleVertexSets( std::set< std::set<vertex_descriptor> >& incompatibleSets) const { const Graph& graph = *this; BGL_FORALL_VERTICES_T(v0, graph, Graph) { // Check the children. std::set<vertex_descriptor> children; if(out_degree(v0, graph) > 1) { bool ok = true; BGL_FORALL_OUTEDGES_T(v0, e, graph, Graph) { const vertex_descriptor v1 = target(e, graph); if(in_degree(v1, graph) != 1) { ok = false; break; } children.insert(v1); } if(ok and not isAmbiguous(children)) { incompatibleSets.insert(children); } } // Check the parents. std::set<vertex_descriptor> parents; if(in_degree(v0, graph) > 1) { bool ok = true; BGL_FORALL_INEDGES_T(v0, e, graph, Graph) { const vertex_descriptor v1 = source(e, graph); if(out_degree(v1, graph) != 1) { ok = false; break; } parents.insert(v1); } if(ok and not isAmbiguous(parents)) { incompatibleSets.insert(parents); } } } } // Remove true if a vertex set is ambiguous - // that is, if the same SequenceId appears more than once in // the vertices in the set. bool isAmbiguous(std::set<vertex_descriptor>& vertexSet) const { const Graph& graph = *this; std::set<SequenceId> alreadyEncountered; for(const vertex_descriptor v: vertexSet) { for(const auto& p: graph[v].occurrences) { const SequenceId sequenceId = p.first; if(alreadyEncountered.find(sequenceId) == alreadyEncountered.end()) { alreadyEncountered.insert(sequenceId); } else { // We already encountered this sequence. return true; } } } // If we get here, we never encountered a SequenceId more than once. return false; } void writeGraphviz(const string& fileName) const { const Graph& graph = *this; ofstream s(fileName); s << "digraph DeBruijnGraph {\n"; BGL_FORALL_VERTICES_T(v, graph, Graph) { s << graph[v].vertexId << "[label=\"" << graph[v].occurrences.size() << "\"];\n"; } BGL_FORALL_EDGES_T(e, graph, Graph) { const vertex_descriptor v0 = source(e, graph); const vertex_descriptor v1 = target(e, graph); s << graph[v0].vertexId << "->"; s << graph[v1].vertexId << ";\n"; } s << "}\n"; } void createVertexCoverageHistogram(vector<uint64_t>& histogram) const { const Graph& graph = *this; histogram.clear(); BGL_FORALL_VERTICES_T(v, graph, Graph) { const uint64_t coverage = graph[v].occurrences.size(); if(coverage >= histogram.size()) { histogram.resize(coverage + 1, 0); } ++histogram[coverage]; } } }; #endif #endif
30.923729
94
0.592948
[ "vector" ]
adea0779a1897cc0c88495b87ec14969edb877d2
31,895
cpp
C++
unittest/object_op_test.cpp
jackyding2679/cos-cpp-sdk-v5
037da66f54473ba9628b532df72759edb6ca7700
[ "MIT" ]
null
null
null
unittest/object_op_test.cpp
jackyding2679/cos-cpp-sdk-v5
037da66f54473ba9628b532df72759edb6ca7700
[ "MIT" ]
null
null
null
unittest/object_op_test.cpp
jackyding2679/cos-cpp-sdk-v5
037da66f54473ba9628b532df72759edb6ca7700
[ "MIT" ]
null
null
null
// Copyright (c) 2017, Tencent Inc. // All rights reserved. // // Author: sevenyou <sevenyou@tencent.com> // Created: 07/25/17 // Description: #include "gtest/gtest.h" #include "common.h" #include "cos_api.h" #include <sstream> namespace qcloud_cos { class ObjectOpTest : public testing::Test { protected: static void SetUpTestCase() { std::cout << "================SetUpTestCase Begin====================" << std::endl; m_config = new CosConfig("./config.json"); m_config->SetAccessKey(GetEnv("CPP_SDK_V5_ACCESS_KEY")); m_config->SetSecretKey(GetEnv("CPP_SDK_V5_SECRET_KEY")); m_client = new CosAPI(*m_config); m_bucket_name = "coscppsdkv5ut" + GetEnv("COS_CPP_V5_TAG") + "-" + GetEnv("CPP_SDK_V5_APPID"); m_bucket_name2 = "coscppsdkv5utcopy" + GetEnv("COS_CPP_V5_TAG") + "-" + GetEnv("CPP_SDK_V5_APPID"); { PutBucketReq req(m_bucket_name); PutBucketResp resp; CosResult result = m_client->PutBucket(req, &resp); ASSERT_TRUE(result.IsSucc()); } { PutBucketReq req(m_bucket_name2); PutBucketResp resp; CosResult result = m_client->PutBucket(req, &resp); ASSERT_TRUE(result.IsSucc()); } #if 0 // 生成一个大文件 { system("dd if=/dev/urandom of=sevenyou_1G.tmp bs=10M count=100"); } #endif std::cout << "================SetUpTestCase End====================" << std::endl; } static void TearDownTestCase() { std::cout << "================TearDownTestCase Begin====================" << std::endl; // 1. 删除所有Object { { GetBucketReq req(m_bucket_name); GetBucketResp resp; CosResult result = m_client->GetBucket(req, &resp); ASSERT_TRUE(result.IsSucc()); const std::vector<Content>& contents = resp.GetContents(); for (std::vector<Content>::const_iterator c_itr = contents.begin(); c_itr != contents.end(); ++c_itr) { const Content& content = *c_itr; DeleteObjectReq del_req(m_bucket_name, content.m_key); DeleteObjectResp del_resp; CosResult del_result = m_client->DeleteObject(del_req, &del_resp); EXPECT_TRUE(del_result.IsSucc()); if (!del_result.IsSucc()) { std::cout << "DeleteObject Failed, check object=" << content.m_key << std::endl; } } } { GetBucketReq req(m_bucket_name2); GetBucketResp resp; CosResult result = m_client->GetBucket(req, &resp); ASSERT_TRUE(result.IsSucc()); const std::vector<Content>& contents = resp.GetContents(); for (std::vector<Content>::const_iterator c_itr = contents.begin(); c_itr != contents.end(); ++c_itr) { const Content& content = *c_itr; DeleteObjectReq del_req(m_bucket_name2, content.m_key); DeleteObjectResp del_resp; CosResult del_result = m_client->DeleteObject(del_req, &del_resp); EXPECT_TRUE(del_result.IsSucc()); if (!del_result.IsSucc()) { std::cout << "DeleteObject Failed, check object=" << content.m_key << std::endl; } } } } // 2. 删除所有未complete的分块 { for (std::map<std::string, std::string>::const_iterator c_itr = m_to_be_aborted.begin(); c_itr != m_to_be_aborted.end(); ++c_itr) { AbortMultiUploadReq req(m_bucket_name, c_itr->first, c_itr->second); AbortMultiUploadResp resp; CosResult result = m_client->AbortMultiUpload(req, &resp); EXPECT_TRUE(result.IsSucc()); if (!result.IsSucc()) { std::cout << "AbortMultiUpload Failed, object=" << c_itr->first << ", upload_id=" << c_itr->second << std::endl; } } } // 3. 删除Bucket { { DeleteBucketReq req(m_bucket_name); DeleteBucketResp resp; CosResult result = m_client->DeleteBucket(req, &resp); ASSERT_TRUE(result.IsSucc()); } { DeleteBucketReq req(m_bucket_name2); DeleteBucketResp resp; CosResult result = m_client->DeleteBucket(req, &resp); ASSERT_TRUE(result.IsSucc()); } } delete m_client; delete m_config; std::cout << "================TearDownTestCase End====================" << std::endl; } protected: static CosConfig* m_config; static CosAPI* m_client; static std::string m_bucket_name; static std::string m_bucket_name2; // 用于copy // 用于记录单测中未Complete的分块上传uploadID,便于清理 static std::map<std::string, std::string> m_to_be_aborted; }; std::string ObjectOpTest::m_bucket_name = ""; std::string ObjectOpTest::m_bucket_name2 = ""; CosConfig* ObjectOpTest::m_config = NULL; CosAPI* ObjectOpTest::m_client = NULL; std::map<std::string, std::string> ObjectOpTest::m_to_be_aborted; #if 1 TEST_F(ObjectOpTest, PutObjectByFileTest) { // 1. ObjectName为普通字符串 { PutObjectByFileReq req(m_bucket_name, "object_test", "sevenyou.txt"); req.SetXCosStorageClass(kStorageClassStandard); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // 2. ObjectName为中文字符串 { PutObjectByFileReq req(m_bucket_name, "这是个中文Object", "sevenyou.txt"); req.SetXCosStorageClass(kStorageClassStandard); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // 3. ObjectName为特殊字符串 { PutObjectByFileReq req(m_bucket_name, "/→↓←→↖↗↙↘! \"#$%&'()*+,-./0123456789:;" "<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", "sevenyou.txt"); req.SetXCosStorageClass(kStorageClassStandardIA); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } #if 0 // 4. 上传大文件1G { PutObjectByFileReq req(m_bucket_name, "sevenyou_1G.tmp", "./sevenyou_1G.tmp"); req.SetXCosStorageClass(kStorageClassStandard); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } #endif // 5. 服务端加密, 正确的加密算法AES256 { PutObjectByFileReq req(m_bucket_name, "object_server_side_enc_test", "sevenyou.txt"); req.SetXCosStorageClass(kStorageClassStandard); req.SetXCosServerSideEncryption("AES256"); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ("AES256", resp.GetXCosServerSideEncryption()); } // 6. 服务端加密, 错误的加密算法AES789 { PutObjectByFileReq req(m_bucket_name, "object_server_side_enc_wrong_test", "sevenyou.txt"); req.SetXCosStorageClass(kStorageClassStandard); req.SetXCosServerSideEncryption("AES789"); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_FALSE(result.IsSucc()); EXPECT_EQ(400, result.GetHttpStatus()); //EXPECT_EQ("SSEContentNotSupported", result.GetErrorCode()); EXPECT_EQ("InvalidArgument", result.GetErrorCode()); } // 7. 关闭MD5上传校验 { PutObjectByFileReq req(m_bucket_name, "object_file_not_count_contentmd5", "sevenyou.txt"); req.TurnOffComputeConentMd5(); PutObjectByFileResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); //ASSERT_FALSE(result.IsSucc()); } } TEST_F(ObjectOpTest, PutObjectByStreamTest) { // 1. ObjectName为普通字符串 { std::istringstream iss("put_obj_by_stream_normal_string"); PutObjectByStreamReq req(m_bucket_name, "object_test2", iss); req.SetXCosStorageClass(kStorageClassStandard); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // 2. ObjectName为中文字符串 { std::istringstream iss("put_obj_by_stream_chinese_string"); PutObjectByStreamReq req(m_bucket_name, "这是个中文Object2", iss); req.SetXCosStorageClass(kStorageClassStandardIA); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // 3. ObjectName为特殊字符串 { std::istringstream iss("put_obj_by_stream_special_string"); PutObjectByStreamReq req(m_bucket_name, "/→↓←→↖↗↙↘! \"#$%&'()*+,-./0123456789:;" "<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~2", iss); req.SetXCosStorageClass(kStorageClassStandard); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // 4. 关闭MD5上传校验 { std::istringstream iss("put_obj_by_stream_not_count_contentmd5"); PutObjectByStreamReq req(m_bucket_name, "object_test3", iss); req.TurnOffComputeConentMd5(); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } } TEST_F(ObjectOpTest, IsObjectExistTest) { EXPECT_TRUE(m_client->IsObjectExist(m_bucket_name, "object_test")); EXPECT_FALSE(m_client->IsObjectExist(m_bucket_name, "not_exist_object")); } TEST_F(ObjectOpTest, HeadObjectTest) { { HeadObjectReq req(m_bucket_name, "object_test"); HeadObjectResp resp; CosResult result = m_client->HeadObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } { HeadObjectReq req(m_bucket_name, "object_server_side_enc_test"); HeadObjectResp resp; CosResult result = m_client->HeadObject(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ("AES256", resp.GetXCosServerSideEncryption()); } } TEST_F(ObjectOpTest, DeleteObjectTest) { { // Delete empty string, test whether call the DeleteBucket interface std::string object_name = ""; DeleteObjectReq req(m_bucket_name, object_name); DeleteObjectResp resp; CosResult result = m_client->DeleteObject(req, &resp); std::string errinfo = result.GetErrorInfo(); EXPECT_EQ("Delete object's name is empty.", errinfo); } } TEST_F(ObjectOpTest, GetObjectByFileTest) { { GetObjectByFileReq req(m_bucket_name, "object_test", "sevenyou2.txt"); GetObjectByFileResp resp; CosResult result = m_client->GetObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } #if 0 { GetObjectByFileReq req(m_bucket_name, "sevenyou_1G.tmp", "sevenyou_1G.tmp_download"); GetObjectByFileResp resp; CosResult result = m_client->GetObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } #endif // 下载服务端加密的文件 { GetObjectByFileReq req(m_bucket_name, "object_server_side_enc_test", "object_server_side_enc_test.download"); GetObjectByFileResp resp; CosResult result = m_client->GetObject(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ("AES256", resp.GetXCosServerSideEncryption()); } } TEST_F(ObjectOpTest, MultiUploadObjectTest) { { uint64_t part_size = 20 * 1000 * 1000; uint64_t max_part_num = 3; std::string object_name = "object_test_multi"; InitMultiUploadReq init_req(m_bucket_name, object_name); InitMultiUploadResp init_resp; CosResult init_result = m_client->InitMultiUpload(init_req, &init_resp); ASSERT_TRUE(init_result.IsSucc()); std::vector<std::string> etags; std::vector<uint64_t> part_numbers; for (uint64_t part_cnt = 0; part_cnt < max_part_num; ++part_cnt) { std::string str(part_size * (part_cnt + 1), 'a'); // 分块大小倍增 std::stringstream ss; ss << str; UploadPartDataReq req(m_bucket_name, object_name, init_resp.GetUploadId(), ss); UploadPartDataResp resp; req.SetPartNumber(part_cnt + 1); CosResult result = m_client->UploadPartData(req, &resp); ASSERT_TRUE(result.IsSucc()); etags.push_back(resp.GetEtag()); part_numbers.push_back(part_cnt + 1); } // 测试ListParts { ListPartsReq req(m_bucket_name, object_name, init_resp.GetUploadId()); ListPartsResp resp; CosResult result = m_client->ListParts(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ(m_bucket_name, resp.GetBucket()); EXPECT_EQ(object_name, resp.GetKey()); EXPECT_EQ(init_resp.GetUploadId(), resp.GetUploadId()); const std::vector<Part>& parts = resp.GetParts(); EXPECT_EQ(max_part_num, parts.size()); for (size_t idx = 0; idx != parts.size(); ++idx) { EXPECT_EQ(part_numbers[idx], parts[idx].m_part_num); EXPECT_EQ(part_size * (idx + 1), parts[idx].m_size); EXPECT_EQ(etags[idx], parts[idx].m_etag); } } CompleteMultiUploadReq comp_req(m_bucket_name, object_name, init_resp.GetUploadId()); CompleteMultiUploadResp comp_resp; comp_req.SetEtags(etags); comp_req.SetPartNumbers(part_numbers); CosResult result = m_client->CompleteMultiUpload(comp_req, &comp_resp); EXPECT_TRUE(result.IsSucc()); } // 服务端加密 { uint64_t part_size = 20 * 1000 * 1000; uint64_t max_part_num = 3; std::string object_name = "object_test_multi_and_enc"; InitMultiUploadReq init_req(m_bucket_name, object_name); init_req.SetXCosServerSideEncryption("AES256"); InitMultiUploadResp init_resp; CosResult init_result = m_client->InitMultiUpload(init_req, &init_resp); ASSERT_TRUE(init_result.IsSucc()); EXPECT_EQ("AES256", init_resp.GetXCosServerSideEncryption()); std::vector<std::string> etags; std::vector<uint64_t> part_numbers; for (uint64_t part_cnt = 0; part_cnt < max_part_num; ++part_cnt) { std::string str(part_size * (part_cnt + 1), 'b'); // 分块大小倍增 std::stringstream ss; ss << str; UploadPartDataReq req(m_bucket_name, object_name, init_resp.GetUploadId(), ss); UploadPartDataResp resp; req.SetPartNumber(part_cnt + 1); CosResult result = m_client->UploadPartData(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ("AES256", resp.GetXCosServerSideEncryption()); etags.push_back(resp.GetEtag()); part_numbers.push_back(part_cnt + 1); } // 测试ListParts { ListPartsReq req(m_bucket_name, object_name, init_resp.GetUploadId()); ListPartsResp resp; CosResult result = m_client->ListParts(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ(m_bucket_name, resp.GetBucket()); EXPECT_EQ(object_name, resp.GetKey()); EXPECT_EQ(init_resp.GetUploadId(), resp.GetUploadId()); const std::vector<Part>& parts = resp.GetParts(); EXPECT_EQ(max_part_num, parts.size()); for (size_t idx = 0; idx != parts.size(); ++idx) { EXPECT_EQ(part_numbers[idx], parts[idx].m_part_num); EXPECT_EQ(part_size * (idx + 1), parts[idx].m_size); EXPECT_EQ(etags[idx], parts[idx].m_etag); } } CompleteMultiUploadReq comp_req(m_bucket_name, object_name, init_resp.GetUploadId()); CompleteMultiUploadResp comp_resp; comp_req.SetEtags(etags); comp_req.SetPartNumbers(part_numbers); CosResult result = m_client->CompleteMultiUpload(comp_req, &comp_resp); EXPECT_EQ("AES256", comp_resp.GetXCosServerSideEncryption()); EXPECT_TRUE(result.IsSucc()); } } TEST_F(ObjectOpTest, MultiUploadObjectTest_OneStep) { { std::string filename = "multi_upload_object_one_step"; std::string object_name = filename; // 1. 生成个临时文件, 用于分块上传 { std::ofstream fs; fs.open(filename.c_str(), std::ios::out | std::ios::binary); std::string str(10 * 1000 * 1000, 'b'); for (int idx = 0; idx < 10; ++idx) { fs << str; } fs.close(); } // 2. 上传 MultiUploadObjectReq req(m_bucket_name, object_name, filename); MultiUploadObjectResp resp; CosResult result = m_client->MultiUploadObject(req, &resp); EXPECT_TRUE(result.IsSucc()); // 3. 删除临时文件 if (-1 == remove(filename.c_str())) { std::cout << "Remove temp file=" << filename << " fail." << std::endl; } } { std::string filename = "multi_upload_object_enc_one_step"; std::string object_name = filename; // 1. 生成个临时文件, 用于分块上传 { std::ofstream fs; fs.open(filename.c_str(), std::ios::out | std::ios::binary); std::string str(10 * 1000 * 1000, 'b'); for (int idx = 0; idx < 10; ++idx) { fs << str; } fs.close(); } // 2. 上传 MultiUploadObjectReq req(m_bucket_name, object_name, filename); req.SetXCosServerSideEncryption("AES256"); MultiUploadObjectResp resp; CosResult result = m_client->MultiUploadObject(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ("AES256", resp.GetXCosServerSideEncryption()); // 3. 删除临时文件 if (-1 == remove(filename.c_str())) { std::cout << "Remove temp file=" << filename << " fail." << std::endl; } } } TEST_F(ObjectOpTest, AbortMultiUploadTest) { uint64_t part_size = 20 * 1000 * 1000; uint64_t max_part_num = 3; std::string object_name = "object_test_abort_multi"; InitMultiUploadReq init_req(m_bucket_name, object_name); InitMultiUploadResp init_resp; CosResult init_result = m_client->InitMultiUpload(init_req, &init_resp); ASSERT_TRUE(init_result.IsSucc()); std::vector<std::string> etags; std::vector<uint64_t> part_numbers; for (uint64_t part_cnt = 0; part_cnt < max_part_num; ++part_cnt) { std::string str(part_size * (part_cnt + 1), 'a'); // 分块大小倍增 std::stringstream ss; ss << str; UploadPartDataReq req(m_bucket_name, object_name, init_resp.GetUploadId(), ss); UploadPartDataResp resp; req.SetPartNumber(part_cnt + 1); CosResult result = m_client->UploadPartData(req, &resp); ASSERT_TRUE(result.IsSucc()); etags.push_back(resp.GetEtag()); part_numbers.push_back(part_cnt + 1); } AbortMultiUploadReq abort_req(m_bucket_name, object_name, init_resp.GetUploadId()); AbortMultiUploadResp abort_resp; CosResult result = m_client->AbortMultiUpload(abort_req, &abort_resp); ASSERT_TRUE(result.IsSucc()); } TEST_F(ObjectOpTest, ObjectACLTest) { // 1. Put { PutObjectACLReq req(m_bucket_name, "object_test"); PutObjectACLResp resp; std::string uin(GetEnv("CPP_SDK_V5_UIN")); std::string grant_uin(GetEnv("CPP_SDK_V5_OTHER_UIN")); qcloud_cos::Owner owner = {"qcs::cam::uin/" + uin + ":uin/" + uin, "qcs::cam::uin/" + uin + ":uin/" + uin}; Grant grant; req.SetOwner(owner); grant.m_perm = "READ"; grant.m_grantee.m_type = "RootAccount"; grant.m_grantee.m_uri = "http://cam.qcloud.com/groups/global/AllUsers"; grant.m_grantee.m_id = "qcs::cam::uin/" + grant_uin + ":uin/" + grant_uin; grant.m_grantee.m_display_name = "qcs::cam::uin/" + grant_uin + ":uin/" + grant_uin; req.AddAccessControlList(grant); CosResult result = m_client->PutObjectACL(req, &resp); EXPECT_TRUE(result.IsSucc()); } // 2. Get { sleep(5); GetObjectACLReq req(m_bucket_name, "object_test"); GetObjectACLResp resp; CosResult result = m_client->GetObjectACL(req, &resp); EXPECT_TRUE(result.IsSucc()); } } TEST_F(ObjectOpTest, PutObjectCopyTest) { { std::string object_name = "object_test"; PutObjectCopyReq req(m_bucket_name2, "object_test_copy_from_bucket1"); PutObjectCopyResp resp; std::string source = m_bucket_name + "." + m_config->GetRegion() + ".mycloud.com/" + object_name; req.SetXCosCopySource(source); CosResult result = m_client->PutObjectCopy(req, &resp); EXPECT_TRUE(result.IsSucc()); } { std::string object_name = "object_test"; PutObjectCopyReq req(m_bucket_name2, "object_enc_test_copy_from_bucket1"); PutObjectCopyResp resp; std::string source = m_bucket_name + "." + m_config->GetRegion() + ".mycloud.com/" + object_name; req.SetXCosCopySource(source); req.SetXCosServerSideEncryption("AES256"); CosResult result = m_client->PutObjectCopy(req, &resp); EXPECT_TRUE(result.IsSucc()); EXPECT_EQ("AES256", resp.GetXCosServerSideEncryption()); } } TEST_F(ObjectOpTest, GeneratePresignedUrlTest) { { GeneratePresignedUrlReq req(m_bucket_name, "object_test", HTTP_GET); req.SetStartTimeInSec(0); req.SetExpiredTimeInSec(5 * 60); std::string presigned_url = m_client->GeneratePresignedUrl(req); EXPECT_FALSE(presigned_url.empty()); // TODO(sevenyou) 先直接调 curl 命令看下是否正常 std::string curl_url = "curl " + presigned_url; int ret = system(curl_url.c_str()); EXPECT_EQ(0, ret); } { std::string presigned_url = m_client->GeneratePresignedUrl(m_bucket_name, "object_test", 0, 0); // TODO(sevenyou) 先直接调 curl 命令看下是否正常 std::string curl_url = "curl " + presigned_url; int ret = system(curl_url.c_str()); EXPECT_EQ(0, ret); } } TEST_F(ObjectOpTest, PutObjectWithMultiMeta) { // put object { std::istringstream iss("put_obj_by_stream_normal_string"); PutObjectByStreamReq req(m_bucket_name, "object_test_with_multiheader", iss); req.SetContentDisposition("attachment; filename=example"); req.SetContentType("image/jpeg"); req.SetContentEncoding("compress"); req.SetXCosMeta("key1", "val1"); req.SetXCosMeta("key2", "val2"); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // head object { HeadObjectReq req(m_bucket_name, "object_test_with_multiheader"); HeadObjectResp resp; CosResult result = m_client->HeadObject(req, &resp); ASSERT_TRUE(result.IsSucc()); EXPECT_EQ("image/jpeg", resp.GetContentType()); EXPECT_EQ("attachment; filename=example", resp.GetContentDisposition()); EXPECT_EQ("compress", resp.GetContentEncoding()); EXPECT_EQ(resp.GetXCosMeta("key1"), "val1"); EXPECT_EQ(resp.GetXCosMeta("key2"), "val2"); } } TEST_F(ObjectOpTest, ObjectOptionsDefault) { // put object { std::istringstream iss("test string"); PutObjectByStreamReq req(m_bucket_name, "object_test_origin", iss); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // test default option { OptionsObjectReq req(m_bucket_name, "object_test_origin"); req.SetOrigin("https://console.cloud.tencent.com"); req.SetAccessControlRequestMethod("GET"); req.SetAccessControlRequestHeaders("Content-Length"); OptionsObjectResp resp; CosResult result = m_client->OptionsObject(req, &resp); EXPECT_EQ(resp.GetAccessControAllowOrigin(), "https://console.cloud.tencent.com"); EXPECT_EQ(resp.GetAccessControlAllowMethods(), "GET,PUT,POST,HEAD,DELETE"); EXPECT_EQ(resp.GetAccessControlAllowHeaders(), "Content-Length"); ASSERT_TRUE(result.IsSucc()); } // put bucket cors and option object { PutBucketCORSReq req(m_bucket_name); PutBucketCORSResp resp; CORSRule rule; rule.m_id = "cors_rule_00"; rule.m_max_age_secs = "600"; rule.m_allowed_headers.push_back("x-cos-header-test1"); rule.m_allowed_headers.push_back("x-cos-header-test2"); rule.m_allowed_origins.push_back("http://www.123.com"); rule.m_allowed_origins.push_back("http://www.abc.com"); rule.m_allowed_methods.push_back("PUT"); rule.m_allowed_methods.push_back("GET"); rule.m_expose_headers.push_back("x-cos-expose-headers"); req.AddRule(rule); CosResult result = m_client->PutBucketCORS(req, &resp); ASSERT_TRUE(result.IsSucc()); } // options object allow { OptionsObjectReq req(m_bucket_name, "object_test_origin"); req.SetOrigin("http://www.123.com"); req.SetAccessControlRequestMethod("GET"); req.SetAccessControlRequestHeaders("x-cos-header-test1"); OptionsObjectResp resp; CosResult result = m_client->OptionsObject(req, &resp); EXPECT_EQ(resp.GetAccessControAllowOrigin(), "http://www.123.com"); EXPECT_EQ(resp.GetAccessControlAllowMethods(), "PUT,GET"); EXPECT_EQ(resp.GetAccessControlAllowHeaders(), "x-cos-header-test1,x-cos-header-test2"); EXPECT_EQ(resp.GetAccessControlExposeHeaders(), "x-cos-expose-headers"); EXPECT_EQ(resp.GetAccessControlMaxAge(), "600"); ASSERT_TRUE(result.IsSucc()); } // options object allow { OptionsObjectReq req(m_bucket_name, "object_test_origin"); req.SetOrigin("http://www.abc.com"); req.SetAccessControlRequestMethod("PUT"); req.SetAccessControlRequestHeaders("x-cos-header-test2"); OptionsObjectResp resp; CosResult result = m_client->OptionsObject(req, &resp); EXPECT_EQ(resp.GetAccessControAllowOrigin(), "http://www.abc.com"); EXPECT_EQ(resp.GetAccessControlAllowMethods(), "PUT,GET"); EXPECT_EQ(resp.GetAccessControlAllowHeaders(), "x-cos-header-test1,x-cos-header-test2"); EXPECT_EQ(resp.GetAccessControlExposeHeaders(), "x-cos-expose-headers"); EXPECT_EQ(resp.GetAccessControlMaxAge(), "600"); ASSERT_TRUE(result.IsSucc()); } // options object not allow { OptionsObjectReq req(m_bucket_name, "object_test_origin"); req.SetOrigin("http://www.1234.com"); req.SetAccessControlRequestMethod("GET"); req.SetAccessControlRequestHeaders("x-cos-header-test"); OptionsObjectResp resp; CosResult result = m_client->OptionsObject(req, &resp); EXPECT_EQ(resp.GetAccessControAllowOrigin(), ""); EXPECT_EQ(resp.GetAccessControlAllowMethods(), ""); EXPECT_EQ(resp.GetAccessControlAllowHeaders(), ""); EXPECT_EQ(resp.GetAccessControlExposeHeaders(), ""); EXPECT_EQ(resp.GetAccessControlMaxAge(), ""); ASSERT_TRUE(!result.IsSucc()); EXPECT_EQ(result.GetHttpStatus(), 403); } } #endif TEST_F(ObjectOpTest, SelectObjectContent) { std::string input_str; // put json object { std::istringstream iss("{\"aaa\":111,\"bbb\":222,\"ccc\":\"333\"}"); input_str = iss.str(); PutObjectByStreamReq req(m_bucket_name, "testjson", iss); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // select object content, input json, output json { SelectObjectContentReq req(m_bucket_name, "testjson", JSON, COMPRESS_NONE, JSON); SelectObjectContentResp resp; req.SetSqlExpression("Select * from COSObject"); CosResult result = m_client->SelectObjectContent(req, &resp); ASSERT_TRUE(result.IsSucc()); resp.PrintResult(); EXPECT_EQ(0, resp.WriteResultToLocalFile("select_result.json")); std::ifstream ifs("select_result.json"); std::stringstream strstream; // read the file strstream << ifs.rdbuf(); // compare EXPECT_EQ(0, input_str.compare(StringUtil::Trim(strstream.str(), "\\n"))); EXPECT_EQ(0, ::remove("select_result.json")); } // select object content using filter, input json, output json, { SelectObjectContentReq req(m_bucket_name, "testjson", JSON, COMPRESS_NONE, JSON); SelectObjectContentResp resp; req.SetSqlExpression("Select testjson.aaa from COSObject testjson"); CosResult result = m_client->SelectObjectContent(req, &resp); ASSERT_TRUE(result.IsSucc()); resp.PrintResult(); EXPECT_EQ(0, resp.WriteResultToLocalFile("select_result.json")); std::ifstream ifs("select_result.json"); std::stringstream strstream; strstream << ifs.rdbuf(); // compare EXPECT_EQ(0, StringUtil::Trim(strstream.str(), "\\n").compare("{\"aaa\":111}")); EXPECT_EQ(0, ::remove("select_result.json")); } // select object content using filter, input json, output json, { SelectObjectContentReq req(m_bucket_name, "testjson", JSON, COMPRESS_NONE, CSV); SelectObjectContentResp resp; req.SetSqlExpression("Select * from COSObject testjson"); CosResult result = m_client->SelectObjectContent(req, &resp); ASSERT_TRUE(result.IsSucc()); resp.PrintResult(); EXPECT_EQ(0, resp.WriteResultToLocalFile("select_result.csv")); //std::ifstream ifs("select_result.csv"); //std::stringstream strstream; //strstream << ifs.rdbuf(); // compare //EXPECT_EQ(0, StringUtil::Trim(strstream.str(), "\\n").compare("{\"aaa\":111}")); EXPECT_EQ(0, ::remove("select_result.csv")); } // put csv object { std::istringstream iss("aaa,111,bbb,222,ccc,333"); input_str = iss.str(); PutObjectByStreamReq req(m_bucket_name, "testcsv", iss); PutObjectByStreamResp resp; CosResult result = m_client->PutObject(req, &resp); ASSERT_TRUE(result.IsSucc()); } // select object content, input csv, output csv { SelectObjectContentReq req(m_bucket_name, "testcsv", CSV, COMPRESS_NONE, CSV); SelectObjectContentResp resp; req.SetSqlExpression("Select * from COSObject"); CosResult result = m_client->SelectObjectContent(req, &resp); ASSERT_TRUE(result.IsSucc()); resp.PrintResult(); EXPECT_EQ(0, resp.WriteResultToLocalFile("select_result.csv")); std::ifstream ifs("select_result.csv"); std::stringstream strstream; strstream << ifs.rdbuf(); // compare EXPECT_EQ(0, input_str.compare(StringUtil::Trim(strstream.str(), "\\\\n"))); EXPECT_EQ(0, ::remove("select_result.csv")); } } } // namespace qcloud_cos
38.151914
107
0.61715
[ "object", "vector" ]
adeb46b046c5d6d10fd343d7c6d056524a3614fe
13,551
hpp
C++
6502.hpp
markypizz/NES-Emulator
6a3be685ad358ca722030baa6384c19ed63acbb9
[ "BSD-3-Clause" ]
1
2020-12-18T02:28:38.000Z
2020-12-18T02:28:38.000Z
6502.hpp
markypizz/NES-Emulator
6a3be685ad358ca722030baa6384c19ed63acbb9
[ "BSD-3-Clause" ]
null
null
null
6502.hpp
markypizz/NES-Emulator
6a3be685ad358ca722030baa6384c19ed63acbb9
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cstdint> #include <string> #include <vector> #include "6502.hpp" #include <map> // Forward declare Bus class Bus; /** * @brief 6502 CPU class */ class CPU6502 { public: CPU6502(); ~CPU6502(); void connectBus(Bus *inBus) { bus = inBus; } /** * @brief Enums for flag bit register */ enum STATUS_FLAG { C = 0b00000001, // Carry Z = 0b00000010, // Result Zero I = 0b00000100, // IRQ Disable D = 0b00001000, // Decimal mode ** not used ** B = 0b00010000, // BRK command U = 0b00100000, // Unused O = 0b01000000, // Overflow N = 0b10000000, // Negative }; //---------------------- // Addressing modes //---------------------- /** Doxy defined in .cpp */ uint8_t IMP(); uint8_t IMM(); uint8_t ZP0(); uint8_t ZPX(); uint8_t ZPY(); uint8_t REL(); uint8_t ABS(); uint8_t ABX(); uint8_t ABY(); uint8_t IND(); uint8_t IZX(); uint8_t IZY(); //---------------------- // Opcodes //---------------------- /** Doxy defined in .cpp */ uint8_t ADC(); uint8_t AND(); uint8_t ASL(); uint8_t BCC(); uint8_t BCS(); uint8_t BEQ(); uint8_t BIT(); uint8_t BMI(); uint8_t BNE(); uint8_t BPL(); uint8_t BRK(); uint8_t BVC(); uint8_t BVS(); uint8_t CLC(); uint8_t CLD(); uint8_t CLI(); uint8_t CLV(); uint8_t CMP(); uint8_t CPX(); uint8_t CPY(); uint8_t DEC(); uint8_t DEX(); uint8_t DEY(); uint8_t EOR(); uint8_t INC(); uint8_t INX(); uint8_t INY(); uint8_t JMP(); uint8_t JSR(); uint8_t LDA(); uint8_t LDX(); uint8_t LDY(); uint8_t LSR(); uint8_t NOP(); uint8_t ORA(); uint8_t PHA(); uint8_t PHP(); uint8_t PLA(); uint8_t PLP(); uint8_t ROL(); uint8_t ROR(); uint8_t RTI(); uint8_t RTS(); uint8_t SBC(); uint8_t SEC(); uint8_t SED(); uint8_t SEI(); uint8_t STA(); uint8_t STX(); uint8_t STY(); uint8_t TAX(); uint8_t TAY(); uint8_t TSX(); uint8_t TXA(); uint8_t TXS(); uint8_t TYA(); /** * @brief Catch illegal opcode * @return uint8_t */ uint8_t ILL(); //---------------------- // * Signals * // // // Asynchronous, can occur at any time // current instruction however will finish executing before these take effect //---------------------- void clock(); void reset(); void irq(); /** * @brief Non-masking interrupt * @note can not be disabled */ void nmi(); /** * @brief Dissasemble function * @note Code from https://github.com/OneLoneCoder/olcNES/blob/master/Part%232%20-%20CPU/olc6502.cpp */ std::map<uint16_t, std::string> disassemble(uint16_t nStart, uint16_t nStop); //---------------------- // Constants //---------------------- static constexpr uint16_t STACK_BASE = 0x0100; static constexpr uint16_t STACK_DEFAULT = 0x00FD; static constexpr uint16_t P_DEFAULT = (0x00 | STATUS_FLAG::U); static constexpr uint16_t PC_DEFAULT = 0xFFFC; static constexpr uint16_t INT_TARGET_ADDR = 0xFFFE; //---------------------- // Data Section //---------------------- uint8_t fetch(); uint8_t fetched_data = 0x00; uint16_t target_addr = 0x0000; uint16_t rel_addr = 0x00; uint8_t current_opcode = 0x00; uint8_t cycles = 0; //---------------------- // Register Definitions //---------------------- uint8_t a = 0x00; // Accumulator A uint8_t y = 0x00; // Index reg Y uint8_t x = 0x00; // Index reg X uint16_t pc = 0x0000; // Program Counter uint8_t s = 0x00; // Stack pointer uint8_t p = 0x00; // Proc status reg (STATUS_FLAG enums) private: Bus* bus = nullptr; using c = CPU6502; /** * @brief Instruction struct */ struct instruction { // Neumonic, for tracing std::string name; uint8_t(c::*op)(void) = nullptr; uint8_t(c::*addr_mode)(void) = nullptr; // Number of cycles uint8_t cycles = 0; }; const instruction illegal_inst = {"XXX", &c::ILL, &c::IMP, 2}; /** * @brief Instruction lookup table * @note derived from http://archive.6502.org/datasheets/rockwell_r650x_r651x.pdf with aid from * https://github.com/OneLoneCoder/olcNES/blob/master/Part%232%20-%20CPU/olc6502.cpp */ std::vector<instruction> instructions = { { "BRK", &c::BRK, &c::IMM, 7 },{ "ORA", &c::ORA, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 3 },{ "ORA", &c::ORA, &c::ZP0, 3 },{ "ASL", &c::ASL, &c::ZP0, 5 },illegal_inst ,{ "PHP", &c::PHP, &c::IMP, 3 },{ "ORA", &c::ORA, &c::IMM, 2 },{ "ASL", &c::ASL, &c::IMP, 2 },illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "ORA", &c::ORA, &c::ABS, 4 },{ "ASL", &c::ASL, &c::ABS, 6 },illegal_inst , { "BPL", &c::BPL, &c::REL, 2 },{ "ORA", &c::ORA, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "ORA", &c::ORA, &c::ZPX, 4 },{ "ASL", &c::ASL, &c::ZPX, 6 },illegal_inst ,{ "CLC", &c::CLC, &c::IMP, 2 },{ "ORA", &c::ORA, &c::ABY, 4 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "ORA", &c::ORA, &c::ABX, 4 },{ "ASL", &c::ASL, &c::ABX, 7 },illegal_inst , { "JSR", &c::JSR, &c::ABS, 6 },{ "AND", &c::AND, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "BIT", &c::BIT, &c::ZP0, 3 },{ "AND", &c::AND, &c::ZP0, 3 },{ "ROL", &c::ROL, &c::ZP0, 5 },illegal_inst ,{ "PLP", &c::PLP, &c::IMP, 4 },{ "AND", &c::AND, &c::IMM, 2 },{ "ROL", &c::ROL, &c::IMP, 2 },illegal_inst ,{ "BIT", &c::BIT, &c::ABS, 4 },{ "AND", &c::AND, &c::ABS, 4 },{ "ROL", &c::ROL, &c::ABS, 6 },illegal_inst , { "BMI", &c::BMI, &c::REL, 2 },{ "AND", &c::AND, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "AND", &c::AND, &c::ZPX, 4 },{ "ROL", &c::ROL, &c::ZPX, 6 },illegal_inst ,{ "SEC", &c::SEC, &c::IMP, 2 },{ "AND", &c::AND, &c::ABY, 4 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "AND", &c::AND, &c::ABX, 4 },{ "ROL", &c::ROL, &c::ABX, 7 },illegal_inst , { "RTI", &c::RTI, &c::IMP, 6 },{ "EOR", &c::EOR, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 3 },{ "EOR", &c::EOR, &c::ZP0, 3 },{ "LSR", &c::LSR, &c::ZP0, 5 },illegal_inst ,{ "PHA", &c::PHA, &c::IMP, 3 },{ "EOR", &c::EOR, &c::IMM, 2 },{ "LSR", &c::LSR, &c::IMP, 2 },illegal_inst ,{ "JMP", &c::JMP, &c::ABS, 3 },{ "EOR", &c::EOR, &c::ABS, 4 },{ "LSR", &c::LSR, &c::ABS, 6 },illegal_inst , { "BVC", &c::BVC, &c::REL, 2 },{ "EOR", &c::EOR, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "EOR", &c::EOR, &c::ZPX, 4 },{ "LSR", &c::LSR, &c::ZPX, 6 },illegal_inst ,{ "CLI", &c::CLI, &c::IMP, 2 },{ "EOR", &c::EOR, &c::ABY, 4 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "EOR", &c::EOR, &c::ABX, 4 },{ "LSR", &c::LSR, &c::ABX, 7 },illegal_inst , { "RTS", &c::RTS, &c::IMP, 6 },{ "ADC", &c::ADC, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 3 },{ "ADC", &c::ADC, &c::ZP0, 3 },{ "ROR", &c::ROR, &c::ZP0, 5 },illegal_inst ,{ "PLA", &c::PLA, &c::IMP, 4 },{ "ADC", &c::ADC, &c::IMM, 2 },{ "ROR", &c::ROR, &c::IMP, 2 },illegal_inst ,{ "JMP", &c::JMP, &c::IND, 5 },{ "ADC", &c::ADC, &c::ABS, 4 },{ "ROR", &c::ROR, &c::ABS, 6 },illegal_inst , { "BVS", &c::BVS, &c::REL, 2 },{ "ADC", &c::ADC, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "ADC", &c::ADC, &c::ZPX, 4 },{ "ROR", &c::ROR, &c::ZPX, 6 },illegal_inst ,{ "SEI", &c::SEI, &c::IMP, 2 },{ "ADC", &c::ADC, &c::ABY, 4 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "ADC", &c::ADC, &c::ABX, 4 },{ "ROR", &c::ROR, &c::ABX, 7 },illegal_inst , illegal_inst ,{ "STA", &c::STA, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "STY", &c::STY, &c::ZP0, 3 },{ "STA", &c::STA, &c::ZP0, 3 },{ "STX", &c::STX, &c::ZP0, 3 },illegal_inst ,{ "DEY", &c::DEY, &c::IMP, 2 },illegal_inst ,{ "TXA", &c::TXA, &c::IMP, 2 },illegal_inst ,{ "STY", &c::STY, &c::ABS, 4 },{ "STA", &c::STA, &c::ABS, 4 },{ "STX", &c::STX, &c::ABS, 4 },illegal_inst , { "BCC", &c::BCC, &c::REL, 2 },{ "STA", &c::STA, &c::IZY, 6 },illegal_inst ,illegal_inst ,{ "STY", &c::STY, &c::ZPX, 4 },{ "STA", &c::STA, &c::ZPX, 4 },{ "STX", &c::STX, &c::ZPY, 4 },illegal_inst ,{ "TYA", &c::TYA, &c::IMP, 2 },{ "STA", &c::STA, &c::ABY, 5 },{ "TXS", &c::TXS, &c::IMP, 2 },illegal_inst ,{ "???", &c::NOP, &c::IMP, 5 },{ "STA", &c::STA, &c::ABX, 5 },illegal_inst ,illegal_inst , { "LDY", &c::LDY, &c::IMM, 2 },{ "LDA", &c::LDA, &c::IZX, 6 },{ "LDX", &c::LDX, &c::IMM, 2 },illegal_inst ,{ "LDY", &c::LDY, &c::ZP0, 3 },{ "LDA", &c::LDA, &c::ZP0, 3 },{ "LDX", &c::LDX, &c::ZP0, 3 },illegal_inst ,{ "TAY", &c::TAY, &c::IMP, 2 },{ "LDA", &c::LDA, &c::IMM, 2 },{ "TAX", &c::TAX, &c::IMP, 2 },illegal_inst ,{ "LDY", &c::LDY, &c::ABS, 4 },{ "LDA", &c::LDA, &c::ABS, 4 },{ "LDX", &c::LDX, &c::ABS, 4 },illegal_inst , { "BCS", &c::BCS, &c::REL, 2 },{ "LDA", &c::LDA, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "LDY", &c::LDY, &c::ZPX, 4 },{ "LDA", &c::LDA, &c::ZPX, 4 },{ "LDX", &c::LDX, &c::ZPY, 4 },illegal_inst ,{ "CLV", &c::CLV, &c::IMP, 2 },{ "LDA", &c::LDA, &c::ABY, 4 },{ "TSX", &c::TSX, &c::IMP, 2 },illegal_inst ,{ "LDY", &c::LDY, &c::ABX, 4 },{ "LDA", &c::LDA, &c::ABX, 4 },{ "LDX", &c::LDX, &c::ABY, 4 },illegal_inst , { "CPY", &c::CPY, &c::IMM, 2 },{ "CMP", &c::CMP, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "CPY", &c::CPY, &c::ZP0, 3 },{ "CMP", &c::CMP, &c::ZP0, 3 },{ "DEC", &c::DEC, &c::ZP0, 5 },illegal_inst ,{ "INY", &c::INY, &c::IMP, 2 },{ "CMP", &c::CMP, &c::IMM, 2 },{ "DEX", &c::DEX, &c::IMP, 2 },illegal_inst ,{ "CPY", &c::CPY, &c::ABS, 4 },{ "CMP", &c::CMP, &c::ABS, 4 },{ "DEC", &c::DEC, &c::ABS, 6 },illegal_inst , { "BNE", &c::BNE, &c::REL, 2 },{ "CMP", &c::CMP, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "CMP", &c::CMP, &c::ZPX, 4 },{ "DEC", &c::DEC, &c::ZPX, 6 },illegal_inst ,{ "CLD", &c::CLD, &c::IMP, 2 },{ "CMP", &c::CMP, &c::ABY, 4 },{ "NOP", &c::NOP, &c::IMP, 2 },illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "CMP", &c::CMP, &c::ABX, 4 },{ "DEC", &c::DEC, &c::ABX, 7 },illegal_inst , { "CPX", &c::CPX, &c::IMM, 2 },{ "SBC", &c::SBC, &c::IZX, 6 },illegal_inst ,illegal_inst ,{ "CPX", &c::CPX, &c::ZP0, 3 },{ "SBC", &c::SBC, &c::ZP0, 3 },{ "INC", &c::INC, &c::ZP0, 5 },illegal_inst ,{ "INX", &c::INX, &c::IMP, 2 },{ "SBC", &c::SBC, &c::IMM, 2 },{ "NOP", &c::NOP, &c::IMP, 2 },illegal_inst ,{ "CPX", &c::CPX, &c::ABS, 4 },{ "SBC", &c::SBC, &c::ABS, 4 },{ "INC", &c::INC, &c::ABS, 6 },illegal_inst , { "BEQ", &c::BEQ, &c::REL, 2 },{ "SBC", &c::SBC, &c::IZY, 5 },illegal_inst ,illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "SBC", &c::SBC, &c::ZPX, 4 },{ "INC", &c::INC, &c::ZPX, 6 },illegal_inst ,{ "SED", &c::SED, &c::IMP, 2 },{ "SBC", &c::SBC, &c::ABY, 4 },{ "NOP", &c::NOP, &c::IMP, 2 },illegal_inst ,{ "???", &c::NOP, &c::IMP, 4 },{ "SBC", &c::SBC, &c::ABX, 4 },{ "INC", &c::INC, &c::ABX, 7 },illegal_inst , }; /** * @brief 6502 read function * * @param addr 16 bit address * @return uint8_t data at addr * @note calls Bus::read */ uint8_t read(uint16_t addr); /** * @brief 6502 write function * * @param addr 16 bit address * @param data data to write * @note calls Bus::write */ void write(uint16_t addr, uint8_t data); /** * @brief Get the STATUS_FLAG in the proc status register * * @param flag flag to get * @return uint8_t HIGH/LOW */ uint8_t getFlag(STATUS_FLAG flag); /** * @brief Set the STATUS_FLAG in the proc status register * * @param flag flag to set * @param h HIGH/LOW */ void setFlag(STATUS_FLAG flag, bool h); }; // Other useful helper functions template <typename T> inline static bool is8BitNeg(T data) { T compare = 0x80; return (data & compare); }
50.752809
504
0.443879
[ "vector" ]
adfb7be88ee250c1fe6db042f20dc496387712c4
13,049
cpp
C++
frmts/zarr/zarr_attribute.cpp
jcphill/gdal
98c9ecf8513325bb69888d368bd9a0d54b79e72b
[ "Apache-2.0" ]
3,100
2015-01-02T10:33:40.000Z
2022-03-31T02:06:51.000Z
frmts/zarr/zarr_attribute.cpp
jcphill/gdal
98c9ecf8513325bb69888d368bd9a0d54b79e72b
[ "Apache-2.0" ]
3,496
2015-01-06T16:53:30.000Z
2022-03-31T20:18:51.000Z
frmts/zarr/zarr_attribute.cpp
jcphill/gdal
98c9ecf8513325bb69888d368bd9a0d54b79e72b
[ "Apache-2.0" ]
2,036
2015-01-08T20:22:12.000Z
2022-03-31T10:24:08.000Z
/****************************************************************************** * * Project: GDAL * Purpose: Zarr driver * Author: Even Rouault <even dot rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2021, Even Rouault <even dot rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "zarr.h" #include <algorithm> #include <cassert> #include <map> /************************************************************************/ /* ZarrAttributeGroup::ZarrAttributeGroup() */ /************************************************************************/ ZarrAttributeGroup::ZarrAttributeGroup(const std::string& osParentName): m_oGroup(osParentName, nullptr) { } /************************************************************************/ /* ZarrAttributeGroup::Init() */ /************************************************************************/ void ZarrAttributeGroup::Init(const CPLJSONObject& obj, bool bUpdatable) { if( obj.GetType() != CPLJSONObject::Type::Object ) return; const auto children = obj.GetChildren(); for( const auto& item: children ) { const auto itemType = item.GetType(); bool bDone = false; std::shared_ptr<GDALAttribute> poAttr; if( itemType == CPLJSONObject::Type::String ) { bDone = true; poAttr = m_oGroup.CreateAttribute( item.GetName(), {}, GDALExtendedDataType::CreateString(), nullptr); if( poAttr ) { const GUInt64 arrayStartIdx = 0; const size_t count = 1; const GInt64 arrayStep = 0; const GPtrDiff_t bufferStride = 0; const std::string str = item.ToString(); const char* c_str = str.c_str(); poAttr->Write(&arrayStartIdx, &count, &arrayStep, &bufferStride, poAttr->GetDataType(), &c_str); } } else if( itemType == CPLJSONObject::Type::Integer || itemType == CPLJSONObject::Type::Long || itemType == CPLJSONObject::Type::Double ) { bDone = true; poAttr = m_oGroup.CreateAttribute( item.GetName(), {}, GDALExtendedDataType::Create( itemType == CPLJSONObject::Type::Integer ? GDT_Int32 : GDT_Float64), nullptr); if( poAttr ) { const GUInt64 arrayStartIdx = 0; const size_t count = 1; const GInt64 arrayStep = 0; const GPtrDiff_t bufferStride = 0; const double val = item.ToDouble(); poAttr->Write(&arrayStartIdx, &count, &arrayStep, &bufferStride, GDALExtendedDataType::Create(GDT_Float64), &val); } } else if( itemType == CPLJSONObject::Type::Array ) { const auto array = item.ToArray(); bool isFirst = true; bool isString = false; bool isNumeric = false; bool foundInt64 = false; bool foundDouble = false; bool mixedType = false; size_t countItems = 0; for( const auto& subItem: array ) { const auto subItemType = subItem.GetType(); if( subItemType == CPLJSONObject::Type::String ) { if( isFirst ) { isString = true; } else if( !isString ) { mixedType = true; break; } countItems ++; } else if( subItemType == CPLJSONObject::Type::Integer || subItemType == CPLJSONObject::Type::Long || subItemType == CPLJSONObject::Type::Double ) { if( isFirst ) { isNumeric = true; } else if( !isNumeric ) { mixedType = true; break; } if( subItemType == CPLJSONObject::Type::Double ) foundDouble = true; else if( subItemType == CPLJSONObject::Type::Long ) foundInt64 = true; countItems ++; } else { mixedType = true; break; } isFirst = false; } if( !mixedType && !isFirst ) { bDone = true; poAttr = m_oGroup.CreateAttribute( item.GetName(), { countItems }, isString ? GDALExtendedDataType::CreateString(): GDALExtendedDataType::Create( (foundDouble || foundInt64) ? GDT_Float64 : GDT_Int32), nullptr); if( poAttr ) { size_t idx = 0; for( const auto& subItem: array ) { const GUInt64 arrayStartIdx = idx; const size_t count = 1; const GInt64 arrayStep = 0; const GPtrDiff_t bufferStride = 0; const auto subItemType = subItem.GetType(); if( subItemType == CPLJSONObject::Type::String ) { const std::string str = subItem.ToString(); const char* c_str = str.c_str(); poAttr->Write(&arrayStartIdx, &count, &arrayStep, &bufferStride, poAttr->GetDataType(), &c_str); } else if( subItemType == CPLJSONObject::Type::Integer || subItemType == CPLJSONObject::Type::Long || subItemType == CPLJSONObject::Type::Double ) { const double val = subItem.ToDouble(); poAttr->Write(&arrayStartIdx, &count, &arrayStep, &bufferStride, GDALExtendedDataType::Create(GDT_Float64), &val); } ++idx; } } } } if( !bDone ) { constexpr size_t nMaxStringLength = 0; const auto eDT = GDALExtendedDataType::CreateString(nMaxStringLength, GEDTST_JSON); poAttr = m_oGroup.CreateAttribute( item.GetName(), {}, eDT, nullptr); if( poAttr ) { const GUInt64 arrayStartIdx = 0; const size_t count = 1; const GInt64 arrayStep = 0; const GPtrDiff_t bufferStride = 0; const std::string str = item.ToString(); const char* c_str = str.c_str(); poAttr->Write(&arrayStartIdx, &count, &arrayStep, &bufferStride, poAttr->GetDataType(), &c_str); } } auto poMemAttr = std::dynamic_pointer_cast<MEMAttribute>(poAttr); if( poMemAttr ) poMemAttr->SetModified(false); } SetUpdatable(bUpdatable); } /************************************************************************/ /* ZarrAttributeGroup::Serialize() */ /************************************************************************/ CPLJSONObject ZarrAttributeGroup::Serialize() const { CPLJSONObject o; const auto attrs = m_oGroup.GetAttributes(nullptr); for( const auto& attr: attrs ) { const auto oType = attr->GetDataType(); if( oType.GetClass() == GEDTC_STRING ) { const auto anDims = attr->GetDimensionsSize(); if( anDims.size() == 0 ) { const char* pszStr = attr->ReadAsString(); if( pszStr ) { CPLJSONDocument oDoc; if( oType.GetSubType() == GEDTST_JSON && oDoc.LoadMemory(pszStr) ) { o.Add(attr->GetName(), oDoc.GetRoot()); } else { o.Add(attr->GetName(), pszStr); } } else { o.AddNull(attr->GetName()); } } else if ( anDims.size() == 1 ) { const auto list = attr->ReadAsStringArray(); CPLJSONArray arr; for( int i = 0; i < list.size(); ++i ) { arr.Add(list[i]); } o.Add(attr->GetName(), arr); } else { CPLError(CE_Warning, CPLE_AppDefined, "Cannot serialize attribute %s of dimension count >= 2", attr->GetName().c_str()); } } else if( oType.GetClass() == GEDTC_NUMERIC ) { const auto anDims = attr->GetDimensionsSize(); const auto eDT = oType.GetNumericDataType(); if( anDims.size() == 0 ) { const double dfVal = attr->ReadAsDouble(); if( eDT == GDT_Byte || eDT == GDT_UInt16 || eDT == GDT_UInt32 || eDT == GDT_Int16 || eDT == GDT_Int32 ) { o.Add(attr->GetName(), static_cast<GInt64>(dfVal)); } else { o.Add(attr->GetName(), dfVal); } } else if ( anDims.size() == 1 ) { const auto list = attr->ReadAsDoubleArray(); CPLJSONArray arr; for( const auto dfVal: list ) { if( eDT == GDT_Byte || eDT == GDT_UInt16 || eDT == GDT_UInt32 || eDT == GDT_Int16 || eDT == GDT_Int32 ) { arr.Add(static_cast<GInt64>(dfVal)); } else { arr.Add(dfVal); } } o.Add(attr->GetName(), arr); } else { CPLError(CE_Warning, CPLE_AppDefined, "Cannot serialize attribute %s of dimension count >= 2", attr->GetName().c_str()); } } } return o; }
39.068862
95
0.406085
[ "object" ]
bc06c983d5049d1c3058d389967403f06e2d6f45
4,863
cpp
C++
dep/skse/skse/GameThreads.cpp
Verteiron/JContainers
a5c83198c782458a7c2ae683319558cc88959d25
[ "MIT" ]
1
2018-07-30T21:36:28.000Z
2018-07-30T21:36:28.000Z
dep/skse/skse/GameThreads.cpp
Verteiron/JContainers
a5c83198c782458a7c2ae683319558cc88959d25
[ "MIT" ]
null
null
null
dep/skse/skse/GameThreads.cpp
Verteiron/JContainers
a5c83198c782458a7c2ae683319558cc88959d25
[ "MIT" ]
1
2021-03-03T06:28:53.000Z
2021-03-03T06:28:53.000Z
#include "GameThreads.h" #include "GameAPI.h" #include "GameReferences.h" #include "GameData.h" #include "GameForms.h" #include "GameRTTI.h" #include "NiNodes.h" #include "common/IMemPool.h" IThreadSafeBasicMemPool<SKSETaskUpdateTintMasks,10> s_updateTintMasksDelegatePool; IThreadSafeBasicMemPool<SKSETaskUpdateHairColor,10> s_updateHairColorDelegatePool; IThreadSafeBasicMemPool<SKSETaskUpdateWeight,10> s_updateWeightDelegatePool; IThreadSafeBasicMemPool<SKSETaskRegenHead,10> s_regenHeadDelegatePool; IThreadSafeBasicMemPool<SKSETaskChangeHeadPart,10> s_changeHeadPartDelegatePool; void BSTaskPool::UpdateTintMasks() { SKSETaskUpdateTintMasks * cmd = s_updateTintMasksDelegatePool.Allocate(); if(cmd) { QueueTask(cmd); } } void BSTaskPool::UpdateHairColor() { SKSETaskUpdateHairColor * cmd = s_updateHairColorDelegatePool.Allocate(); if(cmd) { QueueTask(cmd); } } void BSTaskPool::RegenerateHead(Actor * actor) { SKSETaskRegenHead * cmd = SKSETaskRegenHead::Create(actor); if(cmd) { QueueTask(cmd); } } void BSTaskPool::ChangeHeadPart(Actor * actor, BGSHeadPart * oldPart, BGSHeadPart * newPart) { SKSETaskChangeHeadPart * cmd = SKSETaskChangeHeadPart::Create(actor, oldPart, newPart); if(cmd) { QueueTask(cmd); } } void BSTaskPool::UpdateWeight(Actor * actor, float delta) { SKSETaskUpdateWeight * cmd = SKSETaskUpdateWeight::Create(actor, delta); if(cmd) { QueueTask(cmd); } } void SKSETaskUpdateTintMasks::Dispose(void) { s_updateTintMasksDelegatePool.Free(this); } void SKSETaskUpdateTintMasks::Run() { (*g_thePlayer)->UpdateSkinColor(); UpdatePlayerTints(); } void SKSETaskUpdateHairColor::Run() { (*g_thePlayer)->UpdateHairColor(); } void SKSETaskUpdateHairColor::Dispose(void) { s_updateHairColorDelegatePool.Free(this); } SKSETaskRegenHead * SKSETaskRegenHead::Create(Actor * actor) { SKSETaskRegenHead * cmd = s_regenHeadDelegatePool.Allocate(); if (cmd) { cmd->m_actor = actor; } return cmd; } void SKSETaskRegenHead::Dispose(void) { s_regenHeadDelegatePool.Free(this); } void SKSETaskRegenHead::Run() { TESNPC * npc = DYNAMIC_CAST(m_actor->baseForm, TESForm, TESNPC); BSFaceGenNiNode * faceNode = m_actor->GetFaceGenNiNode(); BGSHeadPart * facePart = NULL; if(CALL_MEMBER_FN(npc, HasOverlays)()) { facePart = npc->GetHeadPartOverlayByType(BGSHeadPart::kTypeFace); } else { facePart = CALL_MEMBER_FN(npc, GetHeadPartByType)(BGSHeadPart::kTypeFace); } if(npc && faceNode && facePart) { CALL_MEMBER_FN(FaceGen::GetSingleton(), RegenerateHead)(faceNode, facePart, npc); } } SKSETaskChangeHeadPart * SKSETaskChangeHeadPart::Create(Actor * actor, BGSHeadPart* oldPart, BGSHeadPart* newPart) { SKSETaskChangeHeadPart * cmd = s_changeHeadPartDelegatePool.Allocate(); if (cmd) { cmd->m_actor = actor; cmd->m_newPart = newPart; cmd->m_oldPart = oldPart; } return cmd; } void SKSETaskChangeHeadPart::Dispose(void) { s_changeHeadPartDelegatePool.Free(this); } void SKSETaskChangeHeadPart::Run() { if(m_actor) { ChangeActorHeadPart(m_actor, m_oldPart, m_newPart); } } SKSETaskUpdateWeight * SKSETaskUpdateWeight::Create(Actor * actor, float delta) { SKSETaskUpdateWeight * cmd = s_updateWeightDelegatePool.Allocate(); if (cmd) { cmd->m_actor = actor; cmd->m_delta = delta; } return cmd; } void SKSETaskUpdateWeight::Dispose(void) { s_updateWeightDelegatePool.Free(this); } void SKSETaskUpdateWeight::Run() { if(m_actor) { TESNPC * npc = DYNAMIC_CAST(m_actor->baseForm, TESForm, TESNPC); if(npc) { BSFaceGenNiNode * faceNode = m_actor->GetFaceGenNiNode(); CALL_MEMBER_FN(faceNode, AdjustHeadMorph)(BSFaceGenNiNode::kAdjustType_Neck, 0, m_delta); UpdateModelFace(faceNode); ActorWeightModel * lowModel = m_actor->GetWeightModel(ActorWeightModel::kWeightModel_Small); if(lowModel && lowModel->weightData) CALL_MEMBER_FN(lowModel->weightData, UpdateWeightData)(); ActorWeightModel * highModel = m_actor->GetWeightModel(ActorWeightModel::kWeightModel_Large); if(highModel && highModel->weightData) CALL_MEMBER_FN(highModel->weightData, UpdateWeightData)(); UInt32 updateFlags = ActorEquipData::kFlags_Unk01 | ActorEquipData::kFlags_Unk02 | ActorEquipData::kFlags_Unk03 | ActorEquipData::kFlags_Mobile; // Resets ActorState //updateFlags |= ActorEquipData::kFlags_DrawHead | ActorEquipData::kFlags_Reset; CALL_MEMBER_FN(m_actor->equipData, SetEquipFlag)(updateFlags); CALL_MEMBER_FN(m_actor->equipData, UpdateEquipment)(m_actor); // Force redraw weapon, weight model update causes weapon position to be reset // Looking at DrawSheatheWeapon there is a lot of stuff going on, hard to find // out how to just manually move the weapon to its intended position if(m_actor->actorState.IsWeaponDrawn()) { m_actor->DrawSheatheWeapon(false); m_actor->DrawSheatheWeapon(true); } } } }
26.286486
147
0.761875
[ "model" ]
bc0c63f340dfcf7ee9c185b68be428bf63243f85
833
hpp
C++
include/disccord/models/embed_field.hpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
44
2016-09-19T15:28:25.000Z
2018-08-09T13:17:40.000Z
include/disccord/models/embed_field.hpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
44
2016-11-03T17:27:30.000Z
2017-12-10T16:17:31.000Z
include/disccord/models/embed_field.hpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
13
2016-11-01T00:17:20.000Z
2018-08-03T19:51:16.000Z
#ifndef _embed_field_hpp_ #define _embed_field_hpp_ #include <disccord/models/entity.hpp> namespace disccord { namespace models { class embed_field : public model { public: embed_field(); virtual ~embed_field(); virtual void decode(web::json::value json) override; std::string get_name(); std::string get_value(); util::optional<bool> get_inline(); protected: virtual void encode_to( std::unordered_map<std::string, web::json::value> &info ) override; private: std::string name, value; util::optional<bool> _inline; //inline is keyword }; } } #endif /* _embed_field_hpp_ */
23.8
75
0.522209
[ "model" ]
bc19b7347bfee08f8cf5db0858974038da8581ff
3,580
cpp
C++
dali/internal/event/object/custom-object-internal.cpp
pwisbey/dali-core
53117f5d4178001b0d688c5bce14d7bf8e861631
[ "Apache-2.0" ]
1
2016-08-05T09:58:38.000Z
2016-08-05T09:58:38.000Z
dali/internal/event/object/custom-object-internal.cpp
tizenorg/platform.core.uifw.dali-core
dd89513b4bb1fdde74a83996c726e10adaf58349
[ "Apache-2.0" ]
null
null
null
dali/internal/event/object/custom-object-internal.cpp
tizenorg/platform.core.uifw.dali-core
dd89513b4bb1fdde74a83996c726e10adaf58349
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/event/object/custom-object-internal.h> // INTERNAL INCLUDES #include <dali/internal/event/common/stage-impl.h> #include <dali/internal/update/common/animatable-property.h> #include <dali/internal/update/common/property-owner.h> #include <dali/internal/update/manager/update-manager.h> #include <dali/internal/update/animation/scene-graph-constraint-base.h> using Dali::Internal::SceneGraph::PropertyOwner; using Dali::Internal::SceneGraph::PropertyBase; using Dali::Internal::SceneGraph::UpdateManager; using Dali::Internal::SceneGraph::AnimatableProperty; namespace Dali { namespace Internal { CustomObject* CustomObject::New() { return new CustomObject(); } const SceneGraph::PropertyOwner* CustomObject::GetSceneObject() const { return mUpdateObject; } const PropertyBase* CustomObject::GetSceneObjectAnimatableProperty( Property::Index index ) const { CustomPropertyMetadata* custom = FindCustomProperty( index ); DALI_ASSERT_ALWAYS( custom && "Property index is invalid" ); return custom->GetSceneGraphProperty(); } const PropertyInputImpl* CustomObject::GetSceneObjectInputProperty( Property::Index index ) const { return GetSceneObjectAnimatableProperty( index ); } unsigned int CustomObject::GetDefaultPropertyCount() const { return 0u; } void CustomObject::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const { } const char* CustomObject::GetDefaultPropertyName( Property::Index index ) const { return NULL; } Property::Index CustomObject::GetDefaultPropertyIndex(const std::string& name) const { return Property::INVALID_INDEX; } bool CustomObject::IsDefaultPropertyWritable(Property::Index index) const { return false; } bool CustomObject::IsDefaultPropertyAnimatable(Property::Index index) const { return false; } bool CustomObject::IsDefaultPropertyAConstraintInput( Property::Index index ) const { return false; } Property::Type CustomObject::GetDefaultPropertyType(Property::Index index) const { return Property::NONE; } void CustomObject::SetDefaultProperty( Property::Index index, const Property::Value& property ) { // do nothing } Property::Value CustomObject::GetDefaultProperty(Property::Index index) const { return Property::Value(); } CustomObject::~CustomObject() { // Guard to allow handle destruction after Core has been destroyed if( Stage::IsInstalled() ) { if( NULL != mUpdateObject ) { RemoveObjectMessage( GetEventThreadServices().GetUpdateManager(), mUpdateObject ); mUpdateObject = NULL; // object is about to be destroyed } } } CustomObject::CustomObject() { PropertyOwner* updateObject = PropertyOwner::New(); // Pass ownership to the update-thread AddObjectMessage( GetEventThreadServices().GetUpdateManager(), updateObject ); // Keep as const since this should only be modified from update-thread mUpdateObject = updateObject; } } // namespace Internal } // namespace Dali
26.131387
97
0.763687
[ "object" ]
bc308b1123421e07c5c853324bbfa81f741188b7
5,289
cpp
C++
src/App/AppCart.cpp
jlcrodrigues/feup-aed
9586e984cd725292c7d76645b146ec969f788e19
[ "MIT" ]
7
2021-12-22T21:57:38.000Z
2022-01-05T18:08:17.000Z
src/App/AppCart.cpp
jlcrodrigues/feup-aed
9586e984cd725292c7d76645b146ec969f788e19
[ "MIT" ]
null
null
null
src/App/AppCart.cpp
jlcrodrigues/feup-aed
9586e984cd725292c7d76645b146ec969f788e19
[ "MIT" ]
1
2021-12-23T00:35:06.000Z
2021-12-23T00:35:06.000Z
#include "App.h" void App::cart() { if (command.empty()) { cout << "Invalid option. Use help cart to see available commands.\n"; } else if (command.front() == "display") { command.pop(); displayCart(); } else if (command.front() == "add") { command.pop(); addCart(); } else if (command.front() == "edit") { command.pop(); editCart(); } else if (command.front() == "remove") { command.pop(); removeCart(); } else if (command.front() == "find") { command.pop(); findCart(); } else if (command.front() == "assign") { command.pop(); assignCart(); } else cout << "Invalid option. Use help cart for more info.\n"; } void App::displayCart() { int page; vector<Cart> carts = airline.getCarts(); if (carts.size() == 0) { cout << "No carts to display.\n"; return; } vector<vector<string> > table; table.push_back({"Id", "Carriages", "Piles", "Pile Size", "Occupation", "Flight"}); if (command.empty()) page = 0; else if (!readNumber(page, command.front())) { cout << "Page must be a number. Please try again.\n"; return; } for (auto & c: carts) { string flight = to_string(c.getFlight()); if (flight == "0") flight = "None"; table.push_back({to_string(c.getId()), to_string(c.getCarriages()), to_string(c.getPiles()), to_string(c.getPileSize()), to_string(c.getOccupation()) + "%", flight}); } displayTable(table, page); } void App::addCart() { int id, carriages, piles, pile_size; string number; vector<string> aux = {"Number of carriages: ", "Number of piles: ", "Number of piles: "}; vector<int> dimensions(3, 0); if (command.empty()) { cout << "Usage:\n cart add 'id'\n"; return; } if (!readNumber(id, command.front())) { cout << "Invalid id. Please try again.\n"; return; } command.pop(); if (airline.checkCart(id)) { cout << "Cart " << id << " already exists. Maybe you want to try:\n cart edit 'id'\n"; return; } for (int i = 0; i < 3; i++) { do { cout << aux[i]; cin >> number; clearStream(); } while(!readNumber(dimensions[i], number)); } airline.addCart({id, dimensions[0], dimensions[1], dimensions[2]}); } void App::editCart() { int id, carriages, piles, pile_size; string number; vector<string> aux = {"Number of carriages: ", "Number of piles: ", "Number of piles: "}; vector<int> dimensions(3, 0); if (command.empty()) { cout << "Usage:\n cart edit 'id'\n"; return; } if (!readNumber(id, command.front())) { cout << "Invalid id. Please try again.\n"; return; } command.pop(); if (!airline.removeCart(id)) { cout << "Cart " << id << " does not exist. Adding a new one.\n"; } for (int i = 0; i < 3; i++) { do { cout << aux[i]; cin >> number; clearStream(); } while(!readNumber(dimensions[i], number)); } airline.addCart({id, dimensions[0], dimensions[1], dimensions[2]}); } void App::removeCart() { int id; if (command.empty()) { cout << "Usage:\n cart remove 'id'\n"; return; } if (!readNumber(id, command.front())) { cout << "Invalid id. Please try again.\n"; return; } if (airline.removeCart(id)) { cout << "Cart " << id << " was removed.\n"; } else cout << "That cart doesn't exist.\n"; } void App::findCart() { int id; if (command.empty()) { cout << "Usage:\n cart find 'id'\n"; return; } if (!readNumber(id, command.front())) { cout << "Invalid id. Please try again.\n"; return; } if (airline.checkCart(id)) { Cart* cart = airline.findCart(id); cout << "Id: " << cart->getId() << "\nCarriages. " << cart->getCarriages(); cout << "\nNumber of piles: " << cart->getPiles() << "\nBags per pile: "; cout << cart->getPileSize() << "\nAssigned flight: "; if (cart->getFlight() == 0) cout << "None\n"; else cout << cart->getFlight() << '\n'; } else cout << "Cart not found.\n"; } void App::assignCart() { int id, flight_id; if (command.empty()) { cout << "Usage:\n cart assign 'id' 'flight_id'\n"; return; } if (!readNumber(id, command.front())) { cout << "Invalid id. Please try again.\n"; return; } if (!airline.checkCart(id)) { cout << "That cart doesn't exist. Use cart display to see available carts.\n"; return; } command.pop(); if (!readNumber(flight_id, command.front())) { cout << "Invalid id. Please try again.\n"; return; } if (!airline.checkFlight(flight_id)) { cout << "That flight doesn't exist. Use flight display to see available flights.\n"; return; } Cart* cart = airline.findCart(id); if (cart->getFlight() != 0) { cout << "Cart " << id << " is already assigned to a flight.\n"; } else { airline.assignCartFlight(id, flight_id); cout << "Cart " << id << " was assigned to flight " << flight_id << ".\n"; } }
23.824324
93
0.532993
[ "vector" ]
bc360624534b6d58993727e1fea2a27babbf087a
3,799
cpp
C++
test/zoneserver.test/FieldTest.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
test/zoneserver.test/FieldTest.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
test/zoneserver.test/FieldTest.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
#include "ZoneServerTestPCH.h" #include "GameTestFixture.h" #include "MockPlayerController.h" #include "MockPlayerMoveController.h" #include "ZoneServer/model/gameobject/Player.h" /** * @class FieldTest * * 필드 상에서의 캐릭터 이동 및 채팅 테스트 */ class FieldTest : public GameTestFixture { }; TEST_F(FieldTest, testGoToward) { ObjectPosition position = player1_->getPosition(); position.x_ = position.x_ + 1.0f; playerMoveController1_->goToward(position); ASSERT_EQ(1, playerMoveController1_->getCallCount("evEntityGoneToward")); ASSERT_EQ(1, playerMoveController2_->getCallCount("evEntityGoneToward")); const UnionEntityInfo& creatureInfo1 = player1_->getUnionEntityInfo(); ASSERT_EQ(true, creatureInfo1.asEntityMovementInfo().isMoving_); ASSERT_FLOAT_EQ(position.x_, creatureInfo1.asEntityMovementInfo().destination_.x_); } TEST_F(FieldTest, testMove) { ObjectPosition position = player1_->getPosition(); position.x_ = position.x_ + 1.0f; playerMoveController1_->move(position); ASSERT_EQ(1, playerMoveController1_->getCallCount("evEntityMoved")); ASSERT_EQ(1, playerMoveController2_->getCallCount("evEntityMoved")); const UnionEntityInfo& creatureInfo1 = player1_->getUnionEntityInfo(); ASSERT_EQ(false, creatureInfo1.asEntityMovementInfo().isMoving_); ASSERT_FLOAT_EQ(position.x_, creatureInfo1.asCharacterInfo().position_.x_); } TEST_F(FieldTest, testStop) { ObjectPosition position = player1_->getPosition(); position.x_ = position.x_ + 1.0f; playerMoveController1_->goToward(position); playerMoveController1_->stop(position); ASSERT_EQ(1, playerMoveController1_->getCallCount("evEntityStopped")); ASSERT_EQ(1, playerMoveController2_->getCallCount("evEntityStopped")); const UnionEntityInfo& creatureInfo1 = player1_->getUnionEntityInfo(); ASSERT_EQ(false, creatureInfo1.asEntityMovementInfo().isMoving_); ASSERT_FLOAT_EQ(position.x_, creatureInfo1.asEntityMovementInfo().destination_.x_); ASSERT_FLOAT_EQ(position.x_, creatureInfo1.asCharacterInfo().position_.x_); } TEST_F(FieldTest, testTurn) { playerMoveController1_->turn(12); ASSERT_EQ(1, playerMoveController1_->getCallCount("evEntityTurned")); ASSERT_EQ(1, playerMoveController2_->getCallCount("evEntityTurned")); const UnionEntityInfo& creatureInfo1 = player1_->getUnionEntityInfo(); ASSERT_EQ(12, creatureInfo1.asCharacterInfo().position_.heading_); } TEST_F(FieldTest, testJump) { ObjectPosition position = player1_->getPosition(); position.x_ = position.x_ + 1.0f; playerMoveController1_->jump(position); ASSERT_EQ(1, playerMoveController1_->getCallCount("evEntityJumped")); ASSERT_EQ(1, playerMoveController2_->getCallCount("evEntityJumped")); const UnionEntityInfo& creatureInfo1 = player1_->getUnionEntityInfo(); ASSERT_EQ(false, creatureInfo1.asEntityMovementInfo().isMoving_); ASSERT_FLOAT_EQ(position.x_, creatureInfo1.asCharacterInfo().position_.x_); } TEST_F(FieldTest, testSay) { const ChatMessage msg(L"abc"); playerController1_->say(msg); ASSERT_EQ(1, playerController1_->getCallCount("evCreatureSaid")); ASSERT_EQ(1, playerController2_->getCallCount("evCreatureSaid")); } TEST_F(FieldTest, testSelectTarget) { playerController1_->selectTarget(GameObjectInfo(otPc, invalidObjectId)); ASSERT_EQ(1, playerController1_->getCallCount("onSelectTarget")); ASSERT_EQ(ecEntityNotFound, playerController1_->lastErrorCode_); playerController1_->selectTarget(GameObjectInfo(otPc, characterId2_)); ASSERT_EQ(2, playerController1_->getCallCount("onSelectTarget")); ASSERT_EQ(ecOk, playerController1_->lastErrorCode_); ASSERT_EQ(characterId2_, playerController1_->lastTargetInfo_.targetInfo_.objectId_); }
32.194915
87
0.765728
[ "model" ]
bc3a076e4f9fd8679999d14662fbfb0a760e1efe
10,113
cpp
C++
PSME/agent/compute/src/status/state_machine_action.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/agent/compute/src/status/state_machine_action.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/agent/compute/src/status/state_machine_action.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @brief Implementation of StateMachineAction class * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file state_machine_action.cpp */ #include "status/state_machine_action.hpp" #include "discovery/discovery_manager.hpp" #include "tree_stability/compute_tree_stabilizer.hpp" #include "agent-framework/module/compute_components.hpp" #include "agent-framework/module/common_components.hpp" #include "agent-framework/eventing/events_queue.hpp" using namespace agent::compute; using namespace agent_framework; using namespace agent_framework::state_machine; using namespace agent_framework::module; using agent_framework::state_machine::enums::State; using agent_framework::model::enums::Component; using agent_framework::state_machine::enums::Transition; using agent_framework::eventing::Notification; using agent_framework::module::CommonComponents; using agent_framework::module::ComputeComponents; namespace { bool is_notification_required(const Transition trans) { switch (trans) { case Transition::CAME_UP: case Transition::WENT_DOWN: case Transition::STARTED: case Transition::DISCOVERY_UP: case Transition::EXTRACTION: case Transition::INSERTION: return true; case Transition::IDLE: case Transition::DISCOVERY_MISSING: case Transition::DISCOVERY_DOWN: case Transition::DID_NOT_START: case Transition::SLOW_INSERTION: default: return false; } } Notification select_notification_for_came_up(bool was_discovered) { if (was_discovered) { return Notification::Update; } else { return Notification::Add; } } Notification select_notification(const Transition trans, bool was_discovered) { switch (trans) { case Transition::CAME_UP: return select_notification_for_came_up(was_discovered); case Transition::WENT_DOWN: return Notification::Update; case Transition::STARTED: case Transition::DISCOVERY_UP: case Transition::INSERTION: return Notification::Add; case Transition::EXTRACTION: return Notification::Remove; case Transition::IDLE: case Transition::DISCOVERY_MISSING: case Transition::DISCOVERY_DOWN: case Transition::DID_NOT_START: case Transition::SLOW_INSERTION: default: // this should never happen assert(false); return Notification::Update; } } void send_event(const std::string& module, const std::string& parent, Component type, Notification notification) { ::agent_framework::eventing::EventData edat; edat.set_parent(parent); edat.set_component(module); edat.set_type(type); edat.set_notification(notification); ::agent_framework::eventing::EventsQueue::get_instance()->push_back(edat); log_info(GET_LOGGER("agent"), "Sending an event for component " << edat.get_component() << "," << "(" << edat.get_type() << ")" << ", notification type: " << edat.get_notification()); } void remove_processors(const string& system_uuid) { auto& pm = ComputeComponents::get_instance()->get_processor_manager(); pm.remove_by_parent(system_uuid); } void remove_memory_modules(const string& system_uuid) { auto& mm = ComputeComponents::get_instance()->get_memory_manager(); mm.remove_by_parent(system_uuid); } void remove_network_interfaces(const string& system_uuid) { auto& nicm = ComputeComponents::get_instance()-> get_network_interface_manager(); nicm.remove_by_parent(system_uuid); } void remove_storage_subsystems(const string& system_uuid) { auto& ssm = CommonComponents::get_instance()-> get_storage_subsystem_manager(); auto& scm = ComputeComponents::get_instance()-> get_storage_controller_manager(); for (const auto& subsystem_uuid : ssm.get_keys(system_uuid)) { scm.remove_by_parent(subsystem_uuid); } ssm.remove_by_parent(system_uuid); } void remove_network_devices(const string& system_uuid) { auto& ndm = ComputeComponents::get_instance()-> get_network_device_manager(); auto& ndfm = ComputeComponents::get_instance()-> get_network_device_function_manager(); for (const auto& device_uuid : ndm.get_keys(system_uuid)) { ndfm.remove_by_parent(device_uuid); } ndm.remove_by_parent(system_uuid); } void remove_systems(const string& manager_uuid) { auto& sm = CommonComponents::get_instance()->get_system_manager(); auto system_keys = sm.get_keys(manager_uuid); for (const auto& key: system_keys) { remove_processors(key); remove_memory_modules(key); remove_network_interfaces(key); remove_storage_subsystems(key); remove_network_devices(key); } sm.remove_by_parent(manager_uuid); for (const auto& key: system_keys) { // sending delete events for systems send_event(key, manager_uuid, Component::System, Notification::Remove); } } void update_status(const string& manager_uuid, model::enums::State state, bool was_discovered) { auto& chm = CommonComponents::get_instance()->get_chassis_manager(); auto chassis_keys = chm.get_keys(manager_uuid); for (const auto& key : chassis_keys) { auto chassis = chm.get_entry_reference(key); auto status = chassis->get_status(); status.set_state(state); chassis->set_status(status); // sending update events for chassis if (was_discovered) { send_event(key, manager_uuid, Component::Chassis, Notification::Update); } else { send_event(key, manager_uuid, Component::Chassis, Notification::Add); } } auto& mm = CommonComponents::get_instance()->get_module_manager(); auto manager = mm.get_entry_reference(manager_uuid); auto status = manager->get_status(); status.set_state(state); manager->set_status(status); } void generate_systems_add_event(const std::string& module) { auto& sm = CommonComponents::get_instance()->get_system_manager(); auto system_keys = sm.get_keys(module); // Sending add events for systems for (const auto& key : system_keys) { send_event(key, module, Component::System, Notification::Add); } } const std::string randomize_module_uuid(const std::string& module_uuid) { auto& chassis_manager = CommonComponents::get_instance()->get_chassis_manager(); auto& module_manager = CommonComponents::get_instance()->get_module_manager(); const auto& chassis_keys = chassis_manager.get_keys(module_uuid); if (chassis_keys.empty()) { throw std::runtime_error("No chassis found for module " + module_uuid); } const std::string module_random_uuid = module_manager.get_entry_reference(module_uuid)->make_random_uuid(); { auto chassis = chassis_manager.get_entry_reference(chassis_keys.front()); chassis->set_parent_uuid(module_random_uuid); chassis->make_random_uuid(); } return module_random_uuid; } } using agent_framework::discovery::Discovery; using DiscoveryUnique = std::unique_ptr<Discovery>; void StateMachineAction::execute(StateThreadEntrySharedPtr entry) { std::lock_guard<std::mutex> lock(m_mutex); auto module = entry->get_module(); auto state = entry->get_state(); auto trans = entry->get_transition(); bool was_discovered = entry->was_discovered(); log_debug(GET_LOGGER("agent"), "State machine action in module (UUID=" + module + "): after event " + trans.to_string() + ", current state is " + state.to_string()); { bool presence = (state == State::ENABLED || (state == State::UNAVAILABLE_OFFLINE && was_discovered)); CommonComponents::get_instance()->get_module_manager().get_entry_reference(module)->set_presence(presence); } switch (state) { case State::ENABLED: log_debug(GET_LOGGER("agent"), "\tAction: Discovery"); try { discovery::DiscoveryManager().discovery(module); module = ComputeTreeStabilizer().stabilize(module); entry->update_module(module); } catch (const std::runtime_error& e) { log_error(GET_LOGGER("agent"), e.what()); } update_status(module, model::enums::State::Enabled, was_discovered); generate_systems_add_event(module); entry->set_discovered(true); break; case State::ABSENT: case State::UNAVAILABLE_OFFLINE: if (enums::Transition::EXTRACTION == trans || enums::Transition::WENT_DOWN == trans) { log_debug(GET_LOGGER("agent"), "\tAction: Removing systems for manager"); update_status(module, model::enums::State::UnavailableOffline, was_discovered); remove_systems(module); } if (State::ABSENT == state) { entry->set_discovered(false); entry->update_module(randomize_module_uuid(module)); } break; case State::UNKNOWN: case State::STARTING: default: break; } // sending events for manager if (is_notification_required(trans)) { send_event(module, {}, Component::Manager, select_notification(trans, was_discovered)); } }
34.050505
115
0.679126
[ "model" ]
bc3ab2ff93bf2549855dab05dea1b0bd6aea064e
2,038
hpp
C++
model copy/boost/statistics/model/wrap/unary/covariate.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
model copy/boost/statistics/model/wrap/unary/covariate.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
model copy/boost/statistics/model/wrap/unary/covariate.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // statistics::model::wrap::unary::covariate.hpp // // // // Copyright 2009 Erwann Rogard. 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 BOOST_STATISTICS_MODEL_WRAP_UNARY_COVARIATE_HPP_ER_2009 #define BOOST_STATISTICS_MODEL_WRAP_UNARY_COVARIATE_HPP_ER_2009 #include <boost/statistics/model/wrap/unary/detail/base.hpp> namespace boost{ namespace statistics{ namespace model{ template<typename X> class covariate_wrapper : detail::base_<X>{ typedef detail::base_<X> base_; public: typedef X covariate_type; typedef covariate_wrapper<X> covariate_wrapper_type; // Construction covariate_wrapper(); covariate_wrapper(const X& x); covariate_wrapper(const covariate_wrapper&); // Access const X& covariate()const; }; // Implementation // template<typename X> covariate_wrapper<X>::covariate_wrapper() : base_(){} template<typename X> covariate_wrapper<X>::covariate_wrapper( const X& x ) : base_(x){} template<typename X> covariate_wrapper<X>::covariate_wrapper(const covariate_wrapper& that) :base_(that){} template<typename X> const X& covariate_wrapper<X>::covariate()const{ return (this->value); } // Free functions template<typename X> covariate_wrapper<X> make_covariate_wrapper(const X& x){ typedef covariate_wrapper<X> result_type; return result_type(x); } }// model }// statistics }// boost #endif
32.870968
79
0.546614
[ "model" ]
a4c6e6ff26b16bff65273f9b8f6ac5de100dec5f
2,530
cpp
C++
datasets/github_cpp_10/4/143.cpp
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2019-05-03T19:27:45.000Z
2019-05-03T19:27:45.000Z
datasets/github_cpp_10/4/143.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/github_cpp_10/4/143.cpp
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
#include <vector> #include <cstdlib> #include <iostream> #include <ctime> #include <algorithm> #include <functional> #include "merge_sort.h" using namespace std; template <typename T> void print_vector(vector<T>& v) { for (auto x : v) { cout << x << " "; } cout << endl; } void selection_sort_vector(vector<double>& v) { for (size_t i = 0; i < v.size(); i++) { auto min_value = v.at(i); auto min_index = i; for (size_t j = i+1; j < v.size(); j++) { if (v.at(j) < min_value) { min_value = v.at(j); min_index = j; } } swap(v.at(i), v.at(min_index)); } } void bubble_sort_vector(vector<double>& v) { bool swaps = true; while (swaps) { swaps = false; for (size_t j = 0; j < v.size()-1; j++) { if (v.at(j) < v.at(j+1)) { swap(v.at(j), v.at(j+1)); swaps = true; } } } } void insertion_sort_internet(vector<double>& v){ int j, temp; for (size_t i = 0; i < v.size(); i++){ j = i; while (j > 0 && v[j] < v[j-1]){ temp = v[j]; v[j] = v[j-1]; v[j-1] = temp; j--; } } } void insertion_sort_vector(vector<double>& v) { for (size_t i = 0; i < v.size(); i++) { auto j = i; while (j > 0 && v[j] < v[j-1]) { swap(v[j], v[j-1]); j--; } } } void std_sort(vector<double>& v) { std::sort(v.begin(), v.end()); } void insertion_sort(vector<double>& v) { for (auto i = begin(v); i != end(v); ++i) rotate(upper_bound(begin(v), i, *i), i, next(i)); } auto timeSize(int size, function<void(vector<double>&)> sort_type) { vector<double> v(size); srand(time(0)); for (auto& x : v) { x = rand() % (size * 5); } clock_t start; start = clock(); sort_type(v); auto duration = (clock() - start) / (double)(CLOCKS_PER_SEC / 1000); return duration; } int main() { for (int i = 2; i < 128; i+=2 ) { cout << "Size: " << i << " "; cout << "\t\tInsertion STL: "; double insertion_stl_time = timeSize(i, insertion_sort); cout << insertion_stl_time; cout << "\t\tInsertion Isaac: "; double insertion_isaac_time = timeSize(i, insertion_sort_vector); cout << insertion_isaac_time; cout << "\t\tMergeSort():"; double merge_sort_time = timeSize(i, mergeSort); cout << merge_sort_time; cout << "\t\tMergeSor2t():"; double merge_sort_time2 = timeSize(i, mergeSort2); cout << merge_sort_time2; cout << endl; } return 0; }
20.569106
71
0.532806
[ "vector" ]
a4c9949a51f6ef43b450e4aa69f81bbb7d5d17bb
19,951
cpp
C++
openstudiocore/src/model/AvailabilityManagerHybridVentilation.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
1
2016-12-29T08:45:03.000Z
2016-12-29T08:45:03.000Z
openstudiocore/src/model/AvailabilityManagerHybridVentilation.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
openstudiocore/src/model/AvailabilityManagerHybridVentilation.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "AvailabilityManagerHybridVentilation.hpp" #include "AvailabilityManagerHybridVentilation_Impl.hpp" #include "ThermalZone.hpp" #include "ThermalZone_Impl.hpp" #include "Schedule.hpp" #include "Schedule_Impl.hpp" #include "ScheduleDay.hpp" #include "ScheduleDay_Impl.hpp" #include "ScheduleRuleset.hpp" #include "ScheduleRuleset_Impl.hpp" #include "Curve.hpp" #include "Curve_Impl.hpp" #include "ScheduleTypeLimits.hpp" #include "ScheduleTypeRegistry.hpp" #include <utilities/idd/OS_AvailabilityManager_HybridVentilation_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include "../utilities/units/Unit.hpp" #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { AvailabilityManagerHybridVentilation_Impl::AvailabilityManagerHybridVentilation_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : AvailabilityManager_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == AvailabilityManagerHybridVentilation::iddObjectType()); } AvailabilityManagerHybridVentilation_Impl::AvailabilityManagerHybridVentilation_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : AvailabilityManager_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == AvailabilityManagerHybridVentilation::iddObjectType()); } AvailabilityManagerHybridVentilation_Impl::AvailabilityManagerHybridVentilation_Impl(const AvailabilityManagerHybridVentilation_Impl& other, Model_Impl* model, bool keepHandle) : AvailabilityManager_Impl(other,model,keepHandle) {} const std::vector<std::string>& AvailabilityManagerHybridVentilation_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType AvailabilityManagerHybridVentilation_Impl::iddObjectType() const { return AvailabilityManagerHybridVentilation::iddObjectType(); } std::vector<ScheduleTypeKey> AvailabilityManagerHybridVentilation_Impl::getScheduleTypeKeys(const Schedule& schedule) const { std::vector<ScheduleTypeKey> result; UnsignedVector fieldIndices = getSourceIndices(schedule.handle()); UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end()); if (std::find(b,e,OS_AvailabilityManager_HybridVentilationFields::VentilationControlModeSchedule) != e) { result.push_back(ScheduleTypeKey("AvailabilityManagerHybridVentilation","Ventilation Control Mode Schedule")); } if (std::find(b,e,OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorVentilationAirSchedule) != e) { result.push_back(ScheduleTypeKey("AvailabilityManagerHybridVentilation","Minimum Outdoor Ventilation Air Schedule")); } if (std::find(b,e,OS_AvailabilityManager_HybridVentilationFields::AirflowNetworkControlTypeSchedule) != e) { result.push_back(ScheduleTypeKey("AvailabilityManagerHybridVentilation","AirflowNetwork Control Type Schedule")); } if (std::find(b,e,OS_AvailabilityManager_HybridVentilationFields::SimpleAirflowControlTypeSchedule) != e) { result.push_back(ScheduleTypeKey("AvailabilityManagerHybridVentilation","Simple Airflow Control Type Schedule")); } return result; } boost::optional<ThermalZone> AvailabilityManagerHybridVentilation_Impl::controlledZone() const { return getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_AvailabilityManager_HybridVentilationFields::ControlledZone); } Schedule AvailabilityManagerHybridVentilation_Impl::ventilationControlModeSchedule() const { boost::optional<Schedule> value = optionalVentilationControlModeSchedule(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Ventilation Control Mode Schedule attached."); } return value.get(); } bool AvailabilityManagerHybridVentilation_Impl::useWeatherFileRainIndicators() const { boost::optional<std::string> value = getString(OS_AvailabilityManager_HybridVentilationFields::UseWeatherFileRainIndicators,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } double AvailabilityManagerHybridVentilation_Impl::maximumWindSpeed() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumWindSpeed,true); OS_ASSERT(value); return value.get(); } double AvailabilityManagerHybridVentilation_Impl::minimumOutdoorTemperature() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorTemperature,true); OS_ASSERT(value); return value.get(); } double AvailabilityManagerHybridVentilation_Impl::maximumOutdoorTemperature() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumOutdoorTemperature,true); OS_ASSERT(value); return value.get(); } double AvailabilityManagerHybridVentilation_Impl::minimumOutdoorEnthalpy() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorEnthalpy,true); OS_ASSERT(value); return value.get(); } double AvailabilityManagerHybridVentilation_Impl::maximumOutdoorEnthalpy() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumOutdoorEnthalpy,true); OS_ASSERT(value); return value.get(); } double AvailabilityManagerHybridVentilation_Impl::minimumOutdoorDewpoint() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorDewpoint,true); OS_ASSERT(value); return value.get(); } double AvailabilityManagerHybridVentilation_Impl::maximumOutdoorDewpoint() const { boost::optional<double> value = getDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumOutdoorDewpoint,true); OS_ASSERT(value); return value.get(); } Schedule AvailabilityManagerHybridVentilation_Impl::minimumOutdoorVentilationAirSchedule() const { auto result = getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorVentilationAirSchedule); OS_ASSERT(result); return result.get(); } boost::optional<Curve> AvailabilityManagerHybridVentilation_Impl::openingFactorFunctionofWindSpeedCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_AvailabilityManager_HybridVentilationFields::OpeningFactorFunctionofWindSpeedCurve); } bool AvailabilityManagerHybridVentilation_Impl::setControlledZone(const boost::optional<ThermalZone>& thermalZone) { bool result(false); if (thermalZone) { result = setPointer(OS_AvailabilityManager_HybridVentilationFields::ControlledZone, thermalZone.get().handle()); } else { resetControlledZone(); result = true; } return result; } void AvailabilityManagerHybridVentilation_Impl::resetControlledZone() { bool result = setString(OS_AvailabilityManager_HybridVentilationFields::ControlledZone, ""); OS_ASSERT(result); } bool AvailabilityManagerHybridVentilation_Impl::setVentilationControlModeSchedule(Schedule& schedule) { bool result = setSchedule(OS_AvailabilityManager_HybridVentilationFields::VentilationControlModeSchedule, "AvailabilityManagerHybridVentilation", "Ventilation Control Mode Schedule", schedule); return result; } void AvailabilityManagerHybridVentilation_Impl::setUseWeatherFileRainIndicators(bool useWeatherFileRainIndicators) { return setBooleanFieldValue(OS_AvailabilityManager_HybridVentilationFields::UseWeatherFileRainIndicators, useWeatherFileRainIndicators); } bool AvailabilityManagerHybridVentilation_Impl::setMaximumWindSpeed(double maximumWindSpeed) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumWindSpeed, maximumWindSpeed); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMinimumOutdoorTemperature(double minimumOutdoorTemperature) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorTemperature, minimumOutdoorTemperature); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMaximumOutdoorTemperature(double maximumOutdoorTemperature) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumOutdoorTemperature, maximumOutdoorTemperature); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMinimumOutdoorEnthalpy(double minimumOutdoorEnthalpy) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorEnthalpy, minimumOutdoorEnthalpy); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMaximumOutdoorEnthalpy(double maximumOutdoorEnthalpy) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumOutdoorEnthalpy, maximumOutdoorEnthalpy); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMinimumOutdoorDewpoint(double minimumOutdoorDewpoint) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorDewpoint, minimumOutdoorDewpoint); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMaximumOutdoorDewpoint(double maximumOutdoorDewpoint) { bool result = setDouble(OS_AvailabilityManager_HybridVentilationFields::MaximumOutdoorDewpoint, maximumOutdoorDewpoint); return result; } bool AvailabilityManagerHybridVentilation_Impl::setMinimumOutdoorVentilationAirSchedule(Schedule& schedule) { bool result = setSchedule(OS_AvailabilityManager_HybridVentilationFields::MinimumOutdoorVentilationAirSchedule, "AvailabilityManagerHybridVentilation", "Minimum Outdoor Ventilation Air Schedule", schedule); return result; } bool AvailabilityManagerHybridVentilation_Impl::setOpeningFactorFunctionofWindSpeedCurve(const boost::optional<Curve>& curve) { bool result(false); if (curve) { result = setPointer(OS_AvailabilityManager_HybridVentilationFields::OpeningFactorFunctionofWindSpeedCurve, curve.get().handle()); } else { resetOpeningFactorFunctionofWindSpeedCurve(); result = true; } return result; } void AvailabilityManagerHybridVentilation_Impl::resetOpeningFactorFunctionofWindSpeedCurve() { bool result = setString(OS_AvailabilityManager_HybridVentilationFields::OpeningFactorFunctionofWindSpeedCurve, ""); OS_ASSERT(result); } boost::optional<Schedule> AvailabilityManagerHybridVentilation_Impl::optionalVentilationControlModeSchedule() const { return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_AvailabilityManager_HybridVentilationFields::VentilationControlModeSchedule); } } // detail AvailabilityManagerHybridVentilation::AvailabilityManagerHybridVentilation(const Model& model) : AvailabilityManager(AvailabilityManagerHybridVentilation::iddObjectType(),model) { OS_ASSERT(getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()); { ScheduleRuleset schedule(model); schedule.defaultDaySchedule().addValue(Time(0,24,0,0),1.0); setVentilationControlModeSchedule(schedule); } { ScheduleRuleset schedule(model); schedule.defaultDaySchedule().addValue(Time(0,24,0,0),0.0); setMinimumOutdoorVentilationAirSchedule(schedule); } setUseWeatherFileRainIndicators(true); setMaximumWindSpeed(40.0); setMinimumOutdoorTemperature(20.0); setMaximumOutdoorTemperature(30.0); setMinimumOutdoorEnthalpy(20000.0); setMaximumOutdoorEnthalpy(30000.0); setMinimumOutdoorDewpoint(15.0); setMaximumOutdoorDewpoint(30.0); } AvailabilityManagerHybridVentilation::AvailabilityManagerHybridVentilation(const Model& model, Schedule& ventilationControlModeSchedule, Schedule& minimumOutdoorVentilationAirSchedule) : AvailabilityManager(AvailabilityManagerHybridVentilation::iddObjectType(),model) { OS_ASSERT(getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()); setVentilationControlModeSchedule(ventilationControlModeSchedule); setMinimumOutdoorVentilationAirSchedule(minimumOutdoorVentilationAirSchedule); setUseWeatherFileRainIndicators(true); setMaximumWindSpeed(40.0); setMinimumOutdoorTemperature(-100.0); setMaximumOutdoorTemperature(100.0); setMinimumOutdoorEnthalpy(0.0); setMaximumOutdoorEnthalpy(300000.0); setMinimumOutdoorDewpoint(-100.0); setMaximumOutdoorDewpoint(100.0); } IddObjectType AvailabilityManagerHybridVentilation::iddObjectType() { return IddObjectType(IddObjectType::OS_AvailabilityManager_HybridVentilation); } boost::optional<ThermalZone> AvailabilityManagerHybridVentilation::controlledZone() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->controlledZone(); } Schedule AvailabilityManagerHybridVentilation::ventilationControlModeSchedule() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->ventilationControlModeSchedule(); } bool AvailabilityManagerHybridVentilation::useWeatherFileRainIndicators() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->useWeatherFileRainIndicators(); } double AvailabilityManagerHybridVentilation::maximumWindSpeed() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->maximumWindSpeed(); } double AvailabilityManagerHybridVentilation::minimumOutdoorTemperature() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->minimumOutdoorTemperature(); } double AvailabilityManagerHybridVentilation::maximumOutdoorTemperature() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->maximumOutdoorTemperature(); } double AvailabilityManagerHybridVentilation::minimumOutdoorEnthalpy() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->minimumOutdoorEnthalpy(); } double AvailabilityManagerHybridVentilation::maximumOutdoorEnthalpy() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->maximumOutdoorEnthalpy(); } double AvailabilityManagerHybridVentilation::minimumOutdoorDewpoint() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->minimumOutdoorDewpoint(); } double AvailabilityManagerHybridVentilation::maximumOutdoorDewpoint() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->maximumOutdoorDewpoint(); } Schedule AvailabilityManagerHybridVentilation::minimumOutdoorVentilationAirSchedule() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->minimumOutdoorVentilationAirSchedule(); } boost::optional<Curve> AvailabilityManagerHybridVentilation::openingFactorFunctionofWindSpeedCurve() const { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->openingFactorFunctionofWindSpeedCurve(); } bool AvailabilityManagerHybridVentilation::setControlledZone(const ThermalZone& thermalZone) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setControlledZone(thermalZone); } void AvailabilityManagerHybridVentilation::resetControlledZone() { getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->resetControlledZone(); } bool AvailabilityManagerHybridVentilation::setVentilationControlModeSchedule(Schedule& schedule) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setVentilationControlModeSchedule(schedule); } void AvailabilityManagerHybridVentilation::setUseWeatherFileRainIndicators(bool useWeatherFileRainIndicators) { getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setUseWeatherFileRainIndicators(useWeatherFileRainIndicators); } bool AvailabilityManagerHybridVentilation::setMaximumWindSpeed(double maximumWindSpeed) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMaximumWindSpeed(maximumWindSpeed); } bool AvailabilityManagerHybridVentilation::setMinimumOutdoorTemperature(double minimumOutdoorTemperature) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMinimumOutdoorTemperature(minimumOutdoorTemperature); } bool AvailabilityManagerHybridVentilation::setMaximumOutdoorTemperature(double maximumOutdoorTemperature) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMaximumOutdoorTemperature(maximumOutdoorTemperature); } bool AvailabilityManagerHybridVentilation::setMinimumOutdoorEnthalpy(double minimumOutdoorEnthalpy) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMinimumOutdoorEnthalpy(minimumOutdoorEnthalpy); } bool AvailabilityManagerHybridVentilation::setMaximumOutdoorEnthalpy(double maximumOutdoorEnthalpy) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMaximumOutdoorEnthalpy(maximumOutdoorEnthalpy); } bool AvailabilityManagerHybridVentilation::setMinimumOutdoorDewpoint(double minimumOutdoorDewpoint) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMinimumOutdoorDewpoint(minimumOutdoorDewpoint); } bool AvailabilityManagerHybridVentilation::setMaximumOutdoorDewpoint(double maximumOutdoorDewpoint) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMaximumOutdoorDewpoint(maximumOutdoorDewpoint); } bool AvailabilityManagerHybridVentilation::setMinimumOutdoorVentilationAirSchedule(Schedule& schedule) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setMinimumOutdoorVentilationAirSchedule(schedule); } bool AvailabilityManagerHybridVentilation::setOpeningFactorFunctionofWindSpeedCurve(const Curve& curve) { return getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->setOpeningFactorFunctionofWindSpeedCurve(curve); } void AvailabilityManagerHybridVentilation::resetOpeningFactorFunctionofWindSpeedCurve() { getImpl<detail::AvailabilityManagerHybridVentilation_Impl>()->resetOpeningFactorFunctionofWindSpeedCurve(); } /// @cond AvailabilityManagerHybridVentilation::AvailabilityManagerHybridVentilation(std::shared_ptr<detail::AvailabilityManagerHybridVentilation_Impl> impl) : AvailabilityManager(impl) {} /// @endcond } // model } // openstudio
46.505828
184
0.788131
[ "vector", "model" ]
a4d172105d87117321664c3b92c7e4c30b89dd1b
3,294
cpp
C++
src/solvers/random_restart_solver.cpp
nodchip/icfpc2021
e50f0172fd62097049dab19c01875c57468a13f1
[ "MIT" ]
1
2021-07-12T13:52:18.000Z
2021-07-12T13:52:18.000Z
src/solvers/random_restart_solver.cpp
nodchip/icfpc2021
e50f0172fd62097049dab19c01875c57468a13f1
[ "MIT" ]
null
null
null
src/solvers/random_restart_solver.cpp
nodchip/icfpc2021
e50f0172fd62097049dab19c01875c57468a13f1
[ "MIT" ]
1
2021-08-24T08:49:18.000Z
2021-08-24T08:49:18.000Z
#include "stdafx.h" #include <cmath> #include <fmt/format.h> #include <boost/geometry.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> #include "contest_types.h" #include "solver_registry.h" #include "visual_editor.h" #include "solver_util.h" #include "judge.h" #include "timer.h" namespace RandomRestartSolver { std::vector<Point> enumerate_interior_points(const SProblem& problem) { integer ymin = INT_MAX, ymax = INT_MIN; integer xmin = INT_MAX, xmax = INT_MIN; for (auto p : problem.hole_polygon) { chmin(xmin, get_x(p)); chmin(ymin, get_y(p)); chmax(xmax, get_x(p)); chmax(ymax, get_y(p)); } std::vector<Point> points; for (int y = ymin; y <= ymax; ++y) { for (int x = xmin; x <= xmax; ++x) { if (contains(problem.hole_polygon, {x, y}) != EContains::EOUT) { // include points on the edge/vertex of the hole. points.emplace_back(x, y); } } } LOG(INFO) << fmt::format("found {} interior points", points.size()); return points; } class Solver : public SolverBase { public: SolverOutputs solve(const SolverArguments& args) override { auto seed = std::random_device()(); LOG(INFO) << fmt::format("seed: {}", seed); rng.seed(seed); constexpr int num_random_restarts = 2; const auto interior_points = enumerate_interior_points(*args.problem); SSolutionPtr best_solution = args.problem->create_solution(); integer best_dislikes = std::numeric_limits<integer>::max(); for (int i = 0; i < num_random_restarts; ++i) { LOG(INFO) << fmt::format("solve {}/{}", i, num_random_restarts); auto init_pose = args.problem->create_solution(); if (i % 2 == 0) { // random init for (auto& v : init_pose->vertices) { v = interior_points[std::uniform_int_distribution<size_t>(0ull, interior_points.size())(rng)]; } } auto solver = SolverRegistry::getSolver("HopGridAnnealingSolver"); CHECK(solver); SolverArguments sub_args = args; sub_args.optional_initial_solution = init_pose; sub_args.random_seed = rng(); Timer t; SolverOutputs trial_res = solver->solve(sub_args); auto trial_judge = judge(*args.problem, *trial_res.solution); LOG(INFO) << fmt::format("solve {}/{} .. elapsed {} ms. is_valid={}, fit_hole={}, DL={}", i, num_random_restarts, t.elapsed_ms(), trial_judge.is_valid(), trial_judge.fit_in_hole(), trial_judge.dislikes); if (trial_judge.is_valid() && trial_judge.dislikes < best_dislikes) { const std::string filename = args.problem->problem_id ? fmt::format("{}.bestsofar.pose.json", *args.problem->problem_id) : "bestsofar.pose.json"; save_solution(args.problem, trial_res.solution, "RandomRestartSolver", filename); LOG(INFO) << fmt::format("@@@@@@ trial {} update best {} -> {}. saved: {}", i, best_dislikes, trial_judge.dislikes, filename); best_solution = trial_res.solution; best_dislikes = trial_judge.dislikes; } } SolverOutputs outputs; outputs.solution = best_solution; return outputs; } private: std::mt19937 rng; }; } REGISTER_SOLVER("RandomRestartSolver", RandomRestartSolver::Solver); // vim:ts=2 sw=2 sts=2 et ci
33.272727
153
0.659381
[ "geometry", "vector" ]
a4d7fef1e7f7a636cdb358a9e6e8e12d5ee8b0f0
5,099
cpp
C++
PacManRenderer.Test/src/entity/RenderEntityTest.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
5
2019-12-23T22:45:46.000Z
2021-11-11T06:27:12.000Z
PacManRenderer.Test/src/entity/RenderEntityTest.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
null
null
null
PacManRenderer.Test/src/entity/RenderEntityTest.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
1
2021-11-11T06:27:14.000Z
2021-11-11T06:27:14.000Z
#include <gmock/gmock.h> #include <gtest/gtest.h> #include "entity/RenderEntity.h" #include "EntityStateRendererMock.h" #include "ValueProviderMock.h" using ::testing::Return; namespace pacman { namespace renderer { namespace entity { enum class DummyState { One, Two, Three, }; std::unique_ptr<IEntityStateRenderer> GetRendererMockWithInitialiseExpectation() { std::unique_ptr<EntityStateRendererMock> p_renderer = std::make_unique<EntityStateRendererMock>(); EXPECT_CALL(*p_renderer, Initialise()).Times(1); return p_renderer; } TEST(RenderEntityTest, Initialise_InitialisesAllStateRenderers) { // Setup std::unique_ptr<ValueProviderMock<DummyState>> p_state_provider = std::make_unique<ValueProviderMock<DummyState>>(); ON_CALL(*p_state_provider, GetValue()).WillByDefault(Return(DummyState::Two)); std::unique_ptr<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>> p_renderers = std::make_unique<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>>(); p_renderers->insert(std::make_pair(DummyState::One, GetRendererMockWithInitialiseExpectation())); RenderEntity<DummyState> render_entity = RenderEntity<DummyState>(std::move(p_renderers), std::move(p_state_provider)); // Call | Assert render_entity.Initialise(); } class RenderEntityUpdateTest : public ::testing::TestWithParam<size_t> { public: static std::vector<size_t> GetTestData() { return { 1, 2, 3, 4, 5 }; } }; TEST_P(RenderEntityUpdateTest, Update_CallsUpdateActiveRenderer) { // Setup const float expected_dtime = 1.23F; std::unique_ptr<ValueProviderMock<DummyState>> p_state_provider = std::make_unique<ValueProviderMock<DummyState>>(); ON_CALL(*p_state_provider, GetValue()).WillByDefault(Return(DummyState::Two)); std::unique_ptr<EntityStateRendererMock> p_renderer_two = std::make_unique<EntityStateRendererMock>(); EXPECT_CALL(*p_renderer_two, Update(expected_dtime)).Times(GetParam()); std::unique_ptr<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>> p_renderers = std::make_unique<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>>(); p_renderers->insert(std::make_pair(DummyState::Two, std::move(p_renderer_two))); RenderEntity<DummyState> render_entity = RenderEntity<DummyState>(std::move(p_renderers), std::move(p_state_provider)); // Call | Assert for (size_t i = 0; i < GetParam(); i++) render_entity.Update(expected_dtime); } INSTANTIATE_TEST_SUITE_P(RenderEntityTest, RenderEntityUpdateTest, ::testing::ValuesIn(RenderEntityUpdateTest::GetTestData())); TEST(RenderEntityTest, Update_ActiveStateChanged_CallsResetNewActiveRenderer) { // Setup const float expected_dtime = 1.23F; std::unique_ptr<ValueProviderMock<DummyState>> p_state_provider = std::make_unique<ValueProviderMock<DummyState>>(); EXPECT_CALL(*p_state_provider, GetValue()).WillOnce(Return(DummyState::One)) .WillOnce(Return(DummyState::Two)); std::unique_ptr<EntityStateRendererMock> p_renderer_two = std::make_unique<EntityStateRendererMock>(); EXPECT_CALL(*p_renderer_two, Reset()).Times(1); EXPECT_CALL(*p_renderer_two, Update(expected_dtime)).Times(1); std::unique_ptr<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>> p_renderers = std::make_unique<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>>(); p_renderers->insert(std::make_pair(DummyState::Two, std::move(p_renderer_two))); RenderEntity<DummyState> render_entity = RenderEntity<DummyState>(std::move(p_renderers), std::move(p_state_provider)); // Call | Assert render_entity.Update(expected_dtime); } TEST(RenderEntityTest, Render_CallsActiveRenderer) { // Setup const float expected_scale = 1.23F; const float expected_offset = 4.56F; std::unique_ptr<ValueProviderMock<DummyState>> p_state_provider = std::make_unique<ValueProviderMock<DummyState>>(); EXPECT_CALL(*p_state_provider, GetValue()).Times(2).WillRepeatedly(Return(DummyState::Two)); std::unique_ptr<EntityStateRendererMock> p_renderer_two = std::make_unique<EntityStateRendererMock>(); EXPECT_CALL(*p_renderer_two, Render(expected_scale, expected_offset)).Times(1); std::unique_ptr<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>> p_renderers = std::make_unique<std::unordered_map<DummyState, std::unique_ptr<IEntityStateRenderer>, EnumClassHash>>(); p_renderers->insert(std::make_pair(DummyState::Two, std::move(p_renderer_two))); RenderEntity<DummyState> render_entity = RenderEntity<DummyState>(std::move(p_renderers), std::move(p_state_provider)); // Call | Assert render_entity.Render(expected_scale, expected_offset); } } } }
33.993333
117
0.735242
[ "render", "vector" ]
a4e48d228bad5318b517d5b415e8bebe4f4f6ba4
1,288
hpp
C++
include/data/Classmate.hpp
davidcorbin/mygcc-application
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
[ "MIT" ]
2
2019-01-18T02:33:45.000Z
2019-02-01T23:44:05.000Z
include/data/Classmate.hpp
davidcorbin/mygcc-application
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
[ "MIT" ]
null
null
null
include/data/Classmate.hpp
davidcorbin/mygcc-application
9e978e4d6e4cd3d8534bbc73f38c45b205258cc9
[ "MIT" ]
null
null
null
/** * Copyright 2018 <David Corbin, Mitchell Harvey> */ #ifndef INCLUDE_DATA_CLASSMATE_HPP_ #define INCLUDE_DATA_CLASSMATE_HPP_ #include <include/data/Login.hpp> #include <include/types/Student.hpp> #include <include/FileManager.hpp> #include <string> #include <vector> class Classmate : public QObject { Q_OBJECT public: /** * Constructor that sets login. * @param login login object */ explicit Classmate(Login *login); /** * Constructor without login. */ Classmate(); void loadClassmates(std::string *token, std::string *courseCode); std::vector<Student *> *getClassmates() const; /** * Get login object. * @return login object */ Login *getLogin() const; /** * Set login object. * @param login login object */ void setLogin(Login *login); private: bool classmatesRec; std::vector<Student *> *students; Login *login; std::string *courseCode; QNetworkAccessManager *nam; QNetworkAccessManager *imgDlnam; FileManager *fm; void parseClassmatesJson(QJsonObject object); void sortClassmates(); void setupConnections(); void downloadImage(std::string *url); signals: // NOLINT void classmatesReceived(); void imageDownloaded(std::string *filename); }; #endif // INCLUDE_DATA_CLASSMATE_HPP_
19.815385
67
0.700311
[ "object", "vector" ]
35016d5bf4f977d7696fe19404713d003c291260
1,978
hpp
C++
include/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelBufferToTexture.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
245
2015-10-29T14:31:45.000Z
2022-03-31T13:04:45.000Z
include/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelBufferToTexture.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
64
2016-03-11T19:45:05.000Z
2022-03-31T23:58:33.000Z
include/Core/Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelBufferToTexture.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
11
2018-05-24T09:07:43.000Z
2022-03-21T21:05:20.000Z
/* See LICENSE file in root folder */ #ifndef ___C3D_VoxelBufferToTexture_H___ #define ___C3D_VoxelBufferToTexture_H___ #include "VoxelizeModule.hpp" #include "Castor3D/Render/Passes/CommandsSemaphore.hpp" #include <ashespp/Descriptor/DescriptorSet.hpp> #include <ashespp/Descriptor/DescriptorSetLayout.hpp> #include <ashespp/Descriptor/DescriptorSetPool.hpp> #include <ashespp/Pipeline/ComputePipeline.hpp> #include <ashespp/Pipeline/PipelineLayout.hpp> #include <RenderGraph/RunnablePass.hpp> namespace castor3d { class VoxelBufferToTexture : public crg::RunnablePass { public: struct Pipeline { ShaderModule shader; ashes::ComputePipelinePtr pipeline{}; }; public: /** *\~english *\param[in] device The GPU device. *\param[in] vctConfig The voxelizer configuration. *\param[in] voxels The voxels buffer. *\param[in] result The resulting texture. *\~french *\param[in] device Le device GPU. *\param[in] vctConfig La configuration du voxelizer. *\param[in] voxels Le tampon de voxels. *\param[in] result La texture résultante. */ C3D_API VoxelBufferToTexture( crg::FramePass const & pass , crg::GraphContext & context , crg::RunnableGraph & graph , RenderDevice const & device , VoxelSceneData const & vctConfig ); /** *\copydoc castor3d::RenderTechniquePass::accept */ C3D_API void accept( RenderTechniqueVisitor & visitor ); private: void doInitialise(); void doRecordInto( VkCommandBuffer commandBuffer , uint32_t index ); VkPipelineStageFlags doGetSemaphoreWaitFlags()const; uint32_t doGetPassIndex()const; bool doIsComputePass()const; private: RenderDevice const & m_device; VoxelSceneData const & m_vctConfig; ashes::DescriptorSetLayoutPtr m_descriptorSetLayout; ashes::PipelineLayoutPtr m_pipelineLayout; std::array< Pipeline, 4u > m_pipelines; ashes::DescriptorSetPoolPtr m_descriptorSetPool; ashes::DescriptorSetPtr m_descriptorSet; }; } #endif
26.72973
59
0.752275
[ "render" ]
35024673e698b0a22ca09fe3d5017933248daee2
3,953
hpp
C++
NeuronalNetwork/Network.hpp
maede97/NeuronalNetwork
adeb1ea1c062893461f9cfed78eba9513df9748c
[ "MIT" ]
null
null
null
NeuronalNetwork/Network.hpp
maede97/NeuronalNetwork
adeb1ea1c062893461f9cfed78eba9513df9748c
[ "MIT" ]
null
null
null
NeuronalNetwork/Network.hpp
maede97/NeuronalNetwork
adeb1ea1c062893461f9cfed78eba9513df9748c
[ "MIT" ]
null
null
null
#ifndef NETWORK_HPP #define NETWORK_HPP #include <cassert> #include <functional> #include <iostream> #include <vector> #include "AbstractBaseLayer.hpp" #include "DataSet.hpp" /** * @brief Network class */ class Network { public: /** * @brief Default constructor */ Network() {} /** * @brief Saves the whole Network configuration to disk * @param path Folder to be saved to */ void saveConfiguration(const std::string& path) const { for (auto layer = layers_.begin(); layer != layers_.end(); layer++) { (*layer)->saveConfiguration(path); } } /** * @brief Loads the whole Network configuration to disk * @param path Folder to be loaded from */ void loadConfiguration(const std::string& path) { for (auto layer = layers_.begin(); layer != layers_.end(); layer++) { (*layer)->loadConfiguration(path); } } /** * @brief Add a new layer * @param layer Pointer to the layer */ void add(AbstractBaseLayer *layer) { layers_.push_back(layer); } /** * @brief Sets loss function and derivative * @param loss Loss function * @param lossPrime The derivative of the loss functoin */ void use(std::function<double(Eigen::VectorXd, Eigen::VectorXd)> loss, std::function<Eigen::VectorXd(Eigen::VectorXd, Eigen::VectorXd)> lossPrime) { loss_ = loss; lossPrime_ = lossPrime; } /** * @brief Set DataSet * @param set The DataSet to use */ void setData(const DataSet& set) { set_ = set; } /** * @brief Returns the last error. * @return The last error. */ double lastError() const { return last_err_; } /** * @brief Predict output of data * @return A Matrix containing all outputs as rows */ Eigen::MatrixXd predict() const { const unsigned int samples = set_.getInputTestData().rows(); std::vector<Eigen::VectorXd> result; Eigen::VectorXd output; for (unsigned int i = 0; i < samples; i++) { output = set_.getInputTestData().row(i).transpose(); for (auto layer = layers_.begin(); layer != layers_.end(); layer++) { output = (*layer)->forwardPropagation(output); } result.push_back(output); } Eigen::MatrixXd resultMat(samples, result[0].size()); for (int i = 0; i < result.size(); i++) { resultMat.row(i) = result[i]; } return resultMat; } /** * @brief Train the network * @param epochs How long to train * @param learning_rate With which rate to train */ void fit(const unsigned int epochs, const double learning_rate) { assert(loss_ && lossPrime_ && "Loss function not initialised."); const unsigned int samples = set_.getInputTrainingData().rows(); Eigen::VectorXd output; for (unsigned int i = 0; i < epochs; i++) { double err = 0; for (unsigned int j = 0; j < samples; j++) { output = set_.getInputTrainingData().row(j).transpose(); for (auto layer = layers_.begin(); layer != layers_.end(); layer++) { output = (*layer)->forwardPropagation(output); } // compute for display purpose err += loss_(set_.getOutputTrainingData().row(j).transpose(), output); // backwards propagation Eigen::VectorXd error = lossPrime_(set_.getOutputTrainingData().row(j).transpose(), output); for (auto layer = layers_.end() - 1; layer + 1 != layers_.begin(); layer--) { error = (*layer)->backwardPropagation(error, learning_rate); } } err /= (double)samples; last_err_ = err; } } private: std::vector<AbstractBaseLayer *> layers_; ///< internal storage for layers std::function<double(Eigen::VectorXd, Eigen::VectorXd)> loss_; ///< loss function to use std::function<Eigen::VectorXd(Eigen::VectorXd, Eigen::VectorXd)> lossPrime_; ///< loss derivative to use DataSet set_; double last_err_; ///< last error }; #endif
29.281481
80
0.622818
[ "vector" ]
3505d01ae44b7b3573d8b810993b29194afcebf1
6,062
hpp
C++
src/Event/Event.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
src/Event/Event.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
src/Event/Event.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
#ifndef Event_b2be9c82b0b54601b3cd1dc5e7a8c09e #define Event_b2be9c82b0b54601b3cd1dc5e7a8c09e #include "../Helpers/DateTime.hpp" #include "../Person/Person.hpp" #include "VirtualEvent.hpp" #include "../Exceptions/InvalidUseException.hpp" #include "EventType.hpp" #include <iostream> #include <map> #include <memory> #include <vector> #include <fstream> class Person; /** * @brief Abstract class providing general interface for events * */ class Event { protected: std::string name; std::string place; DateTime start; TimeSpan duration; std::map<std::string, std::weak_ptr<Person>> participants; public: Event(const std::string & name, const std::string & place, const DateTime & start, const TimeSpan & duration, const std::shared_ptr<Person> & owner); virtual ~Event() = default; /** * @brief Prints Event object according its type * * @param[out] os here it will be printed */ virtual void Print(std::ostream & os) const = 0; /** * @brief Prints all participant of an Event object * * @param[out] os here it will be printed */ void PrintParticipants(std::ostream & os) const; /** * @brief Compares two Event objects by start, then by name and finaly by place * * @param e Second Event object */ bool operator < (const Event & e) const; /** * @brief Compares two Event objects by start, then by name and finaly by place * * @param e Second Event object */ bool operator == (const Event & e) const; const std::string & GetName() const; const std::string & GetPlace() const; const DateTime & GetStart() const; void SetName(const std::string & newName); void SetPlace(const std::string & newPlace); /** * @brief Adds Person object as a participant to this Event * * @param p shared pointer of Person object * @return true if Person object was succesfully added * @return false if Person is already participating */ bool AddPerson(const std::shared_ptr<Person> & p); /** * @brief Removes Person object from participants * * @param p name of the Person object that will be removed * @return true if Person object were removed * @return false if Person object was not participating */ bool RemovePerson(const std::string & p); /** * @brief Adds all participants that are not in this Event object as participants * * @param e Event object from which missing participants will be copied */ void AddMissingParticipants(const std::shared_ptr<Event> & e); /** * @brief Removes all participant * * @param e shared pointer to this event, so it could be send to the participants * to remove it as well */ void RemoveAllParticipants(const std::shared_ptr<Event> & e); /** * @brief Shifts start of this Event object by ts * * @param ts TimeSpan that will be added to start of the Event object */ void Shift(const TimeSpan & ts); /** * @brief Splits Event object starting with from and then shifts the later part * * @param ts TimeSpan that will be added to start of the later Event object * @param from index of Event repetition from where it will be split and shifted * @param owner who is spliting these events * @return std::shared_ptr<Event> shared pointer to new Event object, * it doesn't have to be same Type * @throws InvalidUseException if it is tried to split the EventObject at start or at the end */ virtual std::shared_ptr<Event> SplitShift(const TimeSpan & ts, int from, const std::shared_ptr<Person> & owner) = 0; /** * @brief Fills output parametr with VirtualEvent objects symbolizing instances of this * Event object between given DateTimes * * @param[out] putHere Here will be inserted VirtualEvents that represents instance of Event * @param from * @param to * @param ptr shared pointer to this Event object */ virtual void FillWithVirtualEvents(std::vector<VirtualEvent> & putHere, const DateTime & from, const DateTime & to, std::shared_ptr<Event> & ptr) const = 0; /** * @brief Fills output parametr with VirtualEvent objects symbolizing instances of this * Event object that contains given string * * @param[out] putHere Here will be inserted VirtualEvents that represents instance of Event * @param ptr shared ptr to this Event object * @param search string that is searched for */ void FillWithVirtualEvent(std::vector<VirtualEvent> & putHere, std::shared_ptr<Event> & ptr, const std::string & search = "") const; /** * @brief Exports this Event object to given ofstream * * @param[out] file here it will be exported */ void Export(std::ofstream & file) const; /** * @brief Export Event type specific info * * @param[out] file here it will be exported */ virtual void ExportEventTypeSpecificInfo(std::ofstream & file) const = 0; }; /** * @brief Compares two shared pointer accorfing to operator < between Events objects * */ bool CompareSharedPtrEvents(const std::shared_ptr<Event> & e1, const std::shared_ptr<Event> & e2); /** * @brief Compares two shared pointer accorfing to operator == between Event objects * */ bool AreSharedPtrEventsSame(const std::shared_ptr<Event> & e1, const std::shared_ptr<Event> & e2); #endif //Event_b2be9c82b0b54601b3cd1dc5e7a8c09e
36.739394
102
0.613989
[ "object", "vector" ]
350735d5822a659e1154448571e583e96034c901
190,668
cpp
C++
GCG_Source.build/module.django.core.mail.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.django.core.mail.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.django.core.mail.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
/* Generated code for Python source for module 'django.core.mail' * created by Nuitka version 0.5.28.2 * * This code is in part copyright 2017 Kay Hayen. * * 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 "nuitka/prelude.h" #include "__helpers.h" /* The _module_django$core$mail is a Python object pointer of module type. */ /* Note: For full compatibility with CPython, every module variable access * needs to go through it except for cases where the module cannot possibly * have changed in the mean time. */ PyObject *module_django$core$mail; PyDictObject *moduledict_django$core$mail; /* The module constants used, if any. */ extern PyObject *const_str_plain_MANAGERS; static PyObject *const_str_plain_send_mass_mail; extern PyObject *const_str_plain___spec__; extern PyObject *const_str_plain_sender; extern PyObject *const_dict_empty; extern PyObject *const_str_digest_d434fa92832494458af57a18e30eeae3; extern PyObject *const_str_plain___file__; extern PyObject *const_str_plain_import_string; static PyObject *const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple; extern PyObject *const_str_angle_listcontraction; static PyObject *const_tuple_788da1634d847913dacb66f7ef2950fd_tuple; extern PyObject *const_str_plain_SERVER_EMAIL; extern PyObject *const_str_plain_a; extern PyObject *const_str_plain_EMAIL_BACKEND; extern PyObject *const_str_plain_send_messages; extern PyObject *const_tuple_c15243b3ba68498da186d5d65ae367ca_tuple; extern PyObject *const_tuple_str_plain_import_string_tuple; static PyObject *const_str_digest_17c95fc00e2fa035a4a7e4fe917d63bb; static PyObject *const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple; extern PyObject *const_str_plain_join; extern PyObject *const_str_plain_messages; static PyObject *const_str_plain_NUITKA_PACKAGE_django_core_mail; extern PyObject *const_str_plain___doc__; extern PyObject *const_str_plain_EmailMessage; static PyObject *const_str_digest_dcd9259d193a76e79fad54e9e1350333; static PyObject *const_tuple_str_plain_DNS_NAME_str_plain_CachedDnsName_tuple; extern PyObject *const_str_plain_environ; extern PyObject *const_str_plain_get_connection; static PyObject *const_str_digest_3bc9cd3436adbed05aeee30a149a984b; extern PyObject *const_str_plain___package__; extern PyObject *const_str_digest_690178e17eae3581689f22974cc26edf; extern PyObject *const_tuple_none_false_tuple; static PyObject *const_str_digest_ccaf478ca9df72f2a24652f04baa4957; extern PyObject *const_str_plain_SafeMIMEMultipart; static PyObject *const_list_2a56c87d4d1b4ea30b58df6b484f8201_list; extern PyObject *const_str_digest_d76462298f66c95b4d3ee22e9427a916; extern PyObject *const_str_plain_make_msgid; extern PyObject *const_str_plain_DNS_NAME; extern PyObject *const_str_plain_path; static PyObject *const_str_plain_auth_password; extern PyObject *const_str_digest_e2cff0983efd969a5767cadcc9e9f0e8; static PyObject *const_tuple_false_none_none_tuple; extern PyObject *const_str_plain_message; static PyObject *const_str_plain_auth_user; extern PyObject *const_str_plain_SafeMIMEText; extern PyObject *const_str_digest_aee0d40e09f76fd339276e187b4cadfd; extern PyObject *const_str_plain___path__; extern PyObject *const_str_plain_EMAIL_SUBJECT_PREFIX; extern PyObject *const_tuple_empty; extern PyObject *const_str_plain_username; extern PyObject *const_str_plain___loader__; extern PyObject *const_str_plain_attach_alternative; extern PyObject *const_tuple_b868c6b0937f28ff9b15f6cc52ff2098_tuple; extern PyObject *const_str_plain_send; static PyObject *const_tuple_false_none_none_none_none_tuple; extern PyObject *const_str_plain_send_mail; static PyObject *const_str_plain_recipient_list; extern PyObject *const_str_plain_mail; extern PyObject *const_str_plain_ModuleSpec; extern PyObject *const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE; extern PyObject *const_str_plain_recipient; extern PyObject *const_str_plain___all__; extern PyObject *const_str_plain_connection; extern PyObject *const_int_0; extern PyObject *const_str_plain_kwds; extern PyObject *const_str_plain_CachedDnsName; extern PyObject *const_tuple_str_plain_settings_tuple; extern PyObject *const_str_plain_from_email; extern PyObject *const_str_plain_subject; extern PyObject *const_str_plain_ADMINS; extern PyObject *const_str_digest_1572198cb22a44b444ca284ab3fb285b; static PyObject *const_str_digest_7b409349ae9bcff87319817b7154920c; static PyObject *const_str_plain_mail_managers; extern PyObject *const_str_plain_fail_silently; static PyObject *const_str_digest_234b289f937c6961c780f32ea2f04b3f; extern PyObject *const_str_plain_NUITKA_PACKAGE_django_core; static PyObject *const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple; extern PyObject *const_str_plain_settings; static PyObject *const_str_digest_361587de2a9b7265a8610c25a42e22b5; extern PyObject *const_str_plain_mail_admins; extern PyObject *const_str_plain_BadHeaderError; extern PyObject *const_str_plain_dirname; extern PyObject *const_str_plain___cached__; static PyObject *const_str_digest_daae6d9876cd0712c83b7035415ef6dd; extern PyObject *const_str_plain_password; extern PyObject *const_str_plain_html_message; extern PyObject *const_str_plain_unicode_literals; extern PyObject *const_int_pos_1; static PyObject *const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple; extern PyObject *const_str_plain_backend; extern PyObject *const_str_plain_forbid_multi_line_headers; static PyObject *const_tuple_4e68671053c42ca53246bff32e1352cb_tuple; static PyObject *const_tuple_75a15e879c7a8bd34659463d4ddb0ad9_tuple; extern PyObject *const_str_plain_NUITKA_PACKAGE_django; extern PyObject *const_str_digest_5f972e9cea97219805947b4127aeae11; extern PyObject *const_tuple_str_plain_a_tuple; extern PyObject *const_str_digest_5bfaf90dbd407b4fc29090c8f6415242; extern PyObject *const_str_plain_get; static PyObject *const_str_digest_3f07db178fdeee72a253dae658423338; extern PyObject *const_str_plain_EmailMultiAlternatives; static PyObject *const_tuple_false_none_none_none_tuple; extern PyObject *const_str_plain_klass; static PyObject *const_str_plain_datatuple; static PyObject *module_filename_obj; static bool constants_created = false; static void createModuleConstants( void ) { const_str_plain_send_mass_mail = UNSTREAM_STRING( &constant_bin[ 790682 ], 14, 1 ); const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple = PyTuple_New( 8 ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 0, const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE ); Py_INCREF( const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 1, const_str_plain_BadHeaderError ); Py_INCREF( const_str_plain_BadHeaderError ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 2, const_str_plain_EmailMessage ); Py_INCREF( const_str_plain_EmailMessage ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 3, const_str_plain_EmailMultiAlternatives ); Py_INCREF( const_str_plain_EmailMultiAlternatives ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 4, const_str_plain_SafeMIMEMultipart ); Py_INCREF( const_str_plain_SafeMIMEMultipart ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 5, const_str_plain_SafeMIMEText ); Py_INCREF( const_str_plain_SafeMIMEText ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 6, const_str_plain_forbid_multi_line_headers ); Py_INCREF( const_str_plain_forbid_multi_line_headers ); PyTuple_SET_ITEM( const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple, 7, const_str_plain_make_msgid ); Py_INCREF( const_str_plain_make_msgid ); const_tuple_788da1634d847913dacb66f7ef2950fd_tuple = PyTuple_New( 10 ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 0, const_str_plain_subject ); Py_INCREF( const_str_plain_subject ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 1, const_str_plain_message ); Py_INCREF( const_str_plain_message ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 2, const_str_plain_from_email ); Py_INCREF( const_str_plain_from_email ); const_str_plain_recipient_list = UNSTREAM_STRING( &constant_bin[ 790696 ], 14, 1 ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 3, const_str_plain_recipient_list ); Py_INCREF( const_str_plain_recipient_list ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 4, const_str_plain_fail_silently ); Py_INCREF( const_str_plain_fail_silently ); const_str_plain_auth_user = UNSTREAM_STRING( &constant_bin[ 790710 ], 9, 1 ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 5, const_str_plain_auth_user ); Py_INCREF( const_str_plain_auth_user ); const_str_plain_auth_password = UNSTREAM_STRING( &constant_bin[ 790719 ], 13, 1 ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 6, const_str_plain_auth_password ); Py_INCREF( const_str_plain_auth_password ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 7, const_str_plain_connection ); Py_INCREF( const_str_plain_connection ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 8, const_str_plain_html_message ); Py_INCREF( const_str_plain_html_message ); PyTuple_SET_ITEM( const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 9, const_str_plain_mail ); Py_INCREF( const_str_plain_mail ); const_str_digest_17c95fc00e2fa035a4a7e4fe917d63bb = UNSTREAM_STRING( &constant_bin[ 790732 ], 28, 0 ); const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple = PyTuple_New( 4 ); PyTuple_SET_ITEM( const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple, 0, const_str_plain_backend ); Py_INCREF( const_str_plain_backend ); PyTuple_SET_ITEM( const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple, 1, const_str_plain_fail_silently ); Py_INCREF( const_str_plain_fail_silently ); PyTuple_SET_ITEM( const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple, 2, const_str_plain_kwds ); Py_INCREF( const_str_plain_kwds ); PyTuple_SET_ITEM( const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple, 3, const_str_plain_klass ); Py_INCREF( const_str_plain_klass ); const_str_plain_NUITKA_PACKAGE_django_core_mail = UNSTREAM_STRING( &constant_bin[ 790760 ], 31, 1 ); const_str_digest_dcd9259d193a76e79fad54e9e1350333 = UNSTREAM_STRING( &constant_bin[ 790791 ], 222, 0 ); const_tuple_str_plain_DNS_NAME_str_plain_CachedDnsName_tuple = PyTuple_New( 2 ); PyTuple_SET_ITEM( const_tuple_str_plain_DNS_NAME_str_plain_CachedDnsName_tuple, 0, const_str_plain_DNS_NAME ); Py_INCREF( const_str_plain_DNS_NAME ); PyTuple_SET_ITEM( const_tuple_str_plain_DNS_NAME_str_plain_CachedDnsName_tuple, 1, const_str_plain_CachedDnsName ); Py_INCREF( const_str_plain_CachedDnsName ); const_str_digest_3bc9cd3436adbed05aeee30a149a984b = UNSTREAM_STRING( &constant_bin[ 790739 ], 9, 0 ); const_str_digest_ccaf478ca9df72f2a24652f04baa4957 = UNSTREAM_STRING( &constant_bin[ 791013 ], 25, 0 ); const_list_2a56c87d4d1b4ea30b58df6b484f8201_list = PyList_New( 15 ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 0, const_str_plain_CachedDnsName ); Py_INCREF( const_str_plain_CachedDnsName ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 1, const_str_plain_DNS_NAME ); Py_INCREF( const_str_plain_DNS_NAME ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 2, const_str_plain_EmailMessage ); Py_INCREF( const_str_plain_EmailMessage ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 3, const_str_plain_EmailMultiAlternatives ); Py_INCREF( const_str_plain_EmailMultiAlternatives ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 4, const_str_plain_SafeMIMEText ); Py_INCREF( const_str_plain_SafeMIMEText ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 5, const_str_plain_SafeMIMEMultipart ); Py_INCREF( const_str_plain_SafeMIMEMultipart ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 6, const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE ); Py_INCREF( const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 7, const_str_plain_make_msgid ); Py_INCREF( const_str_plain_make_msgid ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 8, const_str_plain_BadHeaderError ); Py_INCREF( const_str_plain_BadHeaderError ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 9, const_str_plain_forbid_multi_line_headers ); Py_INCREF( const_str_plain_forbid_multi_line_headers ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 10, const_str_plain_get_connection ); Py_INCREF( const_str_plain_get_connection ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 11, const_str_plain_send_mail ); Py_INCREF( const_str_plain_send_mail ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 12, const_str_plain_send_mass_mail ); Py_INCREF( const_str_plain_send_mass_mail ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 13, const_str_plain_mail_admins ); Py_INCREF( const_str_plain_mail_admins ); const_str_plain_mail_managers = UNSTREAM_STRING( &constant_bin[ 791038 ], 13, 1 ); PyList_SET_ITEM( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list, 14, const_str_plain_mail_managers ); Py_INCREF( const_str_plain_mail_managers ); const_tuple_false_none_none_tuple = PyTuple_New( 3 ); PyTuple_SET_ITEM( const_tuple_false_none_none_tuple, 0, Py_False ); Py_INCREF( Py_False ); PyTuple_SET_ITEM( const_tuple_false_none_none_tuple, 1, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_false_none_none_tuple, 2, Py_None ); Py_INCREF( Py_None ); const_tuple_false_none_none_none_none_tuple = PyTuple_New( 5 ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_none_tuple, 0, Py_False ); Py_INCREF( Py_False ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_none_tuple, 1, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_none_tuple, 2, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_none_tuple, 3, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_none_tuple, 4, Py_None ); Py_INCREF( Py_None ); const_str_digest_7b409349ae9bcff87319817b7154920c = UNSTREAM_STRING( &constant_bin[ 791051 ], 569, 0 ); const_str_digest_234b289f937c6961c780f32ea2f04b3f = UNSTREAM_STRING( &constant_bin[ 791620 ], 26, 0 ); const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple = PyTuple_New( 6 ); PyTuple_SET_ITEM( const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 0, const_str_plain_subject ); Py_INCREF( const_str_plain_subject ); PyTuple_SET_ITEM( const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 1, const_str_plain_message ); Py_INCREF( const_str_plain_message ); PyTuple_SET_ITEM( const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 2, const_str_plain_sender ); Py_INCREF( const_str_plain_sender ); PyTuple_SET_ITEM( const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 3, const_str_plain_recipient ); Py_INCREF( const_str_plain_recipient ); const_str_plain_datatuple = UNSTREAM_STRING( &constant_bin[ 791064 ], 9, 1 ); PyTuple_SET_ITEM( const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 4, const_str_plain_datatuple ); Py_INCREF( const_str_plain_datatuple ); PyTuple_SET_ITEM( const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 5, const_str_plain_connection ); Py_INCREF( const_str_plain_connection ); const_str_digest_361587de2a9b7265a8610c25a42e22b5 = UNSTREAM_STRING( &constant_bin[ 791646 ], 433, 0 ); const_str_digest_daae6d9876cd0712c83b7035415ef6dd = UNSTREAM_STRING( &constant_bin[ 792079 ], 68, 0 ); const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple = PyTuple_New( 6 ); PyTuple_SET_ITEM( const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 0, const_str_plain_datatuple ); Py_INCREF( const_str_plain_datatuple ); PyTuple_SET_ITEM( const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 1, const_str_plain_fail_silently ); Py_INCREF( const_str_plain_fail_silently ); PyTuple_SET_ITEM( const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 2, const_str_plain_auth_user ); Py_INCREF( const_str_plain_auth_user ); PyTuple_SET_ITEM( const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 3, const_str_plain_auth_password ); Py_INCREF( const_str_plain_auth_password ); PyTuple_SET_ITEM( const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 4, const_str_plain_connection ); Py_INCREF( const_str_plain_connection ); PyTuple_SET_ITEM( const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 5, const_str_plain_messages ); Py_INCREF( const_str_plain_messages ); const_tuple_4e68671053c42ca53246bff32e1352cb_tuple = PyTuple_New( 6 ); PyTuple_SET_ITEM( const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 0, const_str_plain_subject ); Py_INCREF( const_str_plain_subject ); PyTuple_SET_ITEM( const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 1, const_str_plain_message ); Py_INCREF( const_str_plain_message ); PyTuple_SET_ITEM( const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 2, const_str_plain_fail_silently ); Py_INCREF( const_str_plain_fail_silently ); PyTuple_SET_ITEM( const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 3, const_str_plain_connection ); Py_INCREF( const_str_plain_connection ); PyTuple_SET_ITEM( const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 4, const_str_plain_html_message ); Py_INCREF( const_str_plain_html_message ); PyTuple_SET_ITEM( const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 5, const_str_plain_mail ); Py_INCREF( const_str_plain_mail ); const_tuple_75a15e879c7a8bd34659463d4ddb0ad9_tuple = PyTuple_New( 2 ); PyTuple_SET_ITEM( const_tuple_75a15e879c7a8bd34659463d4ddb0ad9_tuple, 0, const_str_plain_NUITKA_PACKAGE_django_core_mail ); Py_INCREF( const_str_plain_NUITKA_PACKAGE_django_core_mail ); PyTuple_SET_ITEM( const_tuple_75a15e879c7a8bd34659463d4ddb0ad9_tuple, 1, const_str_digest_5bfaf90dbd407b4fc29090c8f6415242 ); Py_INCREF( const_str_digest_5bfaf90dbd407b4fc29090c8f6415242 ); const_str_digest_3f07db178fdeee72a253dae658423338 = UNSTREAM_STRING( &constant_bin[ 792147 ], 64, 0 ); const_tuple_false_none_none_none_tuple = PyTuple_New( 4 ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_tuple, 0, Py_False ); Py_INCREF( Py_False ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_tuple, 1, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_tuple, 2, Py_None ); Py_INCREF( Py_None ); PyTuple_SET_ITEM( const_tuple_false_none_none_none_tuple, 3, Py_None ); Py_INCREF( Py_None ); constants_created = true; } #ifndef __NUITKA_NO_ASSERT__ void checkModuleConstants_django$core$mail( void ) { // The module may not have been used at all. if (constants_created == false) return; } #endif // The module code objects. static PyCodeObject *codeobj_511a530df6fb7b210e19e3f73001044f; static PyCodeObject *codeobj_640ccb64c145fa6c4f28093fc71d23ea; static PyCodeObject *codeobj_65b05b6a0873b6b3ab5a6d198716577e; static PyCodeObject *codeobj_53e53520558709b487bf2d0ddb5e2347; static PyCodeObject *codeobj_face192665c41b1d3945cbf1913f54a4; static PyCodeObject *codeobj_69337f3a07aa8f8d6dbfef3ec162d3a3; static PyCodeObject *codeobj_cc13755fb2b4acdcd7f6f7d182ab7a34; static PyCodeObject *codeobj_d5b66ec9cfc93e1f58efb95eff9f6083; static PyCodeObject *codeobj_5c792633ed03c3d658263f44aa2b1415; static void createModuleCodeObjects(void) { module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_17c95fc00e2fa035a4a7e4fe917d63bb ); codeobj_511a530df6fb7b210e19e3f73001044f = MAKE_CODEOBJ( module_filename_obj, const_str_angle_listcontraction, 85, const_tuple_6eea4ff2571fe6b4c070f34967da81ba_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_640ccb64c145fa6c4f28093fc71d23ea = MAKE_CODEOBJ( module_filename_obj, const_str_angle_listcontraction, 98, const_tuple_str_plain_a_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_65b05b6a0873b6b3ab5a6d198716577e = MAKE_CODEOBJ( module_filename_obj, const_str_angle_listcontraction, 113, const_tuple_str_plain_a_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_53e53520558709b487bf2d0ddb5e2347 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_ccaf478ca9df72f2a24652f04baa4957, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_face192665c41b1d3945cbf1913f54a4 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_get_connection, 28, const_tuple_3b4fee64c2046286743ce267a464bc3b_tuple, 2, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARKEYWORDS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_69337f3a07aa8f8d6dbfef3ec162d3a3 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_mail_admins, 91, const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 5, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_cc13755fb2b4acdcd7f6f7d182ab7a34 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_mail_managers, 106, const_tuple_4e68671053c42ca53246bff32e1352cb_tuple, 5, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_d5b66ec9cfc93e1f58efb95eff9f6083 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_send_mail, 40, const_tuple_788da1634d847913dacb66f7ef2950fd_tuple, 9, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_5c792633ed03c3d658263f44aa2b1415 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_send_mass_mail, 65, const_tuple_c2e983d69a0e4e24b6d4859f17466298_tuple, 5, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); } // The module function declarations. NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_10_complex_call_helper_keywords_star_dict( PyObject **python_pars ); static PyObject *MAKE_FUNCTION_django$core$mail$$$function_1_get_connection( PyObject *defaults ); static PyObject *MAKE_FUNCTION_django$core$mail$$$function_2_send_mail( PyObject *defaults ); static PyObject *MAKE_FUNCTION_django$core$mail$$$function_3_send_mass_mail( PyObject *defaults ); static PyObject *MAKE_FUNCTION_django$core$mail$$$function_4_mail_admins( PyObject *defaults ); static PyObject *MAKE_FUNCTION_django$core$mail$$$function_5_mail_managers( PyObject *defaults ); // The module function definitions. static PyObject *impl_django$core$mail$$$function_1_get_connection( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_backend = python_pars[ 0 ]; PyObject *par_fail_silently = python_pars[ 1 ]; PyObject *par_kwds = python_pars[ 2 ]; PyObject *var_klass = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *tmp_args_element_name_1; PyObject *tmp_assign_source_1; PyObject *tmp_called_name_1; PyObject *tmp_dict_key_1; PyObject *tmp_dict_value_1; PyObject *tmp_dircall_arg1_1; PyObject *tmp_dircall_arg2_1; PyObject *tmp_dircall_arg3_1; int tmp_or_left_truth_1; PyObject *tmp_or_left_value_1; PyObject *tmp_or_right_value_1; int tmp_res; PyObject *tmp_return_value; PyObject *tmp_source_name_1; static struct Nuitka_FrameObject *cache_frame_face192665c41b1d3945cbf1913f54a4 = NULL; struct Nuitka_FrameObject *frame_face192665c41b1d3945cbf1913f54a4; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_face192665c41b1d3945cbf1913f54a4, codeobj_face192665c41b1d3945cbf1913f54a4, module_django$core$mail, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_face192665c41b1d3945cbf1913f54a4 = cache_frame_face192665c41b1d3945cbf1913f54a4; // Push the new frame as the currently active one. pushFrameStack( frame_face192665c41b1d3945cbf1913f54a4 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_face192665c41b1d3945cbf1913f54a4 ) == 2 ); // Frame stack // Framed code: tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_import_string ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_import_string ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "import_string" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 36; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_or_left_value_1 = par_backend; CHECK_OBJECT( tmp_or_left_value_1 ); tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 ); if ( tmp_or_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 36; type_description_1 = "oooo"; goto frame_exception_exit_1; } if ( tmp_or_left_truth_1 == 1 ) { goto or_left_1; } else { goto or_right_1; } or_right_1:; tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 36; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_or_right_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_EMAIL_BACKEND ); if ( tmp_or_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 36; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = tmp_or_right_value_1; goto or_end_1; or_left_1:; Py_INCREF( tmp_or_left_value_1 ); tmp_args_element_name_1 = tmp_or_left_value_1; or_end_1:; frame_face192665c41b1d3945cbf1913f54a4->m_frame.f_lineno = 36; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args ); } Py_DECREF( tmp_args_element_name_1 ); if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 36; type_description_1 = "oooo"; goto frame_exception_exit_1; } assert( var_klass == NULL ); var_klass = tmp_assign_source_1; tmp_dircall_arg1_1 = var_klass; CHECK_OBJECT( tmp_dircall_arg1_1 ); tmp_dircall_arg2_1 = _PyDict_NewPresized( 1 ); tmp_dict_key_1 = const_str_plain_fail_silently; tmp_dict_value_1 = par_fail_silently; if ( tmp_dict_value_1 == NULL ) { Py_DECREF( tmp_dircall_arg2_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "fail_silently" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 37; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_res = PyDict_SetItem( tmp_dircall_arg2_1, tmp_dict_key_1, tmp_dict_value_1 ); assert( !(tmp_res != 0) ); tmp_dircall_arg3_1 = par_kwds; if ( tmp_dircall_arg3_1 == NULL ) { Py_DECREF( tmp_dircall_arg2_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "kwds" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 37; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_dircall_arg1_1 ); Py_INCREF( tmp_dircall_arg3_1 ); { PyObject *dir_call_args[] = {tmp_dircall_arg1_1, tmp_dircall_arg2_1, tmp_dircall_arg3_1}; tmp_return_value = impl___internal__$$$function_10_complex_call_helper_keywords_star_dict( dir_call_args ); } if ( tmp_return_value == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 37; type_description_1 = "oooo"; goto frame_exception_exit_1; } goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_face192665c41b1d3945cbf1913f54a4 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_face192665c41b1d3945cbf1913f54a4 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_face192665c41b1d3945cbf1913f54a4 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_face192665c41b1d3945cbf1913f54a4, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_face192665c41b1d3945cbf1913f54a4->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_face192665c41b1d3945cbf1913f54a4, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_face192665c41b1d3945cbf1913f54a4, type_description_1, par_backend, par_fail_silently, par_kwds, var_klass ); // Release cached frame. if ( frame_face192665c41b1d3945cbf1913f54a4 == cache_frame_face192665c41b1d3945cbf1913f54a4 ) { Py_DECREF( frame_face192665c41b1d3945cbf1913f54a4 ); } cache_frame_face192665c41b1d3945cbf1913f54a4 = NULL; assertFrameObject( frame_face192665c41b1d3945cbf1913f54a4 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_1_get_connection ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_backend ); par_backend = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_kwds ); par_kwds = NULL; Py_XDECREF( var_klass ); var_klass = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_backend ); par_backend = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_kwds ); par_kwds = NULL; Py_XDECREF( var_klass ); var_klass = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_1_get_connection ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$core$mail$$$function_2_send_mail( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_subject = python_pars[ 0 ]; PyObject *par_message = python_pars[ 1 ]; PyObject *par_from_email = python_pars[ 2 ]; PyObject *par_recipient_list = python_pars[ 3 ]; PyObject *par_fail_silently = python_pars[ 4 ]; PyObject *par_auth_user = python_pars[ 5 ]; PyObject *par_auth_password = python_pars[ 6 ]; PyObject *par_connection = python_pars[ 7 ]; PyObject *par_html_message = python_pars[ 8 ]; PyObject *var_mail = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_name_1; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_called_instance_1; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_dict_key_1; PyObject *tmp_dict_key_2; PyObject *tmp_dict_key_3; PyObject *tmp_dict_key_4; PyObject *tmp_dict_value_1; PyObject *tmp_dict_value_2; PyObject *tmp_dict_value_3; PyObject *tmp_dict_value_4; PyObject *tmp_kw_name_1; PyObject *tmp_kw_name_2; int tmp_or_left_truth_1; PyObject *tmp_or_left_value_1; PyObject *tmp_or_right_value_1; int tmp_res; PyObject *tmp_return_value; PyObject *tmp_source_name_1; PyObject *tmp_tuple_element_1; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; static struct Nuitka_FrameObject *cache_frame_d5b66ec9cfc93e1f58efb95eff9f6083 = NULL; struct Nuitka_FrameObject *frame_d5b66ec9cfc93e1f58efb95eff9f6083; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_d5b66ec9cfc93e1f58efb95eff9f6083, codeobj_d5b66ec9cfc93e1f58efb95eff9f6083, module_django$core$mail, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_d5b66ec9cfc93e1f58efb95eff9f6083 = cache_frame_d5b66ec9cfc93e1f58efb95eff9f6083; // Push the new frame as the currently active one. pushFrameStack( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ) == 2 ); // Frame stack // Framed code: tmp_or_left_value_1 = par_connection; CHECK_OBJECT( tmp_or_left_value_1 ); tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 ); if ( tmp_or_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 53; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } if ( tmp_or_left_truth_1 == 1 ) { goto or_left_1; } else { goto or_right_1; } or_right_1:; tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_get_connection ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_get_connection ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "get_connection" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 53; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } tmp_kw_name_1 = _PyDict_NewPresized( 3 ); tmp_dict_key_1 = const_str_plain_username; tmp_dict_value_1 = par_auth_user; CHECK_OBJECT( tmp_dict_value_1 ); tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 ); assert( !(tmp_res != 0) ); tmp_dict_key_2 = const_str_plain_password; tmp_dict_value_2 = par_auth_password; CHECK_OBJECT( tmp_dict_value_2 ); tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_2, tmp_dict_value_2 ); assert( !(tmp_res != 0) ); tmp_dict_key_3 = const_str_plain_fail_silently; tmp_dict_value_3 = par_fail_silently; CHECK_OBJECT( tmp_dict_value_3 ); tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_3, tmp_dict_value_3 ); assert( !(tmp_res != 0) ); frame_d5b66ec9cfc93e1f58efb95eff9f6083->m_frame.f_lineno = 53; tmp_or_right_value_1 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_1, tmp_kw_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_or_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 53; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } tmp_assign_source_1 = tmp_or_right_value_1; goto or_end_1; or_left_1:; Py_INCREF( tmp_or_left_value_1 ); tmp_assign_source_1 = tmp_or_left_value_1; or_end_1:; { PyObject *old = par_connection; par_connection = tmp_assign_source_1; Py_XDECREF( old ); } tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives ); if (unlikely( tmp_called_name_2 == NULL )) { tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives ); } if ( tmp_called_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "EmailMultiAlternatives" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 58; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } tmp_args_name_1 = PyTuple_New( 4 ); tmp_tuple_element_1 = par_subject; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "subject" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 58; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_1 ); tmp_tuple_element_1 = par_message; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 58; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 1, tmp_tuple_element_1 ); tmp_tuple_element_1 = par_from_email; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "from_email" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 58; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 2, tmp_tuple_element_1 ); tmp_tuple_element_1 = par_recipient_list; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "recipient_list" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 58; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 3, tmp_tuple_element_1 ); tmp_kw_name_2 = _PyDict_NewPresized( 1 ); tmp_dict_key_4 = const_str_plain_connection; tmp_dict_value_4 = par_connection; CHECK_OBJECT( tmp_dict_value_4 ); tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_4, tmp_dict_value_4 ); assert( !(tmp_res != 0) ); frame_d5b66ec9cfc93e1f58efb95eff9f6083->m_frame.f_lineno = 58; tmp_assign_source_2 = CALL_FUNCTION( tmp_called_name_2, tmp_args_name_1, tmp_kw_name_2 ); Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_2 ); if ( tmp_assign_source_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 58; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } assert( var_mail == NULL ); var_mail = tmp_assign_source_2; tmp_cond_value_1 = par_html_message; if ( tmp_cond_value_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "html_message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 59; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 59; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_1 == 1 ) { goto branch_yes_1; } else { goto branch_no_1; } branch_yes_1:; tmp_source_name_1 = var_mail; CHECK_OBJECT( tmp_source_name_1 ); tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_attach_alternative ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 60; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = par_html_message; if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_3 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "html_message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 60; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } tmp_args_element_name_2 = const_str_digest_aee0d40e09f76fd339276e187b4cadfd; frame_d5b66ec9cfc93e1f58efb95eff9f6083->m_frame.f_lineno = 60; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_3, call_args ); } Py_DECREF( tmp_called_name_3 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 60; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); branch_no_1:; tmp_called_instance_1 = var_mail; if ( tmp_called_instance_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mail" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 62; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } frame_d5b66ec9cfc93e1f58efb95eff9f6083->m_frame.f_lineno = 62; tmp_return_value = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_send ); if ( tmp_return_value == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 62; type_description_1 = "oooooooooo"; goto frame_exception_exit_1; } goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_d5b66ec9cfc93e1f58efb95eff9f6083, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_d5b66ec9cfc93e1f58efb95eff9f6083->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_d5b66ec9cfc93e1f58efb95eff9f6083, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_d5b66ec9cfc93e1f58efb95eff9f6083, type_description_1, par_subject, par_message, par_from_email, par_recipient_list, par_fail_silently, par_auth_user, par_auth_password, par_connection, par_html_message, var_mail ); // Release cached frame. if ( frame_d5b66ec9cfc93e1f58efb95eff9f6083 == cache_frame_d5b66ec9cfc93e1f58efb95eff9f6083 ) { Py_DECREF( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ); } cache_frame_d5b66ec9cfc93e1f58efb95eff9f6083 = NULL; assertFrameObject( frame_d5b66ec9cfc93e1f58efb95eff9f6083 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_2_send_mail ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_subject ); par_subject = NULL; Py_XDECREF( par_message ); par_message = NULL; Py_XDECREF( par_from_email ); par_from_email = NULL; Py_XDECREF( par_recipient_list ); par_recipient_list = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_auth_user ); par_auth_user = NULL; Py_XDECREF( par_auth_password ); par_auth_password = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( par_html_message ); par_html_message = NULL; Py_XDECREF( var_mail ); var_mail = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_subject ); par_subject = NULL; Py_XDECREF( par_message ); par_message = NULL; Py_XDECREF( par_from_email ); par_from_email = NULL; Py_XDECREF( par_recipient_list ); par_recipient_list = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_auth_user ); par_auth_user = NULL; Py_XDECREF( par_auth_password ); par_auth_password = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( par_html_message ); par_html_message = NULL; Py_XDECREF( var_mail ); var_mail = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_2_send_mail ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$core$mail$$$function_3_send_mass_mail( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_datatuple = python_pars[ 0 ]; PyObject *par_fail_silently = python_pars[ 1 ]; PyObject *par_auth_user = python_pars[ 2 ]; PyObject *par_auth_password = python_pars[ 3 ]; PyObject *par_connection = python_pars[ 4 ]; PyObject *var_messages = NULL; PyObject *outline_0_var_subject = NULL; PyObject *outline_0_var_message = NULL; PyObject *outline_0_var_sender = NULL; PyObject *outline_0_var_recipient = NULL; PyObject *tmp_listcontraction$tuple_unpack_1__element_1 = NULL; PyObject *tmp_listcontraction$tuple_unpack_1__element_2 = NULL; PyObject *tmp_listcontraction$tuple_unpack_1__element_3 = NULL; PyObject *tmp_listcontraction$tuple_unpack_1__element_4 = NULL; PyObject *tmp_listcontraction$tuple_unpack_1__source_iter = NULL; PyObject *tmp_listcontraction_1__$0 = NULL; PyObject *tmp_listcontraction_1__contraction = NULL; PyObject *tmp_listcontraction_1__iter_value_0 = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *exception_keeper_type_4; PyObject *exception_keeper_value_4; PyTracebackObject *exception_keeper_tb_4; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4; PyObject *exception_keeper_type_5; PyObject *exception_keeper_value_5; PyTracebackObject *exception_keeper_tb_5; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_5; PyObject *tmp_append_list_1; PyObject *tmp_append_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_name_1; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; PyObject *tmp_dict_key_1; PyObject *tmp_dict_key_2; PyObject *tmp_dict_key_3; PyObject *tmp_dict_key_4; PyObject *tmp_dict_value_1; PyObject *tmp_dict_value_2; PyObject *tmp_dict_value_3; PyObject *tmp_dict_value_4; PyObject *tmp_iter_arg_1; PyObject *tmp_iter_arg_2; PyObject *tmp_iterator_attempt; PyObject *tmp_iterator_name_1; PyObject *tmp_kw_name_1; PyObject *tmp_kw_name_2; PyObject *tmp_next_source_1; int tmp_or_left_truth_1; PyObject *tmp_or_left_value_1; PyObject *tmp_or_right_value_1; PyObject *tmp_outline_return_value_1; int tmp_res; PyObject *tmp_return_value; PyObject *tmp_source_name_1; PyObject *tmp_tuple_element_1; PyObject *tmp_unpack_1; PyObject *tmp_unpack_2; PyObject *tmp_unpack_3; PyObject *tmp_unpack_4; static struct Nuitka_FrameObject *cache_frame_511a530df6fb7b210e19e3f73001044f_2 = NULL; struct Nuitka_FrameObject *frame_511a530df6fb7b210e19e3f73001044f_2; static struct Nuitka_FrameObject *cache_frame_5c792633ed03c3d658263f44aa2b1415 = NULL; struct Nuitka_FrameObject *frame_5c792633ed03c3d658263f44aa2b1415; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL; tmp_return_value = NULL; tmp_outline_return_value_1 = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_5c792633ed03c3d658263f44aa2b1415, codeobj_5c792633ed03c3d658263f44aa2b1415, module_django$core$mail, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_5c792633ed03c3d658263f44aa2b1415 = cache_frame_5c792633ed03c3d658263f44aa2b1415; // Push the new frame as the currently active one. pushFrameStack( frame_5c792633ed03c3d658263f44aa2b1415 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_5c792633ed03c3d658263f44aa2b1415 ) == 2 ); // Frame stack // Framed code: tmp_or_left_value_1 = par_connection; CHECK_OBJECT( tmp_or_left_value_1 ); tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 ); if ( tmp_or_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 79; type_description_1 = "oooooo"; goto frame_exception_exit_1; } if ( tmp_or_left_truth_1 == 1 ) { goto or_left_1; } else { goto or_right_1; } or_right_1:; tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_get_connection ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_get_connection ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "get_connection" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 79; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_kw_name_1 = _PyDict_NewPresized( 3 ); tmp_dict_key_1 = const_str_plain_username; tmp_dict_value_1 = par_auth_user; CHECK_OBJECT( tmp_dict_value_1 ); tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 ); assert( !(tmp_res != 0) ); tmp_dict_key_2 = const_str_plain_password; tmp_dict_value_2 = par_auth_password; CHECK_OBJECT( tmp_dict_value_2 ); tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_2, tmp_dict_value_2 ); assert( !(tmp_res != 0) ); tmp_dict_key_3 = const_str_plain_fail_silently; tmp_dict_value_3 = par_fail_silently; CHECK_OBJECT( tmp_dict_value_3 ); tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_3, tmp_dict_value_3 ); assert( !(tmp_res != 0) ); frame_5c792633ed03c3d658263f44aa2b1415->m_frame.f_lineno = 79; tmp_or_right_value_1 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_1, tmp_kw_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_or_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 79; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_assign_source_1 = tmp_or_right_value_1; goto or_end_1; or_left_1:; Py_INCREF( tmp_or_left_value_1 ); tmp_assign_source_1 = tmp_or_left_value_1; or_end_1:; { PyObject *old = par_connection; par_connection = tmp_assign_source_1; Py_XDECREF( old ); } // Tried code: tmp_iter_arg_1 = par_datatuple; if ( tmp_iter_arg_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "datatuple" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 86; type_description_1 = "oooooo"; goto try_except_handler_2; } tmp_assign_source_3 = MAKE_ITERATOR( tmp_iter_arg_1 ); if ( tmp_assign_source_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; type_description_1 = "oooooo"; goto try_except_handler_2; } assert( tmp_listcontraction_1__$0 == NULL ); tmp_listcontraction_1__$0 = tmp_assign_source_3; tmp_assign_source_4 = PyList_New( 0 ); assert( tmp_listcontraction_1__contraction == NULL ); tmp_listcontraction_1__contraction = tmp_assign_source_4; MAKE_OR_REUSE_FRAME( cache_frame_511a530df6fb7b210e19e3f73001044f_2, codeobj_511a530df6fb7b210e19e3f73001044f, module_django$core$mail, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_511a530df6fb7b210e19e3f73001044f_2 = cache_frame_511a530df6fb7b210e19e3f73001044f_2; // Push the new frame as the currently active one. pushFrameStack( frame_511a530df6fb7b210e19e3f73001044f_2 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_511a530df6fb7b210e19e3f73001044f_2 ) == 2 ); // Frame stack // Framed code: // Tried code: loop_start_1:; tmp_next_source_1 = tmp_listcontraction_1__$0; CHECK_OBJECT( tmp_next_source_1 ); tmp_assign_source_5 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_5 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_3; } } { PyObject *old = tmp_listcontraction_1__iter_value_0; tmp_listcontraction_1__iter_value_0 = tmp_assign_source_5; Py_XDECREF( old ); } // Tried code: tmp_iter_arg_2 = tmp_listcontraction_1__iter_value_0; CHECK_OBJECT( tmp_iter_arg_2 ); tmp_assign_source_6 = MAKE_ITERATOR( tmp_iter_arg_2 ); if ( tmp_assign_source_6 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_4; } { PyObject *old = tmp_listcontraction$tuple_unpack_1__source_iter; tmp_listcontraction$tuple_unpack_1__source_iter = tmp_assign_source_6; Py_XDECREF( old ); } // Tried code: tmp_unpack_1 = tmp_listcontraction$tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_1 ); tmp_assign_source_7 = UNPACK_NEXT( tmp_unpack_1, 0, 4 ); if ( tmp_assign_source_7 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_5; } { PyObject *old = tmp_listcontraction$tuple_unpack_1__element_1; tmp_listcontraction$tuple_unpack_1__element_1 = tmp_assign_source_7; Py_XDECREF( old ); } tmp_unpack_2 = tmp_listcontraction$tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_2 ); tmp_assign_source_8 = UNPACK_NEXT( tmp_unpack_2, 1, 4 ); if ( tmp_assign_source_8 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_5; } { PyObject *old = tmp_listcontraction$tuple_unpack_1__element_2; tmp_listcontraction$tuple_unpack_1__element_2 = tmp_assign_source_8; Py_XDECREF( old ); } tmp_unpack_3 = tmp_listcontraction$tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_3 ); tmp_assign_source_9 = UNPACK_NEXT( tmp_unpack_3, 2, 4 ); if ( tmp_assign_source_9 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_5; } { PyObject *old = tmp_listcontraction$tuple_unpack_1__element_3; tmp_listcontraction$tuple_unpack_1__element_3 = tmp_assign_source_9; Py_XDECREF( old ); } tmp_unpack_4 = tmp_listcontraction$tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_unpack_4 ); tmp_assign_source_10 = UNPACK_NEXT( tmp_unpack_4, 3, 4 ); if ( tmp_assign_source_10 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_5; } { PyObject *old = tmp_listcontraction$tuple_unpack_1__element_4; tmp_listcontraction$tuple_unpack_1__element_4 = tmp_assign_source_10; Py_XDECREF( old ); } tmp_iterator_name_1 = tmp_listcontraction$tuple_unpack_1__source_iter; CHECK_OBJECT( tmp_iterator_name_1 ); // Check if iterator has left-over elements. CHECK_OBJECT( tmp_iterator_name_1 ); assert( HAS_ITERNEXT( tmp_iterator_name_1 ) ); tmp_iterator_attempt = (*Py_TYPE( tmp_iterator_name_1 )->tp_iternext)( tmp_iterator_name_1 ); if (likely( tmp_iterator_attempt == NULL )) { PyObject *error = GET_ERROR_OCCURRED(); if ( error != NULL ) { if ( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration )) { CLEAR_ERROR_OCCURRED(); } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_5; } } } else { Py_DECREF( tmp_iterator_attempt ); // TODO: Could avoid PyErr_Format. #if PYTHON_VERSION < 300 PyErr_Format( PyExc_ValueError, "too many values to unpack" ); #else PyErr_Format( PyExc_ValueError, "too many values to unpack (expected 4)" ); #endif FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); type_description_2 = "oooooo"; exception_lineno = 85; goto try_except_handler_5; } goto try_end_1; // Exception handler code: try_except_handler_5:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__source_iter ); tmp_listcontraction$tuple_unpack_1__source_iter = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto try_except_handler_4; // End of try: try_end_1:; goto try_end_2; // Exception handler code: try_except_handler_4:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_1 ); tmp_listcontraction$tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_2 ); tmp_listcontraction$tuple_unpack_1__element_2 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_3 ); tmp_listcontraction$tuple_unpack_1__element_3 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_4 ); tmp_listcontraction$tuple_unpack_1__element_4 = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto try_except_handler_3; // End of try: try_end_2:; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__source_iter ); tmp_listcontraction$tuple_unpack_1__source_iter = NULL; tmp_assign_source_11 = tmp_listcontraction$tuple_unpack_1__element_1; CHECK_OBJECT( tmp_assign_source_11 ); { PyObject *old = outline_0_var_subject; outline_0_var_subject = tmp_assign_source_11; Py_INCREF( outline_0_var_subject ); Py_XDECREF( old ); } Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_1 ); tmp_listcontraction$tuple_unpack_1__element_1 = NULL; tmp_assign_source_12 = tmp_listcontraction$tuple_unpack_1__element_2; CHECK_OBJECT( tmp_assign_source_12 ); { PyObject *old = outline_0_var_message; outline_0_var_message = tmp_assign_source_12; Py_INCREF( outline_0_var_message ); Py_XDECREF( old ); } Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_2 ); tmp_listcontraction$tuple_unpack_1__element_2 = NULL; tmp_assign_source_13 = tmp_listcontraction$tuple_unpack_1__element_3; CHECK_OBJECT( tmp_assign_source_13 ); { PyObject *old = outline_0_var_sender; outline_0_var_sender = tmp_assign_source_13; Py_INCREF( outline_0_var_sender ); Py_XDECREF( old ); } Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_3 ); tmp_listcontraction$tuple_unpack_1__element_3 = NULL; tmp_assign_source_14 = tmp_listcontraction$tuple_unpack_1__element_4; CHECK_OBJECT( tmp_assign_source_14 ); { PyObject *old = outline_0_var_recipient; outline_0_var_recipient = tmp_assign_source_14; Py_INCREF( outline_0_var_recipient ); Py_XDECREF( old ); } Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_4 ); tmp_listcontraction$tuple_unpack_1__element_4 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_1 ); tmp_listcontraction$tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_2 ); tmp_listcontraction$tuple_unpack_1__element_2 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_3 ); tmp_listcontraction$tuple_unpack_1__element_3 = NULL; Py_XDECREF( tmp_listcontraction$tuple_unpack_1__element_4 ); tmp_listcontraction$tuple_unpack_1__element_4 = NULL; tmp_append_list_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_append_list_1 ); tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_EmailMessage ); if (unlikely( tmp_called_name_2 == NULL )) { tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_EmailMessage ); } if ( tmp_called_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "EmailMessage" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } tmp_args_name_1 = PyTuple_New( 4 ); tmp_tuple_element_1 = outline_0_var_subject; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "subject" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_1 ); tmp_tuple_element_1 = outline_0_var_message; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 1, tmp_tuple_element_1 ); tmp_tuple_element_1 = outline_0_var_sender; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "sender" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 2, tmp_tuple_element_1 ); tmp_tuple_element_1 = outline_0_var_recipient; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "recipient" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 3, tmp_tuple_element_1 ); tmp_kw_name_2 = _PyDict_NewPresized( 1 ); tmp_dict_key_4 = const_str_plain_connection; tmp_dict_value_4 = par_connection; if ( tmp_dict_value_4 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_2 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "connection" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_4, tmp_dict_value_4 ); assert( !(tmp_res != 0) ); frame_511a530df6fb7b210e19e3f73001044f_2->m_frame.f_lineno = 85; tmp_append_value_1 = CALL_FUNCTION( tmp_called_name_2, tmp_args_name_1, tmp_kw_name_2 ); Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_2 ); if ( tmp_append_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } assert( PyList_Check( tmp_append_list_1 ) ); tmp_res = PyList_Append( tmp_append_list_1, tmp_append_value_1 ); Py_DECREF( tmp_append_value_1 ); if ( tmp_res == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 85; type_description_2 = "oooooo"; goto try_except_handler_3; } goto loop_start_1; loop_end_1:; tmp_outline_return_value_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_outline_return_value_1 ); Py_INCREF( tmp_outline_return_value_1 ); goto try_return_handler_3; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_3_send_mass_mail ); return NULL; // Return handler code: try_return_handler_3:; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; goto frame_return_exit_2; // Exception handler code: try_except_handler_3:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto frame_exception_exit_2; // End of try: #if 0 RESTORE_FRAME_EXCEPTION( frame_511a530df6fb7b210e19e3f73001044f_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_511a530df6fb7b210e19e3f73001044f_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_2; frame_exception_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_511a530df6fb7b210e19e3f73001044f_2 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_511a530df6fb7b210e19e3f73001044f_2, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_511a530df6fb7b210e19e3f73001044f_2->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_511a530df6fb7b210e19e3f73001044f_2, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_511a530df6fb7b210e19e3f73001044f_2, type_description_2, outline_0_var_subject, outline_0_var_message, outline_0_var_sender, outline_0_var_recipient, par_datatuple, par_connection ); // Release cached frame. if ( frame_511a530df6fb7b210e19e3f73001044f_2 == cache_frame_511a530df6fb7b210e19e3f73001044f_2 ) { Py_DECREF( frame_511a530df6fb7b210e19e3f73001044f_2 ); } cache_frame_511a530df6fb7b210e19e3f73001044f_2 = NULL; assertFrameObject( frame_511a530df6fb7b210e19e3f73001044f_2 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto nested_frame_exit_1; frame_no_exception_1:; goto skip_nested_handling_1; nested_frame_exit_1:; type_description_1 = "oooooo"; goto try_except_handler_2; skip_nested_handling_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_3_send_mass_mail ); return NULL; // Return handler code: try_return_handler_2:; Py_XDECREF( outline_0_var_subject ); outline_0_var_subject = NULL; Py_XDECREF( outline_0_var_message ); outline_0_var_message = NULL; Py_XDECREF( outline_0_var_sender ); outline_0_var_sender = NULL; Py_XDECREF( outline_0_var_recipient ); outline_0_var_recipient = NULL; goto outline_result_1; // Exception handler code: try_except_handler_2:; exception_keeper_type_4 = exception_type; exception_keeper_value_4 = exception_value; exception_keeper_tb_4 = exception_tb; exception_keeper_lineno_4 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( outline_0_var_subject ); outline_0_var_subject = NULL; Py_XDECREF( outline_0_var_message ); outline_0_var_message = NULL; Py_XDECREF( outline_0_var_sender ); outline_0_var_sender = NULL; Py_XDECREF( outline_0_var_recipient ); outline_0_var_recipient = NULL; // Re-raise. exception_type = exception_keeper_type_4; exception_value = exception_keeper_value_4; exception_tb = exception_keeper_tb_4; exception_lineno = exception_keeper_lineno_4; goto outline_exception_1; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_3_send_mass_mail ); return NULL; outline_exception_1:; exception_lineno = 85; goto frame_exception_exit_1; outline_result_1:; tmp_assign_source_2 = tmp_outline_return_value_1; assert( var_messages == NULL ); var_messages = tmp_assign_source_2; tmp_source_name_1 = par_connection; if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "connection" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_send_messages ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = var_messages; if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_3 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "messages" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; type_description_1 = "oooooo"; goto frame_exception_exit_1; } frame_5c792633ed03c3d658263f44aa2b1415->m_frame.f_lineno = 88; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args ); } Py_DECREF( tmp_called_name_3 ); if ( tmp_return_value == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; type_description_1 = "oooooo"; goto frame_exception_exit_1; } goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_5c792633ed03c3d658263f44aa2b1415 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_2; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_5c792633ed03c3d658263f44aa2b1415 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_5c792633ed03c3d658263f44aa2b1415 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_5c792633ed03c3d658263f44aa2b1415, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_5c792633ed03c3d658263f44aa2b1415->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_5c792633ed03c3d658263f44aa2b1415, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_5c792633ed03c3d658263f44aa2b1415, type_description_1, par_datatuple, par_fail_silently, par_auth_user, par_auth_password, par_connection, var_messages ); // Release cached frame. if ( frame_5c792633ed03c3d658263f44aa2b1415 == cache_frame_5c792633ed03c3d658263f44aa2b1415 ) { Py_DECREF( frame_5c792633ed03c3d658263f44aa2b1415 ); } cache_frame_5c792633ed03c3d658263f44aa2b1415 = NULL; assertFrameObject( frame_5c792633ed03c3d658263f44aa2b1415 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_2:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_3_send_mass_mail ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_datatuple ); par_datatuple = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_auth_user ); par_auth_user = NULL; Py_XDECREF( par_auth_password ); par_auth_password = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( var_messages ); var_messages = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_5 = exception_type; exception_keeper_value_5 = exception_value; exception_keeper_tb_5 = exception_tb; exception_keeper_lineno_5 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_datatuple ); par_datatuple = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_auth_user ); par_auth_user = NULL; Py_XDECREF( par_auth_password ); par_auth_password = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( var_messages ); var_messages = NULL; // Re-raise. exception_type = exception_keeper_type_5; exception_value = exception_keeper_value_5; exception_tb = exception_keeper_tb_5; exception_lineno = exception_keeper_lineno_5; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_3_send_mass_mail ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$core$mail$$$function_4_mail_admins( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_subject = python_pars[ 0 ]; PyObject *par_message = python_pars[ 1 ]; PyObject *par_fail_silently = python_pars[ 2 ]; PyObject *par_connection = python_pars[ 3 ]; PyObject *par_html_message = python_pars[ 4 ]; PyObject *var_mail = NULL; PyObject *outline_0_var_a = NULL; PyObject *tmp_listcontraction_1__$0 = NULL; PyObject *tmp_listcontraction_1__contraction = NULL; PyObject *tmp_listcontraction_1__iter_value_0 = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *tmp_append_list_1; PyObject *tmp_append_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_name_1; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; int tmp_cond_truth_1; int tmp_cond_truth_2; PyObject *tmp_cond_value_1; PyObject *tmp_cond_value_2; PyObject *tmp_dict_key_1; PyObject *tmp_dict_key_2; PyObject *tmp_dict_value_1; PyObject *tmp_dict_value_2; PyObject *tmp_iter_arg_1; PyObject *tmp_kw_name_1; PyObject *tmp_kw_name_2; PyObject *tmp_left_name_1; PyObject *tmp_next_source_1; PyObject *tmp_outline_return_value_1; int tmp_res; PyObject *tmp_return_value; PyObject *tmp_right_name_1; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; PyObject *tmp_source_name_4; PyObject *tmp_source_name_5; PyObject *tmp_source_name_6; PyObject *tmp_subscribed_name_1; PyObject *tmp_subscript_name_1; PyObject *tmp_tuple_element_1; PyObject *tmp_tuple_element_2; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; static struct Nuitka_FrameObject *cache_frame_640ccb64c145fa6c4f28093fc71d23ea_2 = NULL; struct Nuitka_FrameObject *frame_640ccb64c145fa6c4f28093fc71d23ea_2; static struct Nuitka_FrameObject *cache_frame_69337f3a07aa8f8d6dbfef3ec162d3a3 = NULL; struct Nuitka_FrameObject *frame_69337f3a07aa8f8d6dbfef3ec162d3a3; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL; tmp_return_value = NULL; tmp_outline_return_value_1 = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_69337f3a07aa8f8d6dbfef3ec162d3a3, codeobj_69337f3a07aa8f8d6dbfef3ec162d3a3, module_django$core$mail, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_69337f3a07aa8f8d6dbfef3ec162d3a3 = cache_frame_69337f3a07aa8f8d6dbfef3ec162d3a3; // Push the new frame as the currently active one. pushFrameStack( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ) == 2 ); // Frame stack // Framed code: tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 94; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_cond_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_ADMINS ); if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 94; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 94; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_return_value = Py_None; Py_INCREF( tmp_return_value ); goto frame_return_exit_1; branch_no_1:; tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "EmailMultiAlternatives" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 96; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_name_1 = PyTuple_New( 4 ); tmp_left_name_1 = const_str_digest_d76462298f66c95b4d3ee22e9427a916; tmp_right_name_1 = PyTuple_New( 2 ); tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_2 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_right_name_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 97; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_tuple_element_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_EMAIL_SUBJECT_PREFIX ); if ( tmp_tuple_element_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_right_name_1 ); exception_lineno = 97; type_description_1 = "oooooo"; goto frame_exception_exit_1; } PyTuple_SET_ITEM( tmp_right_name_1, 0, tmp_tuple_element_2 ); tmp_tuple_element_2 = par_subject; if ( tmp_tuple_element_2 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_right_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "subject" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 97; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_2 ); PyTuple_SET_ITEM( tmp_right_name_1, 1, tmp_tuple_element_2 ); tmp_tuple_element_1 = BINARY_OPERATION_REMAINDER( tmp_left_name_1, tmp_right_name_1 ); Py_DECREF( tmp_right_name_1 ); if ( tmp_tuple_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_args_name_1 ); exception_lineno = 97; type_description_1 = "oooooo"; goto frame_exception_exit_1; } PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_1 ); tmp_tuple_element_1 = par_message; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 97; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 1, tmp_tuple_element_1 ); tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_3 == NULL )) { tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_3 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 98; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_tuple_element_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_SERVER_EMAIL ); if ( tmp_tuple_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_args_name_1 ); exception_lineno = 98; type_description_1 = "oooooo"; goto frame_exception_exit_1; } PyTuple_SET_ITEM( tmp_args_name_1, 2, tmp_tuple_element_1 ); // Tried code: tmp_source_name_4 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_4 == NULL )) { tmp_source_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_4 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 98; type_description_1 = "oooooo"; goto try_except_handler_2; } tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_ADMINS ); if ( tmp_iter_arg_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_1 = "oooooo"; goto try_except_handler_2; } tmp_assign_source_2 = MAKE_ITERATOR( tmp_iter_arg_1 ); Py_DECREF( tmp_iter_arg_1 ); if ( tmp_assign_source_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_1 = "oooooo"; goto try_except_handler_2; } assert( tmp_listcontraction_1__$0 == NULL ); tmp_listcontraction_1__$0 = tmp_assign_source_2; tmp_assign_source_3 = PyList_New( 0 ); assert( tmp_listcontraction_1__contraction == NULL ); tmp_listcontraction_1__contraction = tmp_assign_source_3; MAKE_OR_REUSE_FRAME( cache_frame_640ccb64c145fa6c4f28093fc71d23ea_2, codeobj_640ccb64c145fa6c4f28093fc71d23ea, module_django$core$mail, sizeof(void *) ); frame_640ccb64c145fa6c4f28093fc71d23ea_2 = cache_frame_640ccb64c145fa6c4f28093fc71d23ea_2; // Push the new frame as the currently active one. pushFrameStack( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ) == 2 ); // Frame stack // Framed code: // Tried code: loop_start_1:; tmp_next_source_1 = tmp_listcontraction_1__$0; CHECK_OBJECT( tmp_next_source_1 ); tmp_assign_source_4 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_4 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); type_description_2 = "o"; exception_lineno = 98; goto try_except_handler_3; } } { PyObject *old = tmp_listcontraction_1__iter_value_0; tmp_listcontraction_1__iter_value_0 = tmp_assign_source_4; Py_XDECREF( old ); } tmp_assign_source_5 = tmp_listcontraction_1__iter_value_0; CHECK_OBJECT( tmp_assign_source_5 ); { PyObject *old = outline_0_var_a; outline_0_var_a = tmp_assign_source_5; Py_INCREF( outline_0_var_a ); Py_XDECREF( old ); } tmp_append_list_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_append_list_1 ); tmp_subscribed_name_1 = outline_0_var_a; CHECK_OBJECT( tmp_subscribed_name_1 ); tmp_subscript_name_1 = const_int_pos_1; tmp_append_value_1 = LOOKUP_SUBSCRIPT( tmp_subscribed_name_1, tmp_subscript_name_1 ); if ( tmp_append_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_2 = "o"; goto try_except_handler_3; } assert( PyList_Check( tmp_append_list_1 ) ); tmp_res = PyList_Append( tmp_append_list_1, tmp_append_value_1 ); Py_DECREF( tmp_append_value_1 ); if ( tmp_res == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_2 = "o"; goto try_except_handler_3; } if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_2 = "o"; goto try_except_handler_3; } goto loop_start_1; loop_end_1:; tmp_outline_return_value_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_outline_return_value_1 ); Py_INCREF( tmp_outline_return_value_1 ); goto try_return_handler_3; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_4_mail_admins ); return NULL; // Return handler code: try_return_handler_3:; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; goto frame_return_exit_2; // Exception handler code: try_except_handler_3:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto frame_exception_exit_2; // End of try: #if 0 RESTORE_FRAME_EXCEPTION( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_2; frame_exception_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_640ccb64c145fa6c4f28093fc71d23ea_2, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_640ccb64c145fa6c4f28093fc71d23ea_2->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_640ccb64c145fa6c4f28093fc71d23ea_2, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_640ccb64c145fa6c4f28093fc71d23ea_2, type_description_2, outline_0_var_a ); // Release cached frame. if ( frame_640ccb64c145fa6c4f28093fc71d23ea_2 == cache_frame_640ccb64c145fa6c4f28093fc71d23ea_2 ) { Py_DECREF( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ); } cache_frame_640ccb64c145fa6c4f28093fc71d23ea_2 = NULL; assertFrameObject( frame_640ccb64c145fa6c4f28093fc71d23ea_2 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto nested_frame_exit_1; frame_no_exception_1:; goto skip_nested_handling_1; nested_frame_exit_1:; type_description_1 = "oooooo"; goto try_except_handler_2; skip_nested_handling_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_4_mail_admins ); return NULL; // Return handler code: try_return_handler_2:; Py_XDECREF( outline_0_var_a ); outline_0_var_a = NULL; goto outline_result_1; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( outline_0_var_a ); outline_0_var_a = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto outline_exception_1; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_4_mail_admins ); return NULL; outline_exception_1:; exception_lineno = 98; goto frame_exception_exit_1; outline_result_1:; tmp_tuple_element_1 = tmp_outline_return_value_1; PyTuple_SET_ITEM( tmp_args_name_1, 3, tmp_tuple_element_1 ); tmp_kw_name_1 = _PyDict_NewPresized( 1 ); tmp_dict_key_1 = const_str_plain_connection; tmp_dict_value_1 = par_connection; if ( tmp_dict_value_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "connection" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 99; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 ); assert( !(tmp_res != 0) ); frame_69337f3a07aa8f8d6dbfef3ec162d3a3->m_frame.f_lineno = 96; tmp_assign_source_1 = CALL_FUNCTION( tmp_called_name_1, tmp_args_name_1, tmp_kw_name_1 ); Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 96; type_description_1 = "oooooo"; goto frame_exception_exit_1; } assert( var_mail == NULL ); var_mail = tmp_assign_source_1; tmp_cond_value_2 = par_html_message; if ( tmp_cond_value_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "html_message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 101; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 ); if ( tmp_cond_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 101; type_description_1 = "oooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_2 == 1 ) { goto branch_yes_2; } else { goto branch_no_2; } branch_yes_2:; tmp_source_name_5 = var_mail; CHECK_OBJECT( tmp_source_name_5 ); tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_attach_alternative ); if ( tmp_called_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 102; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = par_html_message; if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "html_message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 102; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_element_name_2 = const_str_digest_aee0d40e09f76fd339276e187b4cadfd; frame_69337f3a07aa8f8d6dbfef3ec162d3a3->m_frame.f_lineno = 102; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args ); } Py_DECREF( tmp_called_name_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 102; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); branch_no_2:; tmp_source_name_6 = var_mail; if ( tmp_source_name_6 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mail" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 103; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_send ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 103; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_kw_name_2 = _PyDict_NewPresized( 1 ); tmp_dict_key_2 = const_str_plain_fail_silently; tmp_dict_value_2 = par_fail_silently; if ( tmp_dict_value_2 == NULL ) { Py_DECREF( tmp_called_name_3 ); Py_DECREF( tmp_kw_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "fail_silently" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 103; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_2, tmp_dict_value_2 ); assert( !(tmp_res != 0) ); frame_69337f3a07aa8f8d6dbfef3ec162d3a3->m_frame.f_lineno = 103; tmp_unused = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_3, tmp_kw_name_2 ); Py_DECREF( tmp_called_name_3 ); Py_DECREF( tmp_kw_name_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 103; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); #if 0 RESTORE_FRAME_EXCEPTION( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_2; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_69337f3a07aa8f8d6dbfef3ec162d3a3, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_69337f3a07aa8f8d6dbfef3ec162d3a3->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_69337f3a07aa8f8d6dbfef3ec162d3a3, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_69337f3a07aa8f8d6dbfef3ec162d3a3, type_description_1, par_subject, par_message, par_fail_silently, par_connection, par_html_message, var_mail ); // Release cached frame. if ( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 == cache_frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ) { Py_DECREF( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ); } cache_frame_69337f3a07aa8f8d6dbfef3ec162d3a3 = NULL; assertFrameObject( frame_69337f3a07aa8f8d6dbfef3ec162d3a3 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_2:; tmp_return_value = Py_None; Py_INCREF( tmp_return_value ); goto try_return_handler_1; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_4_mail_admins ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_subject ); par_subject = NULL; Py_XDECREF( par_message ); par_message = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( par_html_message ); par_html_message = NULL; Py_XDECREF( var_mail ); var_mail = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_subject ); par_subject = NULL; Py_XDECREF( par_message ); par_message = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( par_html_message ); par_html_message = NULL; Py_XDECREF( var_mail ); var_mail = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_4_mail_admins ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$core$mail$$$function_5_mail_managers( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_subject = python_pars[ 0 ]; PyObject *par_message = python_pars[ 1 ]; PyObject *par_fail_silently = python_pars[ 2 ]; PyObject *par_connection = python_pars[ 3 ]; PyObject *par_html_message = python_pars[ 4 ]; PyObject *var_mail = NULL; PyObject *outline_0_var_a = NULL; PyObject *tmp_listcontraction_1__$0 = NULL; PyObject *tmp_listcontraction_1__contraction = NULL; PyObject *tmp_listcontraction_1__iter_value_0 = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *tmp_append_list_1; PyObject *tmp_append_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_name_1; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; int tmp_cond_truth_1; int tmp_cond_truth_2; PyObject *tmp_cond_value_1; PyObject *tmp_cond_value_2; PyObject *tmp_dict_key_1; PyObject *tmp_dict_key_2; PyObject *tmp_dict_value_1; PyObject *tmp_dict_value_2; PyObject *tmp_iter_arg_1; PyObject *tmp_kw_name_1; PyObject *tmp_kw_name_2; PyObject *tmp_left_name_1; PyObject *tmp_next_source_1; PyObject *tmp_outline_return_value_1; int tmp_res; PyObject *tmp_return_value; PyObject *tmp_right_name_1; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; PyObject *tmp_source_name_4; PyObject *tmp_source_name_5; PyObject *tmp_source_name_6; PyObject *tmp_subscribed_name_1; PyObject *tmp_subscript_name_1; PyObject *tmp_tuple_element_1; PyObject *tmp_tuple_element_2; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; static struct Nuitka_FrameObject *cache_frame_65b05b6a0873b6b3ab5a6d198716577e_2 = NULL; struct Nuitka_FrameObject *frame_65b05b6a0873b6b3ab5a6d198716577e_2; static struct Nuitka_FrameObject *cache_frame_cc13755fb2b4acdcd7f6f7d182ab7a34 = NULL; struct Nuitka_FrameObject *frame_cc13755fb2b4acdcd7f6f7d182ab7a34; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL; tmp_return_value = NULL; tmp_outline_return_value_1 = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_cc13755fb2b4acdcd7f6f7d182ab7a34, codeobj_cc13755fb2b4acdcd7f6f7d182ab7a34, module_django$core$mail, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_cc13755fb2b4acdcd7f6f7d182ab7a34 = cache_frame_cc13755fb2b4acdcd7f6f7d182ab7a34; // Push the new frame as the currently active one. pushFrameStack( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ) == 2 ); // Frame stack // Framed code: tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 109; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_cond_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_MANAGERS ); if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 109; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 109; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_return_value = Py_None; Py_INCREF( tmp_return_value ); goto frame_return_exit_1; branch_no_1:; tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "EmailMultiAlternatives" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 111; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_name_1 = PyTuple_New( 4 ); tmp_left_name_1 = const_str_digest_d76462298f66c95b4d3ee22e9427a916; tmp_right_name_1 = PyTuple_New( 2 ); tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_2 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_right_name_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 112; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_tuple_element_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_EMAIL_SUBJECT_PREFIX ); if ( tmp_tuple_element_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_right_name_1 ); exception_lineno = 112; type_description_1 = "oooooo"; goto frame_exception_exit_1; } PyTuple_SET_ITEM( tmp_right_name_1, 0, tmp_tuple_element_2 ); tmp_tuple_element_2 = par_subject; if ( tmp_tuple_element_2 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_right_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "subject" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 112; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_2 ); PyTuple_SET_ITEM( tmp_right_name_1, 1, tmp_tuple_element_2 ); tmp_tuple_element_1 = BINARY_OPERATION_REMAINDER( tmp_left_name_1, tmp_right_name_1 ); Py_DECREF( tmp_right_name_1 ); if ( tmp_tuple_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_args_name_1 ); exception_lineno = 112; type_description_1 = "oooooo"; goto frame_exception_exit_1; } PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_1 ); tmp_tuple_element_1 = par_message; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 112; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_args_name_1, 1, tmp_tuple_element_1 ); tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_3 == NULL )) { tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_3 == NULL ) { Py_DECREF( tmp_args_name_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 113; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_tuple_element_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_SERVER_EMAIL ); if ( tmp_tuple_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_args_name_1 ); exception_lineno = 113; type_description_1 = "oooooo"; goto frame_exception_exit_1; } PyTuple_SET_ITEM( tmp_args_name_1, 2, tmp_tuple_element_1 ); // Tried code: tmp_source_name_4 = GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings ); if (unlikely( tmp_source_name_4 == NULL )) { tmp_source_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_settings ); } if ( tmp_source_name_4 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "settings" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 113; type_description_1 = "oooooo"; goto try_except_handler_2; } tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_MANAGERS ); if ( tmp_iter_arg_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 113; type_description_1 = "oooooo"; goto try_except_handler_2; } tmp_assign_source_2 = MAKE_ITERATOR( tmp_iter_arg_1 ); Py_DECREF( tmp_iter_arg_1 ); if ( tmp_assign_source_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 113; type_description_1 = "oooooo"; goto try_except_handler_2; } assert( tmp_listcontraction_1__$0 == NULL ); tmp_listcontraction_1__$0 = tmp_assign_source_2; tmp_assign_source_3 = PyList_New( 0 ); assert( tmp_listcontraction_1__contraction == NULL ); tmp_listcontraction_1__contraction = tmp_assign_source_3; MAKE_OR_REUSE_FRAME( cache_frame_65b05b6a0873b6b3ab5a6d198716577e_2, codeobj_65b05b6a0873b6b3ab5a6d198716577e, module_django$core$mail, sizeof(void *) ); frame_65b05b6a0873b6b3ab5a6d198716577e_2 = cache_frame_65b05b6a0873b6b3ab5a6d198716577e_2; // Push the new frame as the currently active one. pushFrameStack( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ) == 2 ); // Frame stack // Framed code: // Tried code: loop_start_1:; tmp_next_source_1 = tmp_listcontraction_1__$0; CHECK_OBJECT( tmp_next_source_1 ); tmp_assign_source_4 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_4 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); type_description_2 = "o"; exception_lineno = 113; goto try_except_handler_3; } } { PyObject *old = tmp_listcontraction_1__iter_value_0; tmp_listcontraction_1__iter_value_0 = tmp_assign_source_4; Py_XDECREF( old ); } tmp_assign_source_5 = tmp_listcontraction_1__iter_value_0; CHECK_OBJECT( tmp_assign_source_5 ); { PyObject *old = outline_0_var_a; outline_0_var_a = tmp_assign_source_5; Py_INCREF( outline_0_var_a ); Py_XDECREF( old ); } tmp_append_list_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_append_list_1 ); tmp_subscribed_name_1 = outline_0_var_a; CHECK_OBJECT( tmp_subscribed_name_1 ); tmp_subscript_name_1 = const_int_pos_1; tmp_append_value_1 = LOOKUP_SUBSCRIPT( tmp_subscribed_name_1, tmp_subscript_name_1 ); if ( tmp_append_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 113; type_description_2 = "o"; goto try_except_handler_3; } assert( PyList_Check( tmp_append_list_1 ) ); tmp_res = PyList_Append( tmp_append_list_1, tmp_append_value_1 ); Py_DECREF( tmp_append_value_1 ); if ( tmp_res == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 113; type_description_2 = "o"; goto try_except_handler_3; } if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 113; type_description_2 = "o"; goto try_except_handler_3; } goto loop_start_1; loop_end_1:; tmp_outline_return_value_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_outline_return_value_1 ); Py_INCREF( tmp_outline_return_value_1 ); goto try_return_handler_3; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_5_mail_managers ); return NULL; // Return handler code: try_return_handler_3:; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; goto frame_return_exit_2; // Exception handler code: try_except_handler_3:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto frame_exception_exit_2; // End of try: #if 0 RESTORE_FRAME_EXCEPTION( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_2; frame_exception_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_65b05b6a0873b6b3ab5a6d198716577e_2, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_65b05b6a0873b6b3ab5a6d198716577e_2->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_65b05b6a0873b6b3ab5a6d198716577e_2, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_65b05b6a0873b6b3ab5a6d198716577e_2, type_description_2, outline_0_var_a ); // Release cached frame. if ( frame_65b05b6a0873b6b3ab5a6d198716577e_2 == cache_frame_65b05b6a0873b6b3ab5a6d198716577e_2 ) { Py_DECREF( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ); } cache_frame_65b05b6a0873b6b3ab5a6d198716577e_2 = NULL; assertFrameObject( frame_65b05b6a0873b6b3ab5a6d198716577e_2 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto nested_frame_exit_1; frame_no_exception_1:; goto skip_nested_handling_1; nested_frame_exit_1:; type_description_1 = "oooooo"; goto try_except_handler_2; skip_nested_handling_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_5_mail_managers ); return NULL; // Return handler code: try_return_handler_2:; Py_XDECREF( outline_0_var_a ); outline_0_var_a = NULL; goto outline_result_1; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( outline_0_var_a ); outline_0_var_a = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto outline_exception_1; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_5_mail_managers ); return NULL; outline_exception_1:; exception_lineno = 113; goto frame_exception_exit_1; outline_result_1:; tmp_tuple_element_1 = tmp_outline_return_value_1; PyTuple_SET_ITEM( tmp_args_name_1, 3, tmp_tuple_element_1 ); tmp_kw_name_1 = _PyDict_NewPresized( 1 ); tmp_dict_key_1 = const_str_plain_connection; tmp_dict_value_1 = par_connection; if ( tmp_dict_value_1 == NULL ) { Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "connection" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 114; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 ); assert( !(tmp_res != 0) ); frame_cc13755fb2b4acdcd7f6f7d182ab7a34->m_frame.f_lineno = 111; tmp_assign_source_1 = CALL_FUNCTION( tmp_called_name_1, tmp_args_name_1, tmp_kw_name_1 ); Py_DECREF( tmp_args_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 111; type_description_1 = "oooooo"; goto frame_exception_exit_1; } assert( var_mail == NULL ); var_mail = tmp_assign_source_1; tmp_cond_value_2 = par_html_message; if ( tmp_cond_value_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "html_message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 116; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 ); if ( tmp_cond_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 116; type_description_1 = "oooooo"; goto frame_exception_exit_1; } if ( tmp_cond_truth_2 == 1 ) { goto branch_yes_2; } else { goto branch_no_2; } branch_yes_2:; tmp_source_name_5 = var_mail; CHECK_OBJECT( tmp_source_name_5 ); tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_attach_alternative ); if ( tmp_called_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 117; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = par_html_message; if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "html_message" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 117; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_args_element_name_2 = const_str_digest_aee0d40e09f76fd339276e187b4cadfd; frame_cc13755fb2b4acdcd7f6f7d182ab7a34->m_frame.f_lineno = 117; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args ); } Py_DECREF( tmp_called_name_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 117; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); branch_no_2:; tmp_source_name_6 = var_mail; if ( tmp_source_name_6 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "mail" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 118; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_send ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 118; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_kw_name_2 = _PyDict_NewPresized( 1 ); tmp_dict_key_2 = const_str_plain_fail_silently; tmp_dict_value_2 = par_fail_silently; if ( tmp_dict_value_2 == NULL ) { Py_DECREF( tmp_called_name_3 ); Py_DECREF( tmp_kw_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "fail_silently" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 118; type_description_1 = "oooooo"; goto frame_exception_exit_1; } tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_2, tmp_dict_value_2 ); assert( !(tmp_res != 0) ); frame_cc13755fb2b4acdcd7f6f7d182ab7a34->m_frame.f_lineno = 118; tmp_unused = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_3, tmp_kw_name_2 ); Py_DECREF( tmp_called_name_3 ); Py_DECREF( tmp_kw_name_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 118; type_description_1 = "oooooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); #if 0 RESTORE_FRAME_EXCEPTION( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_2; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_cc13755fb2b4acdcd7f6f7d182ab7a34, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_cc13755fb2b4acdcd7f6f7d182ab7a34->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_cc13755fb2b4acdcd7f6f7d182ab7a34, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_cc13755fb2b4acdcd7f6f7d182ab7a34, type_description_1, par_subject, par_message, par_fail_silently, par_connection, par_html_message, var_mail ); // Release cached frame. if ( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 == cache_frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ) { Py_DECREF( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ); } cache_frame_cc13755fb2b4acdcd7f6f7d182ab7a34 = NULL; assertFrameObject( frame_cc13755fb2b4acdcd7f6f7d182ab7a34 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_2:; tmp_return_value = Py_None; Py_INCREF( tmp_return_value ); goto try_return_handler_1; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_5_mail_managers ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_subject ); par_subject = NULL; Py_XDECREF( par_message ); par_message = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( par_html_message ); par_html_message = NULL; Py_XDECREF( var_mail ); var_mail = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_subject ); par_subject = NULL; Py_XDECREF( par_message ); par_message = NULL; Py_XDECREF( par_fail_silently ); par_fail_silently = NULL; Py_XDECREF( par_connection ); par_connection = NULL; Py_XDECREF( par_html_message ); par_html_message = NULL; Py_XDECREF( var_mail ); var_mail = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$core$mail$$$function_5_mail_managers ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *MAKE_FUNCTION_django$core$mail$$$function_1_get_connection( PyObject *defaults ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$core$mail$$$function_1_get_connection, const_str_plain_get_connection, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_face192665c41b1d3945cbf1913f54a4, defaults, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$core$mail, const_str_digest_dcd9259d193a76e79fad54e9e1350333, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$core$mail$$$function_2_send_mail( PyObject *defaults ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$core$mail$$$function_2_send_mail, const_str_plain_send_mail, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_d5b66ec9cfc93e1f58efb95eff9f6083, defaults, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$core$mail, const_str_digest_361587de2a9b7265a8610c25a42e22b5, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$core$mail$$$function_3_send_mass_mail( PyObject *defaults ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$core$mail$$$function_3_send_mass_mail, const_str_plain_send_mass_mail, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_5c792633ed03c3d658263f44aa2b1415, defaults, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$core$mail, const_str_digest_7b409349ae9bcff87319817b7154920c, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$core$mail$$$function_4_mail_admins( PyObject *defaults ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$core$mail$$$function_4_mail_admins, const_str_plain_mail_admins, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_69337f3a07aa8f8d6dbfef3ec162d3a3, defaults, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$core$mail, const_str_digest_3f07db178fdeee72a253dae658423338, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$core$mail$$$function_5_mail_managers( PyObject *defaults ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$core$mail$$$function_5_mail_managers, const_str_plain_mail_managers, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_cc13755fb2b4acdcd7f6f7d182ab7a34, defaults, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$core$mail, const_str_digest_daae6d9876cd0712c83b7035415ef6dd, 0 ); return (PyObject *)result; } #if PYTHON_VERSION >= 300 static struct PyModuleDef mdef_django$core$mail = { PyModuleDef_HEAD_INIT, "django.core.mail", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PYTHON_VERSION >= 300 extern PyObject *metapath_based_loader; #endif #if PYTHON_VERSION >= 330 extern PyObject *const_str_plain___loader__; #endif extern void _initCompiledCellType(); extern void _initCompiledGeneratorType(); extern void _initCompiledFunctionType(); extern void _initCompiledMethodType(); extern void _initCompiledFrameType(); #if PYTHON_VERSION >= 350 extern void _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 extern void _initCompiledAsyncgenTypes(); #endif // The exported interface to CPython. On import of the module, this function // gets called. It has to have an exact function name, in cases it's a shared // library export. This is hidden behind the MOD_INIT_DECL. MOD_INIT_DECL( django$core$mail ) { #if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300 static bool _init_done = false; // Modules might be imported repeatedly, which is to be ignored. if ( _init_done ) { return MOD_RETURN_VALUE( module_django$core$mail ); } else { _init_done = true; } #endif #ifdef _NUITKA_MODULE // In case of a stand alone extension module, need to call initialization // the init here because that's the first and only time we are going to get // called here. // Initialize the constant values used. _initBuiltinModule(); createGlobalConstants(); /* Initialize the compiled types of Nuitka. */ _initCompiledCellType(); _initCompiledGeneratorType(); _initCompiledFunctionType(); _initCompiledMethodType(); _initCompiledFrameType(); #if PYTHON_VERSION >= 350 _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 _initCompiledAsyncgenTypes(); #endif #if PYTHON_VERSION < 300 _initSlotCompare(); #endif #if PYTHON_VERSION >= 270 _initSlotIternext(); #endif patchBuiltinModule(); patchTypeComparison(); // Enable meta path based loader if not already done. setupMetaPathBasedLoader(); #if PYTHON_VERSION >= 300 patchInspectModule(); #endif #endif /* The constants only used by this module are created now. */ #ifdef _NUITKA_TRACE puts("django.core.mail: Calling createModuleConstants()."); #endif createModuleConstants(); /* The code objects used by this module are created now. */ #ifdef _NUITKA_TRACE puts("django.core.mail: Calling createModuleCodeObjects()."); #endif createModuleCodeObjects(); // puts( "in initdjango$core$mail" ); // Create the module object first. There are no methods initially, all are // added dynamically in actual code only. Also no "__doc__" is initially // set at this time, as it could not contain NUL characters this way, they // are instead set in early module code. No "self" for modules, we have no // use for it. #if PYTHON_VERSION < 300 module_django$core$mail = Py_InitModule4( "django.core.mail", // Module Name NULL, // No methods initially, all are added // dynamically in actual module code only. NULL, // No __doc__ is initially set, as it could // not contain NUL this way, added early in // actual code. NULL, // No self for modules, we don't use it. PYTHON_API_VERSION ); #else module_django$core$mail = PyModule_Create( &mdef_django$core$mail ); #endif moduledict_django$core$mail = MODULE_DICT( module_django$core$mail ); CHECK_OBJECT( module_django$core$mail ); // Seems to work for Python2.7 out of the box, but for Python3, the module // doesn't automatically enter "sys.modules", so do it manually. #if PYTHON_VERSION >= 300 { int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_d434fa92832494458af57a18e30eeae3, module_django$core$mail ); assert( r != -1 ); } #endif // For deep importing of a module we need to have "__builtins__", so we set // it ourselves in the same way than CPython does. Note: This must be done // before the frame object is allocated, or else it may fail. if ( GET_STRING_DICT_VALUE( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL ) { PyObject *value = (PyObject *)builtin_module; // Check if main module, not a dict then but the module itself. #if !defined(_NUITKA_EXE) || !0 value = PyModule_GetDict( value ); #endif UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___builtins__, value ); } #if PYTHON_VERSION >= 330 UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader ); #endif // Temp variables if any PyObject *tmp_import_from_1__module = NULL; PyObject *tmp_import_from_2__module = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_element_name_3; PyObject *tmp_args_element_name_4; PyObject *tmp_args_element_name_5; PyObject *tmp_args_element_name_6; PyObject *tmp_args_element_name_7; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_assign_source_15; PyObject *tmp_assign_source_16; PyObject *tmp_assign_source_17; PyObject *tmp_assign_source_18; PyObject *tmp_assign_source_19; PyObject *tmp_assign_source_20; PyObject *tmp_assign_source_21; PyObject *tmp_assign_source_22; PyObject *tmp_assign_source_23; PyObject *tmp_assign_source_24; PyObject *tmp_assign_source_25; PyObject *tmp_assign_source_26; PyObject *tmp_assign_source_27; PyObject *tmp_assign_source_28; PyObject *tmp_called_instance_1; PyObject *tmp_called_instance_2; PyObject *tmp_called_instance_3; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; PyObject *tmp_called_name_4; PyObject *tmp_defaults_1; PyObject *tmp_defaults_2; PyObject *tmp_defaults_3; PyObject *tmp_defaults_4; PyObject *tmp_defaults_5; PyObject *tmp_fromlist_name_1; PyObject *tmp_fromlist_name_2; PyObject *tmp_fromlist_name_3; PyObject *tmp_fromlist_name_4; PyObject *tmp_globals_name_1; PyObject *tmp_globals_name_2; PyObject *tmp_globals_name_3; PyObject *tmp_globals_name_4; PyObject *tmp_import_name_from_1; PyObject *tmp_import_name_from_2; PyObject *tmp_import_name_from_3; PyObject *tmp_import_name_from_4; PyObject *tmp_import_name_from_5; PyObject *tmp_import_name_from_6; PyObject *tmp_import_name_from_7; PyObject *tmp_import_name_from_8; PyObject *tmp_import_name_from_9; PyObject *tmp_import_name_from_10; PyObject *tmp_import_name_from_11; PyObject *tmp_import_name_from_12; PyObject *tmp_import_name_from_13; PyObject *tmp_level_name_1; PyObject *tmp_level_name_2; PyObject *tmp_level_name_3; PyObject *tmp_level_name_4; PyObject *tmp_list_element_1; PyObject *tmp_locals_name_1; PyObject *tmp_locals_name_2; PyObject *tmp_locals_name_3; PyObject *tmp_locals_name_4; PyObject *tmp_name_name_1; PyObject *tmp_name_name_2; PyObject *tmp_name_name_3; PyObject *tmp_name_name_4; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; struct Nuitka_FrameObject *frame_53e53520558709b487bf2d0ddb5e2347; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; // Module code. tmp_assign_source_1 = const_str_digest_234b289f937c6961c780f32ea2f04b3f; UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 ); tmp_assign_source_2 = module_filename_obj; UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 ); // Frame without reuse. frame_53e53520558709b487bf2d0ddb5e2347 = MAKE_MODULE_FRAME( codeobj_53e53520558709b487bf2d0ddb5e2347, module_django$core$mail ); // Push the new frame as the currently active one, and we should be exclusively // owning it. pushFrameStack( frame_53e53520558709b487bf2d0ddb5e2347 ); assert( Py_REFCNT( frame_53e53520558709b487bf2d0ddb5e2347 ) == 2 ); // Framed code: tmp_assign_source_3 = PyList_New( 4 ); frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("os"); if (likely( module != NULL )) { tmp_source_name_1 = PyObject_GetAttr( module, const_str_plain_path ); } else { tmp_source_name_1 = NULL; } } if ( tmp_source_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_dirname ); if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_1 = module_filename_obj; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args ); } Py_DECREF( tmp_called_name_1 ); if ( tmp_list_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } PyList_SET_ITEM( tmp_assign_source_3, 0, tmp_list_element_1 ); frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("os"); if (likely( module != NULL )) { tmp_source_name_2 = PyObject_GetAttr( module, const_str_plain_path ); } else { tmp_source_name_2 = NULL; } } if ( tmp_source_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_join ); if ( tmp_called_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("os"); if (likely( module != NULL )) { tmp_called_instance_1 = PyObject_GetAttr( module, const_str_plain_environ ); } else { tmp_called_instance_1 = NULL; } } if ( tmp_called_instance_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); Py_DECREF( tmp_called_name_2 ); exception_lineno = 1; goto frame_exception_exit_1; } frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; tmp_args_element_name_2 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_1, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_c15243b3ba68498da186d5d65ae367ca_tuple, 0 ) ); if ( tmp_args_element_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); Py_DECREF( tmp_called_name_2 ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_3 = const_str_digest_3bc9cd3436adbed05aeee30a149a984b; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_2, tmp_args_element_name_3 }; tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args ); } Py_DECREF( tmp_called_name_2 ); Py_DECREF( tmp_args_element_name_2 ); if ( tmp_list_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } PyList_SET_ITEM( tmp_assign_source_3, 1, tmp_list_element_1 ); frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("os"); if (likely( module != NULL )) { tmp_source_name_3 = PyObject_GetAttr( module, const_str_plain_path ); } else { tmp_source_name_3 = NULL; } } if ( tmp_source_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_join ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("os"); if (likely( module != NULL )) { tmp_called_instance_2 = PyObject_GetAttr( module, const_str_plain_environ ); } else { tmp_called_instance_2 = NULL; } } if ( tmp_called_instance_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); Py_DECREF( tmp_called_name_3 ); exception_lineno = 1; goto frame_exception_exit_1; } frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; tmp_args_element_name_4 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_2, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_b868c6b0937f28ff9b15f6cc52ff2098_tuple, 0 ) ); if ( tmp_args_element_name_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); Py_DECREF( tmp_called_name_3 ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_5 = const_str_plain_mail; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_4, tmp_args_element_name_5 }; tmp_list_element_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_3, call_args ); } Py_DECREF( tmp_called_name_3 ); Py_DECREF( tmp_args_element_name_4 ); if ( tmp_list_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } PyList_SET_ITEM( tmp_assign_source_3, 2, tmp_list_element_1 ); frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("os"); if (likely( module != NULL )) { tmp_called_instance_3 = PyObject_GetAttr( module, const_str_plain_environ ); } else { tmp_called_instance_3 = NULL; } } if ( tmp_called_instance_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; tmp_list_element_1 = CALL_METHOD_WITH_ARGS2( tmp_called_instance_3, const_str_plain_get, &PyTuple_GET_ITEM( const_tuple_75a15e879c7a8bd34659463d4ddb0ad9_tuple, 0 ) ); if ( tmp_list_element_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_assign_source_3 ); exception_lineno = 1; goto frame_exception_exit_1; } PyList_SET_ITEM( tmp_assign_source_3, 3, tmp_list_element_1 ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___path__, tmp_assign_source_3 ); tmp_assign_source_4 = metapath_based_loader; UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_4 ); frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("importlib._bootstrap"); if (likely( module != NULL )) { tmp_called_name_4 = PyObject_GetAttr( module, const_str_plain_ModuleSpec ); } else { tmp_called_name_4 = NULL; } } if ( tmp_called_name_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_6 = const_str_digest_d434fa92832494458af57a18e30eeae3; tmp_args_element_name_7 = metapath_based_loader; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 }; tmp_assign_source_5 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_4, call_args ); } if ( tmp_assign_source_5 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_5 ); tmp_assign_source_6 = Py_None; UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_6 ); tmp_assign_source_7 = const_str_digest_d434fa92832494458af57a18e30eeae3; UPDATE_STRING_DICT0( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_7 ); frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 4; tmp_import_name_from_1 = PyImport_ImportModule("__future__"); assert( tmp_import_name_from_1 != NULL ); tmp_assign_source_8 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_unicode_literals ); if ( tmp_assign_source_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 4; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_8 ); tmp_name_name_1 = const_str_digest_e2cff0983efd969a5767cadcc9e9f0e8; tmp_globals_name_1 = (PyObject *)moduledict_django$core$mail; tmp_locals_name_1 = Py_None; tmp_fromlist_name_1 = const_tuple_str_plain_settings_tuple; tmp_level_name_1 = const_int_0; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 6; tmp_import_name_from_2 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 ); if ( tmp_import_name_from_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto frame_exception_exit_1; } tmp_assign_source_9 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_settings ); Py_DECREF( tmp_import_name_from_2 ); if ( tmp_assign_source_9 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_settings, tmp_assign_source_9 ); tmp_name_name_2 = const_str_digest_1572198cb22a44b444ca284ab3fb285b; tmp_globals_name_2 = (PyObject *)moduledict_django$core$mail; tmp_locals_name_2 = Py_None; tmp_fromlist_name_2 = const_tuple_5bc1bc8adf0bed8c300dc21a6ec2bfdc_tuple; tmp_level_name_2 = const_int_0; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 11; tmp_assign_source_10 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 ); if ( tmp_assign_source_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto frame_exception_exit_1; } assert( tmp_import_from_1__module == NULL ); tmp_import_from_1__module = tmp_assign_source_10; // Tried code: tmp_import_name_from_3 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_3 ); tmp_assign_source_11 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE ); if ( tmp_assign_source_11 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_DEFAULT_ATTACHMENT_MIME_TYPE, tmp_assign_source_11 ); tmp_import_name_from_4 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_4 ); tmp_assign_source_12 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_BadHeaderError ); if ( tmp_assign_source_12 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_BadHeaderError, tmp_assign_source_12 ); tmp_import_name_from_5 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_5 ); tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_EmailMessage ); if ( tmp_assign_source_13 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_EmailMessage, tmp_assign_source_13 ); tmp_import_name_from_6 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_6 ); tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_EmailMultiAlternatives ); if ( tmp_assign_source_14 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_EmailMultiAlternatives, tmp_assign_source_14 ); tmp_import_name_from_7 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_7 ); tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_7, const_str_plain_SafeMIMEMultipart ); if ( tmp_assign_source_15 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_SafeMIMEMultipart, tmp_assign_source_15 ); tmp_import_name_from_8 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_8 ); tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_8, const_str_plain_SafeMIMEText ); if ( tmp_assign_source_16 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_SafeMIMEText, tmp_assign_source_16 ); tmp_import_name_from_9 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_9 ); tmp_assign_source_17 = IMPORT_NAME( tmp_import_name_from_9, const_str_plain_forbid_multi_line_headers ); if ( tmp_assign_source_17 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_forbid_multi_line_headers, tmp_assign_source_17 ); tmp_import_name_from_10 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_10 ); tmp_assign_source_18 = IMPORT_NAME( tmp_import_name_from_10, const_str_plain_make_msgid ); if ( tmp_assign_source_18 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 11; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_make_msgid, tmp_assign_source_18 ); goto try_end_1; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_import_from_1__module ); tmp_import_from_1__module = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto frame_exception_exit_1; // End of try: try_end_1:; Py_XDECREF( tmp_import_from_1__module ); tmp_import_from_1__module = NULL; tmp_name_name_3 = const_str_digest_5f972e9cea97219805947b4127aeae11; tmp_globals_name_3 = (PyObject *)moduledict_django$core$mail; tmp_locals_name_3 = Py_None; tmp_fromlist_name_3 = const_tuple_str_plain_DNS_NAME_str_plain_CachedDnsName_tuple; tmp_level_name_3 = const_int_0; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 16; tmp_assign_source_19 = IMPORT_MODULE5( tmp_name_name_3, tmp_globals_name_3, tmp_locals_name_3, tmp_fromlist_name_3, tmp_level_name_3 ); if ( tmp_assign_source_19 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 16; goto frame_exception_exit_1; } assert( tmp_import_from_2__module == NULL ); tmp_import_from_2__module = tmp_assign_source_19; // Tried code: tmp_import_name_from_11 = tmp_import_from_2__module; CHECK_OBJECT( tmp_import_name_from_11 ); tmp_assign_source_20 = IMPORT_NAME( tmp_import_name_from_11, const_str_plain_DNS_NAME ); if ( tmp_assign_source_20 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 16; goto try_except_handler_2; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_DNS_NAME, tmp_assign_source_20 ); tmp_import_name_from_12 = tmp_import_from_2__module; CHECK_OBJECT( tmp_import_name_from_12 ); tmp_assign_source_21 = IMPORT_NAME( tmp_import_name_from_12, const_str_plain_CachedDnsName ); if ( tmp_assign_source_21 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 16; goto try_except_handler_2; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_CachedDnsName, tmp_assign_source_21 ); goto try_end_2; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_import_from_2__module ); tmp_import_from_2__module = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto frame_exception_exit_1; // End of try: try_end_2:; Py_XDECREF( tmp_import_from_2__module ); tmp_import_from_2__module = NULL; tmp_name_name_4 = const_str_digest_690178e17eae3581689f22974cc26edf; tmp_globals_name_4 = (PyObject *)moduledict_django$core$mail; tmp_locals_name_4 = Py_None; tmp_fromlist_name_4 = const_tuple_str_plain_import_string_tuple; tmp_level_name_4 = const_int_0; frame_53e53520558709b487bf2d0ddb5e2347->m_frame.f_lineno = 17; tmp_import_name_from_13 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 ); if ( tmp_import_name_from_13 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 17; goto frame_exception_exit_1; } tmp_assign_source_22 = IMPORT_NAME( tmp_import_name_from_13, const_str_plain_import_string ); Py_DECREF( tmp_import_name_from_13 ); if ( tmp_assign_source_22 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 17; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_import_string, tmp_assign_source_22 ); // Restore frame exception if necessary. #if 0 RESTORE_FRAME_EXCEPTION( frame_53e53520558709b487bf2d0ddb5e2347 ); #endif popFrameStack(); assertFrameObject( frame_53e53520558709b487bf2d0ddb5e2347 ); goto frame_no_exception_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_53e53520558709b487bf2d0ddb5e2347 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_53e53520558709b487bf2d0ddb5e2347, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_53e53520558709b487bf2d0ddb5e2347->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_53e53520558709b487bf2d0ddb5e2347, exception_lineno ); } // Put the previous frame back on top. popFrameStack(); // Return the error. goto module_exception_exit; frame_no_exception_1:; tmp_assign_source_23 = LIST_COPY( const_list_2a56c87d4d1b4ea30b58df6b484f8201_list ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain___all__, tmp_assign_source_23 ); tmp_defaults_1 = const_tuple_none_false_tuple; Py_INCREF( tmp_defaults_1 ); tmp_assign_source_24 = MAKE_FUNCTION_django$core$mail$$$function_1_get_connection( tmp_defaults_1 ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_get_connection, tmp_assign_source_24 ); tmp_defaults_2 = const_tuple_false_none_none_none_none_tuple; Py_INCREF( tmp_defaults_2 ); tmp_assign_source_25 = MAKE_FUNCTION_django$core$mail$$$function_2_send_mail( tmp_defaults_2 ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_send_mail, tmp_assign_source_25 ); tmp_defaults_3 = const_tuple_false_none_none_none_tuple; Py_INCREF( tmp_defaults_3 ); tmp_assign_source_26 = MAKE_FUNCTION_django$core$mail$$$function_3_send_mass_mail( tmp_defaults_3 ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_send_mass_mail, tmp_assign_source_26 ); tmp_defaults_4 = const_tuple_false_none_none_tuple; Py_INCREF( tmp_defaults_4 ); tmp_assign_source_27 = MAKE_FUNCTION_django$core$mail$$$function_4_mail_admins( tmp_defaults_4 ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_mail_admins, tmp_assign_source_27 ); tmp_defaults_5 = const_tuple_false_none_none_tuple; Py_INCREF( tmp_defaults_5 ); tmp_assign_source_28 = MAKE_FUNCTION_django$core$mail$$$function_5_mail_managers( tmp_defaults_5 ); UPDATE_STRING_DICT1( moduledict_django$core$mail, (Nuitka_StringObject *)const_str_plain_mail_managers, tmp_assign_source_28 ); return MOD_RETURN_VALUE( module_django$core$mail ); module_exception_exit: RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return MOD_RETURN_VALUE( NULL ); }
34.997797
290
0.72738
[ "object" ]
3509fa2bae26215206b6c369d6c460429d972eb1
8,284
cpp
C++
competition-analysis/data-parser/parse_submission_file_dynamic.cpp
Satendra01/CEC2013
3f88a03fb407e52046233588169ea81c4716a1ed
[ "BSD-2-Clause-FreeBSD" ]
65
2016-04-07T10:53:45.000Z
2022-03-21T00:48:32.000Z
competition-analysis/data-parser/parse_submission_file_dynamic.cpp
Satendra01/CEC2013
3f88a03fb407e52046233588169ea81c4716a1ed
[ "BSD-2-Clause-FreeBSD" ]
5
2016-08-29T01:52:20.000Z
2020-09-04T04:10:54.000Z
competition-analysis/data-parser/parse_submission_file_dynamic.cpp
Satendra01/CEC2013
3f88a03fb407e52046233588169ea81c4716a1ed
[ "BSD-2-Clause-FreeBSD" ]
56
2015-08-08T04:24:05.000Z
2022-02-28T08:43:11.000Z
/****************************************************************************** * Version: 1.0.2 * Last modified on: 10 July, 2019 * Developers: Michael G. Epitropakis * email: m_(DOT)_epitropakis_(AT)_gmail_(DOT)_com * ***************************************************************************/ #include <iostream> #include <cstdlib> #include <vector> #include <cstring> #include <fstream> #include <sstream> #include <iomanip> #include <utility> #include <map> #include <string> #include "cec2013.h" #include "params.h" typedef std::vector< std::vector< std::vector<double> > > Array3D; typedef std::vector< std::vector<double> > Array2D; typedef std::pair< std::vector<double>, std::vector<double> > TwoVectors; typedef std::multimap< std::string, TwoVectors > archive; using namespace std; std::string vector_to_string(const std::vector<double> & vec); std::string operator+(const string& a, const string& b); void load_file_with_archive_action(const std::string filename, std::vector< std::vector<double> > &data, const int &dim); int read_data_line(const std::vector<double> &data, TwoVectors &result, const int &dim) ; void init_memory(Array3D &results, Array2D &PR, Array2D &SR, const int &problems, const int &noruns, const int &noacc); void calculate_number_of_goptima_per_acc_run_get_result(std::vector<double> &results, const Array2D &pop, const int &noacc, const double *acclevels, CEC2013 *pFunc); std::string int_to_string_with_leading_zeros(int no, size_t orders_of_magnitute) { std::ostringstream ss; ss << setw(orders_of_magnitute) << setfill('0') << no; return ss.str(); } static bool header = true; int main(int argc, char **argv) { parameters p(argc, argv); const int noruns = p.noruns, problems = p.problems, noacc = 5; double acclevels[noacc] = {0.1, 0.01, 0.001, 0.0001, 0.00001}; std::string outfilename(p.outfilename), respath(p.respath+"/"), algname(p.algname); Array3D results; Array2D PR, SR, pop, costs, all_dists, data; std::vector<double> fitnesses; init_memory(results, PR, SR, problems, noruns, noacc); /* for each functions */ CEC2013 *pFunc; for (int index = 1; index <= 20; ++index) { /* Create one */ pFunc = new CEC2013(index); const unsigned int dim = pFunc->get_dimension(); cout << "F_" << index << ": "; // load global optima Array2D goptima = pFunc->get_copy_of_goptima(); /* for each run */ for (int irun = 0; irun < noruns; ++irun) { cout << "."; /* Create data structures and read data from files */ pop.clear(); costs.clear(); data.clear(); //Parse: respath = algorithms/cma/ + problem001run001.dat string tmpfilename = respath + "problem" + int_to_string_with_leading_zeros(index,3) + "run" + int_to_string_with_leading_zeros(irun+1,3) + ".dat"; /* Load file */ load_file_with_archive_action(tmpfilename, data, dim); /* sort based on FEs */ std::sort(data.begin(), data.end(), [](const std::vector<double>& a, const std::vector<double>& b) { return a[a.size()-3] < b[b.size()-3]; }); // create archive archive myarchive; for (unsigned int ii=0; ii< data.size(); ii++) { myarchive.clear(); for (unsigned int jj=0; jj<=ii; jj++) { //cout << data[ii][jj] << "\t"; TwoVectors result; int action = read_data_line(data[jj], result, dim); if (action == 0) { // empty the archive and myarchive.clear(); /// add the new solution std::string key(vector_to_string(result.first)); myarchive.insert( std::pair<std::string, TwoVectors>(key, result) ); } else if (action == 1) { // add the new solution std::string key(vector_to_string(result.first)); myarchive.insert( std::pair<std::string, TwoVectors>(key, result) ); } else if (action == -1) { // search for it and remove it std::string key(vector_to_string(result.first)); archive::iterator it = myarchive.find(key); if (it != myarchive.end()) { // found it myarchive.erase(it); } else { cerr << "WARNING: I could not remove solution at line " << jj << " because it was not in the archive." << endl; } } else { cerr << "ERROR: " << tmpfilename << " contains incorrect archive action index: " << action << " at line: "<< jj << endl; exit(-1); } } Array2D cpop; // add info from archive into pop/costs for (archive::iterator it = myarchive.begin(); it != myarchive.end(); ++it) { cpop.push_back((it->second).first); } std::vector<double> res; // Calculate how many global optima are in the population calculate_number_of_goptima_per_acc_run_get_result(res, cpop, noacc, acclevels, pFunc); // Create data file. // ///////////////////////////////////////////////////////////////////////////////////////// // std::fstream file; std::string filename = p.alldata; if (p.header && header){ file.open(filename.c_str(), std::fstream::out); file << "#algorithm,problem,run,fes,time,"; for (int iacc = 0; iacc < noacc; ++iacc) { file << "numGOacc" << iacc << ","; } file << "numberGO,popsize" << endl; header = false; } else { file.open(filename.c_str(), std::fstream::out | std::fstream::app); } int number_of_goptima = pFunc->get_no_goptima(); file << p.algname << "," << "prob" << index << "," << irun << ","; file << data[ii][data[ii].size()-3] << "," << data[ii][data[ii].size()-2] << ","; for (unsigned int iii=0; iii < res.size(); iii++) { file << res[iii] << ","; } file << number_of_goptima <<"," << cpop.size() << endl; file.close(); } } cout << endl; /* Clean up */ delete pFunc; } return EXIT_SUCCESS; } int read_data_line(const std::vector<double> &data, TwoVectors &result, const int &dim) { vector<double> indi; vector<double> cost; int archive_action; int icounter = 0; for (icounter=0; icounter<dim; ++icounter) { indi.push_back(data[icounter]); } cost.push_back(data[icounter]); // fitness cost.push_back(data[++icounter]); // fes cost.push_back(data[++icounter]); // time archive_action = data[++icounter]; // action result = std::make_pair(indi, cost); return archive_action; } void calculate_number_of_goptima_per_acc_run_get_result(std::vector<double> &results, const Array2D &pop, const int &noacc, const double *acclevels, CEC2013 *pFunc) { int size = pop.size(); /* for each accuracy level */ for (int iacc = 0; iacc < noacc; ++iacc) { /* Calculate how many global optima are in the population */ double accuracy = acclevels[iacc]; std::vector< std::vector<double> > seeds; if (size == 0) { results.push_back(0); } else { int count = how_many_goptima(pop, seeds, pFunc, accuracy, pFunc->get_rho()); results.push_back(count); } } } void init_memory(Array3D &results, Array2D &PR, Array2D &SR, const int &problems, const int &noruns, const int &noacc) { results.resize(problems); PR.resize(problems); SR.resize(problems); for (int i=0; i<problems; ++i) { results[i].resize(noruns); for (int j=0; j<noruns; ++j) { results[i][j].resize(noacc); } PR[i].resize(noacc); SR[i].resize(noacc); } } void load_file_with_archive_action(const std::string filename, std::vector< std::vector<double> > &data, const int &dim) { std::ifstream file; file.open(filename.c_str(), std::fstream::in); std::string line; while (std::getline(file, line)) { std::istringstream iss(line); vector<double> all; double tmpdbl, fes, time; int archive_action; for (int i=0; i<dim; ++i) { iss >> tmpdbl; all.push_back(tmpdbl); } char tmpchar; iss >> tmpchar; // = iss >> tmpdbl; // fitness iss >> tmpchar; // @ iss >> fes; // fes iss >> time; // time iss >> archive_action; // archive action all.push_back(tmpdbl); all.push_back(fes); all.push_back(time); all.push_back(archive_action); data.push_back(all); } // Close file file.close(); } std::string operator+ (const string& a, const string& b) { std::string result(a); result += b; return result; } std::string vector_to_string(const std::vector<double> & vec) { std::string result = ""; for (int i=0; i< vec.size(); i++) { result += std::to_string(vec[i]); } return result; }
32.108527
126
0.622767
[ "vector" ]
350e64f60999c5b2a85f30c157620e1c495e0d85
3,831
hpp
C++
include/hyperpose/operator/parser/paf.hpp
lengyuner/hyperpose4fly
c9866bce1a0109e1b9c727ca550b5a380eb3ee17
[ "Apache-2.0" ]
null
null
null
include/hyperpose/operator/parser/paf.hpp
lengyuner/hyperpose4fly
c9866bce1a0109e1b9c727ca550b5a380eb3ee17
[ "Apache-2.0" ]
null
null
null
include/hyperpose/operator/parser/paf.hpp
lengyuner/hyperpose4fly
c9866bce1a0109e1b9c727ca550b5a380eb3ee17
[ "Apache-2.0" ]
null
null
null
#pragma once /// \file paf.hpp /// \brief Post-processing using Part Affinity Field (PAF). #include "../../utility/data.hpp" namespace hyperpose { /// \brief The namespace to contain things related to post processing. /// \note In HyperPose, the pose estimation pipeline consists of DNN inference and parsing(post-processing). The /// parser part implementation is under the namespace `hyperpose::parser`. namespace parser { /// \brief Post-processing using Part Affinity Field (PAF). /// \see https://arxiv.org/abs/1812.08008 class paf { public: /// \brief Constructor indicating the image size and thresholds. /// /// \param conf_thresh The activation threshold. /// \param paf_thresh The threshold of Part Affinity Field. /// \param resolution_size The size(width, height) of expected resolution for the post-processing. /// \note Before doing PAF, the (width, height) of feature map will be expanded to `resolution_size` to perform /// a more accurate post processing. And `resolution_size` will be N x the size of first input tensor if it's /// not set. (now, N is 4) explicit paf(float conf_thresh = 0.05, float paf_thresh = 0.05, cv::Size resolution_size = cv::Size(UNINITIALIZED_VAL, UNINITIALIZED_VAL)); /// \brief Function to process one image. /// /// \code /// // Initialization of PAF. /// hyperpose::parser::paf paf_processor(); /// /// // ... /// /// // Do inference. /// // Note that, tensor_pairs.size is equal to the batch_size process. Each of them represents one image. /// auto tensor_pairs = engine.inference(...); // Ordered by tensor name. /// /// for(auto&& tensor_pair/* CONF, PAF */ : tensor_pairs) /// human_topology = paf_processor.process(tensor_pair[0], tensor_pair[1]); /// \endcode /// /// \param conf The conf tensor. /// \param paf The paf tensor. /// \return All human topologies found in "this" image. std::vector<human_t> process(const feature_map_t& conf, const feature_map_t& paf); /// \brief Function to process one image. /// /// \see `hyperpose::paf::process(feature_map_t paf, feature_map_t conf)`. /// \tparam C Container<feature_map_t> /// \param feature_map_containers {CONF, PAF} tensors. /// \return All human topologies found in "this" image. /// \note Template parameter `C` must support `operator[]` as indexing. template <typename C> std::vector<human_t> process(C&& feature_map_containers) { // 1@conf, 2@paf. return process(feature_map_containers[0], feature_map_containers[1]); } /// /// \param thresh The PAF threshold. void set_paf_thresh(float thresh); /// /// \param thresh The CONF threshold. void set_conf_thresh(float thresh); /// \note This copy constructor will only copy the parameters introduces in constructor(`hyperpose::paf`). /// \param p Object to be "copied". paf(const paf& p); /// Deconstructor. ~paf(); private: static constexpr std::nullptr_t UNINITIALIZED_PTR = nullptr; static constexpr int UNINITIALIZED_VAL = -1; float m_conf_thresh, m_paf_thresh; cv::Size m_resolution_size; int m_n_joints = UNINITIALIZED_VAL, m_n_connections = UNINITIALIZED_VAL; cv::Size m_feature_size = { UNINITIALIZED_VAL, UNINITIALIZED_VAL }; struct ttl_impl; std::unique_ptr<ttl_impl> m_ttl; struct peak_finder_impl; std::unique_ptr<peak_finder_impl> m_peak_finder_ptr; }; } // namespace parser } // namespace hyperpose
39.494845
147
0.629079
[ "object", "vector" ]
350fdad24c62b834a51513f2d12737d63961a2c2
2,778
cpp
C++
tests/geometry_moveable.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
2
2015-11-05T20:08:00.000Z
2016-07-07T04:17:07.000Z
tests/geometry_moveable.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
3
2016-10-29T02:20:49.000Z
2017-04-01T11:09:53.000Z
tests/geometry_moveable.cpp
crr0004/terrian_prototype
34b04239ee2fb01e48f1602ff6dd08e8bd26da63
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <fakeit.hpp> #include <glm/ext.hpp> #include <string> #include <fmt/format.h> #include "node.hpp" #include "geometry/moveable.hpp" using namespace fakeit; TEST_CASE("Moveable Visit double dispatch works"){ using namespace Geometry; INode* node1 = new Moveable(); Mock<Geometry::Moveable> mockMoveable; Fake(OverloadedMethod(mockMoveable, visit, int(Moveable*))); Fake(OverloadedMethod(mockMoveable, visit, int(INode*))); INode* node2 = (INode*)&mockMoveable.get(); node1->visit(node2); Verify(OverloadedMethod(mockMoveable, visit, int(Moveable*))); delete node1; } TEST_CASE("Movable All moveable operations cascade to children"){ using namespace Geometry; Moveable root; Moveable child1; Moveable child2; glm::vec3 moveBy = glm::vec3(1.0,2.0,-3.0); glm::vec3 moveBy2 = glm::vec3(2.0,3.0,-4.0); root.add(&child1); child1.add(&child2); root.translate(moveBy); glm::mat4& rootMatrix = *root.getModelMatrix(); glm::mat4 child1Matrix = child1.getCulumativeMatrix(); glm::mat4 child2Matrix = child2.getCulumativeMatrix(); REQUIRE(rootMatrix[3][0] == moveBy[0]); REQUIRE(rootMatrix[3][1] == moveBy[1]); REQUIRE(rootMatrix[3][2] == moveBy[2]); //child1 gets transformed by rootMatrix REQUIRE(child1Matrix[3][0] == rootMatrix[3][0]); REQUIRE(child1Matrix[3][1] == rootMatrix[3][1]); REQUIRE(child1Matrix[3][2] == rootMatrix[3][2]); //child2 gets transformed by rootMatrix REQUIRE(child2Matrix[3][0] == rootMatrix[3][0]); REQUIRE(child2Matrix[3][1] == rootMatrix[3][1]); REQUIRE(child2Matrix[3][2] == rootMatrix[3][2]); //child2 gets transformed by rootMatrix and child1 child1.translate(moveBy2); child2Matrix = child2.getCulumativeMatrix(); REQUIRE(child2Matrix[3][0] == rootMatrix[3][0] + moveBy2[0]); REQUIRE(child2Matrix[3][1] == rootMatrix[3][1] + moveBy2[1]); REQUIRE(child2Matrix[3][2] == rootMatrix[3][2] + moveBy2[2]); child1.translate(-moveBy2); child1.translate(-moveBy); child1Matrix = child1.getCulumativeMatrix(); REQUIRE(child1Matrix[3][0] == 0.0); REQUIRE(child1Matrix[3][1] == 0.0); REQUIRE(child1Matrix[3][2] == 0.0); } TEST_CASE("Moveable Push and pop matrix works correctly"){ using namespace Geometry; Moveable root; Moveable child1; glm::vec3 moveBy = glm::vec3(1.0,2.0,-3.0); root.add(&child1); glm::mat4& rootMatrix = *root.getModelMatrix(); glm::mat4& child1Matrix = *child1.getModelMatrix(); // root.push(); // root.translate(moveBy); // REQUIRE(child1Matrix[3][0] == rootMatrix[3][0]); // REQUIRE(child1Matrix[3][1] == rootMatrix[3][1]); // REQUIRE(child1Matrix[3][2] == rootMatrix[3][2]); // root.pop(); // REQUIRE(child1Matrix[3][0] == rootMatrix[3][0]); // REQUIRE(child1Matrix[3][1] == rootMatrix[3][1]); // REQUIRE(child1Matrix[3][2] == rootMatrix[3][2]); }
30.866667
65
0.700504
[ "geometry" ]
35109a3a8503be7c6e97a20060dd5cdd983e66dc
4,714
cpp
C++
examples/Verify.cpp
joke325/Cerop
04351582ac626a10d4e2bb1d478d59cb70879571
[ "BSD-2-Clause" ]
null
null
null
examples/Verify.cpp
joke325/Cerop
04351582ac626a10d4e2bb1d478d59cb70879571
[ "BSD-2-Clause" ]
null
null
null
examples/Verify.cpp
joke325/Cerop
04351582ac626a10d4e2bb1d478d59cb70879571
[ "BSD-2-Clause" ]
null
null
null
/** * Copyright (c) 2020 Janky <box@janky.tech> * All right reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ // Inspired by https://github.com/rnpgp/rnp/blob/master/src/examples/verify.c #include <iostream> #include <exception> #include "Verify.hpp" // an example key provider void Verify::KeyCallBack(const RopSession& ses, void* ctx, const InString& identifier_type, const InString& identifier, const bool secret) { if(strcmp(identifier_type, "keyid") == 0) { std::string filename = std::string("key-") + (const char*)identifier + "-" + (secret? "sec" : "pub") + ".asc"; std::string err_desc; try { RopBind rop = ses->getBind(); err_desc = std::string("failed to open key file ") + filename; RopInput input = rop->create_input(filename); err_desc = std::string("failed to load key from file ") + filename; ses->load_keys(RopBindT::KEYSTORE_GPG, input, true, true); } catch(RopError&) { std::cout << err_desc << std::endl; throw; } } } void Verify::verify(RopBind& rop) { try { // initialize RopSession ses = rop->create_session(RopBindT::KEYSTORE_GPG, RopBindT::KEYSTORE_GPG); // we do not load any keys here since we'll use key provider ses->set_key_provider(this, nullptr); std::string err_desc; RopOutput output; try { // create file input and memory output objects for the signed message // and verified message err_desc = "Failed to open file 'signed.asc'. Did you run the sign example?"; RopInput input = rop->create_input("signed.asc"); err_desc = "Failed to create output object"; output = rop->create_output(0); err_desc = "Failed to create verification context"; RopOpVerify verify = ses->op_verify_create(input, output); err_desc = "Failed to execute verification operation"; verify->execute(); // now check signatures and get some info about them err_desc = "Failed to get signature count"; size_t sigcount = verify->signature_count(); for(size_t idx = 0; idx < sigcount; idx++) { err_desc = std::string("Failed to get signature ") + std::to_string(idx); RopVeriSignature sig = verify->get_signature_at(idx); err_desc = std::string("failed to get signature's ") + std::to_string(idx) + "key"; RopKey key = sig->get_key(); err_desc = std::string("failed to get key id ") + std::to_string(idx); std::cout << "Status for signature from key " << key->keyid() << " : " << sig->status() << std::endl; } } catch(RopError&) { std::cout << err_desc << std::endl; throw; } // get the verified message from the output structure RopData buf = output->memory_get_buf(false); std::cout << "Verified message: " << buf << std::endl; } catch(std::exception&) { throw; } } void Verify::execute() { try { RopBind rop = NewRopBind(); verify(rop); } catch(std::exception&) { throw; } } #ifndef CEROP_EX_TEST int main(int argc, char **argv) { Verify *ver = new Verify(); ver->execute(); delete ver; } #endif // CEROP_EX_TEST
37.412698
140
0.632372
[ "object" ]
3511632d1bda2ac50253ac00958530bdaa07b5be
8,230
cpp
C++
src/head.cpp
Hazematman/Ultrabrew2021
934d8609179effcf26ce2f5d53361031d8a1aa01
[ "WTFPL" ]
3
2021-12-14T00:14:53.000Z
2022-03-30T04:08:34.000Z
src/head.cpp
Hazematman/Ultrabrew2021
934d8609179effcf26ce2f5d53361031d8a1aa01
[ "WTFPL" ]
null
null
null
src/head.cpp
Hazematman/Ultrabrew2021
934d8609179effcf26ce2f5d53361031d8a1aa01
[ "WTFPL" ]
1
2021-12-09T10:21:11.000Z
2021-12-09T10:21:11.000Z
#include <ugfx.h> #include "mesh.hpp" const uint16_t head_head[] __attribute__ ((aligned (64))) = { 0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0x843,0x843,0xf889,0x843,0x843,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0x843,0x1043,0xf889,0x843,0x843,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0x843,0xf089,0xf889,0xf889,0xf889,0x843,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0x843,0x843,0x843,0x843,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889,0xf889, }; ugfx_vertex_t head_None_verts[] = { make_vertex_c(0.0, -1.0, -0.0, 0.5391, 0.9671, 0, 1, 255, 255), make_vertex_c(0.7236, -0.4472, 0.5257, 0.3044, 0.8316, 66, 66, 255, 255), make_vertex_c(-0.2764, -0.4472, 0.8506, 0.9304, 0.8316, 3, 4, 255, 255), make_vertex_c(0.7236, -0.4472, 0.5257, 0.3044, 0.8316, 66, 66, 255, 255), make_vertex_c(0.0, -1.0, -0.0, 0.5391, 0.9671, 0, 1, 255, 255), make_vertex_c(0.7236, -0.4472, -0.5257, 0.4609, 0.8316, 0, 1, 255, 255), make_vertex_c(0.0, -1.0, -0.0, 0.5391, 0.9671, 0, 1, 255, 255), make_vertex_c(-0.2764, -0.4472, 0.8506, 0.9304, 0.8316, 3, 4, 255, 255), make_vertex_c(-0.8944, -0.4472, -0.0, 0.7739, 0.8316, 3, 3, 255, 255), make_vertex_c(0.0, -1.0, -0.0, 0.5391, 0.9671, 0, 1, 255, 255), make_vertex_c(-0.8944, -0.4472, -0.0, 0.7739, 0.8316, 3, 3, 255, 255), make_vertex_c(-0.2764, -0.4472, -0.8506, 0.6174, 0.8316, 0, 1, 255, 255), make_vertex_c(0.0, -1.0, -0.0, 0.5391, 0.9671, 0, 1, 255, 255), make_vertex_c(-0.2764, -0.4472, -0.8506, 0.6174, 0.8316, 0, 1, 255, 255), make_vertex_c(0.7236, -0.4472, -0.5257, 0.4609, 0.8316, 0, 1, 255, 255), make_vertex_c(0.7236, -0.4472, 0.5257, 0.3044, 0.8316, 66, 66, 255, 255), make_vertex_c(0.7236, -0.4472, -0.5257, 0.4609, 0.8316, 0, 1, 255, 255), make_vertex_c(0.8944, 0.4472, -0.0, 0.3826, 0.696, 0, 1, 255, 255), make_vertex_c(-0.2764, -0.4472, 0.8506, 0.3516, 0.499, 3, 4, 255, 255), make_vertex_c(0.7236, -0.4472, 0.5257, 0.8496, 0.499, 66, 66, 255, 255), make_vertex_c(0.2764, 0.4472, 0.8506, 0.6006, 0.0677, 32, 32, 255, 255), make_vertex_c(-0.8944, -0.4472, -0.0, 0.7739, 0.8316, 3, 3, 255, 255), make_vertex_c(-0.2764, -0.4472, 0.8506, 0.9304, 0.8316, 3, 4, 255, 255), make_vertex_c(-0.7236, 0.4472, 0.5257, 0.8521, 0.696, 1, 3, 255, 255), make_vertex_c(-0.2764, -0.4472, -0.8506, 0.6174, 0.8316, 0, 1, 255, 255), make_vertex_c(-0.8944, -0.4472, -0.0, 0.7739, 0.8316, 3, 3, 255, 255), make_vertex_c(-0.7236, 0.4472, -0.5257, 0.6956, 0.696, 31, 31, 255, 255), make_vertex_c(0.7236, -0.4472, -0.5257, 0.4609, 0.8316, 0, 1, 255, 255), make_vertex_c(-0.2764, -0.4472, -0.8506, 0.6174, 0.8316, 0, 1, 255, 255), make_vertex_c(0.2764, 0.4472, -0.8506, 0.5391, 0.696, 0, 1, 255, 255), make_vertex_c(0.7236, -0.4472, 0.5257, 0.3044, 0.8316, 66, 66, 255, 255), make_vertex_c(0.8944, 0.4472, -0.0, 0.3826, 0.696, 0, 1, 255, 255), make_vertex_c(0.2764, 0.4472, 0.8506, 0.2261, 0.696, 32, 32, 255, 255), make_vertex_c(-0.2764, -0.4472, 0.8506, 0.3516, 0.499, 3, 4, 255, 255), make_vertex_c(0.2764, 0.4472, 0.8506, 0.6006, 0.0677, 32, 32, 255, 255), make_vertex_c(-0.7236, 0.4472, 0.5257, 0.1026, 0.0677, 1, 3, 255, 255), make_vertex_c(-0.8944, -0.4472, -0.0, 0.7739, 0.8316, 3, 3, 255, 255), make_vertex_c(-0.7236, 0.4472, 0.5257, 0.8521, 0.696, 1, 3, 255, 255), make_vertex_c(-0.7236, 0.4472, -0.5257, 0.6956, 0.696, 31, 31, 255, 255), make_vertex_c(-0.2764, -0.4472, -0.8506, 0.6174, 0.8316, 0, 1, 255, 255), make_vertex_c(-0.7236, 0.4472, -0.5257, 0.6956, 0.696, 31, 31, 255, 255), make_vertex_c(0.2764, 0.4472, -0.8506, 0.5391, 0.696, 0, 1, 255, 255), make_vertex_c(0.7236, -0.4472, -0.5257, 0.4609, 0.8316, 0, 1, 255, 255), make_vertex_c(0.2764, 0.4472, -0.8506, 0.5391, 0.696, 0, 1, 255, 255), make_vertex_c(0.8944, 0.4472, -0.0, 0.3826, 0.696, 0, 1, 255, 255), make_vertex_c(0.2764, 0.4472, 0.8506, 0.2261, 0.696, 32, 32, 255, 255), make_vertex_c(0.8944, 0.4472, -0.0, 0.3826, 0.696, 0, 1, 255, 255), make_vertex_c(0.0, 1.0, -0.0, 0.4609, 0.5605, 9, 9, 255, 255), make_vertex_c(-0.7236, 0.4472, 0.5257, 0.8521, 0.696, 1, 3, 255, 255), make_vertex_c(0.2764, 0.4472, 0.8506, 0.2261, 0.696, 32, 32, 255, 255), make_vertex_c(0.0, 1.0, -0.0, 0.4609, 0.5605, 9, 9, 255, 255), make_vertex_c(-0.7236, 0.4472, -0.5257, 0.6956, 0.696, 31, 31, 255, 255), make_vertex_c(-0.7236, 0.4472, 0.5257, 0.8521, 0.696, 1, 3, 255, 255), make_vertex_c(0.0, 1.0, -0.0, 0.4609, 0.5605, 9, 9, 255, 255), make_vertex_c(0.2764, 0.4472, -0.8506, 0.5391, 0.696, 0, 1, 255, 255), make_vertex_c(-0.7236, 0.4472, -0.5257, 0.6956, 0.696, 31, 31, 255, 255), make_vertex_c(0.0, 1.0, -0.0, 0.4609, 0.5605, 9, 9, 255, 255), make_vertex_c(0.8944, 0.4472, -0.0, 0.3826, 0.696, 0, 1, 255, 255), make_vertex_c(0.2764, 0.4472, -0.8506, 0.5391, 0.696, 0, 1, 255, 255), make_vertex_c(0.0, 1.0, -0.0, 0.4609, 0.5605, 9, 9, 255, 255), }; ugfx_command_t head_None_commands[] = { ugfx_set_address_slot(1, head_None_verts), ugfx_sync_pipe(), ugfx_set_combine_mode(UGFX_CC_SUB_0, UGFX_CC_SUB_0, UGFX_CC_MUL_0, UGFX_CC_T0_COLOR, UGFX_AC_0, UGFX_AC_0, UGFX_AC_0, UGFX_AC_1, UGFX_CC_SUB_0, UGFX_CC_SUB_0, UGFX_CC_MUL_0, UGFX_CC_T0_COLOR, UGFX_AC_0, UGFX_AC_0, UGFX_AC_0, UGFX_AC_1), ugfx_set_geometry_mode(UGFX_GEOMETRY_SHADE | UGFX_GEOMETRY_ZBUFFER | UGFX_GEOMETRY_TEXTURE | UGFX_GEOMETRY_SMOOTH), ugfx_set_texture_image(0, head_head, UGFX_FORMAT_RGBA, UGFX_PIXEL_SIZE_16B, 16 - 1), ugfx_set_tile(UGFX_FORMAT_RGBA, UGFX_PIXEL_SIZE_16B, (2 * 16) >> 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), ugfx_load_tile(0 << 2, 0 << 2, (16 - 1) << 2, (16 - 1) << 2, 0), ugfx_set_texture_settings(0x3fff, 0x3fff, 0, 0), ugfx_load_vertices(1, 0*sizeof(ugfx_vertex_t), 0, 32), ugfx_draw_triangle(0, 1, 2), ugfx_draw_triangle(3, 4, 5), ugfx_draw_triangle(6, 7, 8), ugfx_draw_triangle(9, 10, 11), ugfx_draw_triangle(12, 13, 14), ugfx_draw_triangle(15, 16, 17), ugfx_draw_triangle(18, 19, 20), ugfx_draw_triangle(21, 22, 23), ugfx_draw_triangle(24, 25, 26), ugfx_draw_triangle(27, 28, 29), ugfx_load_vertices(1, 30*sizeof(ugfx_vertex_t), 0, 32), ugfx_draw_triangle(0, 1, 2), ugfx_draw_triangle(3, 4, 5), ugfx_draw_triangle(6, 7, 8), ugfx_draw_triangle(9, 10, 11), ugfx_draw_triangle(12, 13, 14), ugfx_draw_triangle(15, 16, 17), ugfx_draw_triangle(18, 19, 20), ugfx_draw_triangle(21, 22, 23), ugfx_draw_triangle(24, 25, 26), ugfx_draw_triangle(27, 28, 29), ugfx_finalize(), }; uint32_t head_None_verts_length = sizeof(head_None_verts) / sizeof(*head_None_verts); uint32_t head_None_commands_length = sizeof(head_None_commands) / sizeof(*head_None_commands); AnimationGroup head_groups[] = { }; MeshDef head_meshes[] ={ {{0.0, 0.0, -0.0}, head_None_verts, head_None_commands, sizeof(head_None_commands) / sizeof(*head_None_commands)}, }; ModelDef head_def = { head_meshes, sizeof(head_meshes) / sizeof(*head_meshes), head_groups, sizeof(head_groups) / sizeof(*head_groups), -0.8944, 0.8944, -1.0, 1.0, -0.8506, 0.8506, };
62.348485
1,779
0.707776
[ "mesh" ]
3511c92cb34f25dd72da460a2cdf74256c76a918
476
hpp
C++
Sandbox/ParticleMan.hpp
delahee/enjmin
5d982da486ad0565fcda38939212e6745bdf3e3f
[ "MIT" ]
null
null
null
Sandbox/ParticleMan.hpp
delahee/enjmin
5d982da486ad0565fcda38939212e6745bdf3e3f
[ "MIT" ]
null
null
null
Sandbox/ParticleMan.hpp
delahee/enjmin
5d982da486ad0565fcda38939212e6745bdf3e3f
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "Particle.hpp" class ParticleMan { public: std::vector<Particle> parts; void add(Particle & p) { parts.push_back(p); } void update(double dt) { for (auto iter = parts.begin(); iter != parts.end(); ) { Particle & p = *iter; p.update((float)dt); if (p.destroyed) iter = parts.erase(iter); else iter++; } } void draw(sf::RenderWindow& win) { for (Particle & p : parts) { win.draw(p.el); } } };
15.866667
58
0.596639
[ "vector" ]
3523a44a07c385cfe4f705311a24393d31dcae03
5,111
cpp
C++
implementations/opencv_io/janice_io_opencv_sparse.cpp
carlosdcastillo/janice
221a94dd25ab4304d3c959a364ec89548b807509
[ "MIT" ]
null
null
null
implementations/opencv_io/janice_io_opencv_sparse.cpp
carlosdcastillo/janice
221a94dd25ab4304d3c959a364ec89548b807509
[ "MIT" ]
null
null
null
implementations/opencv_io/janice_io_opencv_sparse.cpp
carlosdcastillo/janice
221a94dd25ab4304d3c959a364ec89548b807509
[ "MIT" ]
null
null
null
#include <janice_io.h> #include <opencv2/highgui.hpp> #include <string> #include <vector> #ifdef __cplusplus extern "C" { #endif JANICE_EXPORT JaniceError janice_io_opencv_create_sparse_media_iterator(const char** filenames, size_t num_files, JaniceMediaIterator* it); #ifdef __cplusplus } // extern "C" #endif namespace { static inline JaniceError cv_mat_to_janice_image(cv::Mat& m, JaniceImage* _image) { // Allocate a new image JaniceImage image = new JaniceImageType(); // Set up the dimensions image->channels = m.channels(); image->rows = m.rows; image->cols = m.cols; image->data = (uint8_t*) malloc(m.channels() * m.rows * m.cols); memcpy(image->data, m.data, m.channels() * m.rows * m.cols); image->owner = true; *_image = image; return JANICE_SUCCESS; } // ---------------------------------------------------------------------------- // JaniceMediaIterator struct JaniceMediaIteratorStateType { std::vector<std::string> filenames; size_t pos; }; JaniceError is_video(JaniceMediaIterator it, bool* video) { *video = true; // Treat this as a video return JANICE_SUCCESS; } JaniceError get_frame_rate(JaniceMediaIterator, float*) { return JANICE_INVALID_MEDIA; } JaniceError get_physical_frame_rate(JaniceMediaIterator it, float* frame_rate) { return get_frame_rate(it, frame_rate); } JaniceError next(JaniceMediaIterator it, JaniceImage* image) { JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal; if (state->pos == state->filenames.size()) return JANICE_MEDIA_AT_END; try { cv::Mat cv_img = cv::imread(state->filenames[state->pos], cv::IMREAD_ANYCOLOR | cv::IMREAD_IGNORE_ORIENTATION); cv_mat_to_janice_image(cv_img, image); } catch (...) { return JANICE_UNKNOWN_ERROR; } ++state->pos; return JANICE_SUCCESS; } JaniceError seek(JaniceMediaIterator it, uint32_t frame) { JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal; if (frame >= state->filenames.size()) return JANICE_BAD_ARGUMENT; state->pos = frame; return JANICE_SUCCESS; } JaniceError get(JaniceMediaIterator it, JaniceImage* image, uint32_t frame) { JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal; if (frame >= state->filenames.size()) return JANICE_BAD_ARGUMENT; try { cv::Mat cv_img = cv::imread(state->filenames[frame], cv::IMREAD_ANYCOLOR | cv::IMREAD_IGNORE_ORIENTATION); cv_mat_to_janice_image(cv_img, image); } catch (...) { return JANICE_UNKNOWN_ERROR; } return JANICE_SUCCESS; } JaniceError tell(JaniceMediaIterator it, uint32_t* frame) { JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal; if (state->pos == state->filenames.size()) return JANICE_MEDIA_AT_END; *frame = state->pos; return JANICE_SUCCESS; } // Map a logical frame number (as from tell) to a physical frame number, allowing // for downsampling, clipping, etc. on videos. Here, we just return the physical frame. JaniceError physical_frame(JaniceMediaIterator it, uint32_t logical, uint32_t *physical) { if (physical == nullptr) { return JANICE_BAD_ARGUMENT; } *physical = logical; return JANICE_SUCCESS; } JaniceError free_image(JaniceImage* image) { if (image && (*image)->owner) free((*image)->data); delete (*image); return JANICE_SUCCESS; } JaniceError free_iterator(JaniceMediaIterator* it) { if (it && (*it)->_internal) { delete (JaniceMediaIteratorStateType*) (*it)->_internal; delete (*it); *it = nullptr; } return JANICE_SUCCESS; } JaniceError reset(JaniceMediaIterator it) { JaniceMediaIteratorStateType* state = (JaniceMediaIteratorStateType*) it->_internal; state->pos = 0; return JANICE_SUCCESS; } } // anonymous namespace // ---------------------------------------------------------------------------- // OpenCV I/O only, create a sparse opencv_io media iterator JaniceError janice_io_opencv_create_sparse_media_iterator(const char** filenames, size_t num_files, JaniceMediaIterator *_it) { JaniceMediaIterator it = new JaniceMediaIteratorType(); it->is_video = &is_video; it->get_frame_rate = &get_frame_rate; it->get_physical_frame_rate = &get_physical_frame_rate; it->next = &next; it->seek = &seek; it->get = &get; it->tell = &tell; it->physical_frame = &physical_frame; it->free_image = &free_image; it->free = &free_iterator; it->reset = &reset; JaniceMediaIteratorStateType* state = new JaniceMediaIteratorStateType(); for (size_t i = 0; i < num_files; ++i) { state->filenames.push_back(std::string(filenames[i])); } state->pos = 0; it->_internal = (void*) (state); *_it = it; return JANICE_SUCCESS; }
25.17734
125
0.652123
[ "vector" ]
3537ef45e7e627ee6820ffda09f9fc337deed431
5,159
cpp
C++
Classes/HelloWorldScene.cpp
XINCGer/CrazyWorker
6c86aa9e336539f9004dbe761acae3ae25da0f6a
[ "Apache-2.0" ]
1
2018-11-19T00:34:32.000Z
2018-11-19T00:34:32.000Z
Classes/HelloWorldScene.cpp
XINCGer/CrazyWorker
6c86aa9e336539f9004dbe761acae3ae25da0f6a
[ "Apache-2.0" ]
null
null
null
Classes/HelloWorldScene.cpp
XINCGer/CrazyWorker
6c86aa9e336539f9004dbe761acae3ae25da0f6a
[ "Apache-2.0" ]
4
2017-03-22T10:00:32.000Z
2018-11-06T15:05:51.000Z
#include "HelloWorldScene.h" #include "TreeModel.h" #include "GameOver.h" #include "SimpleAudioEngine.h" USING_NS_CC; Scene* HelloWorld::createScene() { auto scene = Scene::create(); auto layer = HelloWorld::create(); scene->addChild(layer); return scene; } bool HelloWorld::init() { if ( !Layer::init() ) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); _score = 0; bg1 = Sprite::create("bg1.jpg"); this->addChild(bg1); bg1->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); bg2 = Sprite::create("bg2.jpg"); this->addChild(bg2); bg2->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); bg2->setVisible(false); auto model = TreeModel::getInstance(); model->setPosition(visibleSize.width/2,100); this->addChild(model); timber = Timber::createTimber(); this->addChild(timber); timber->setPosition(visibleSize.width/2-timber->getContentSize().width/2-20,150); list = EventListenerTouchOneByOne::create(); list->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegans,this); this->_eventDispatcher->addEventListenerWithSceneGraphPriority(list,this); list->setEnabled(false); score = GameScore::createScore(); this->addChild(score); score->setPosition(visibleSize/2); score->callBackFun = CC_CALLBACK_0(HelloWorld::menuCloseCallback,this); auto leftIcon = Sprite::create("left.png"); auto rightIcon = Sprite::create("right.png"); leftIcon->setScale(0.5); rightIcon->setScale(0.5); leftIcon->setPosition(leftIcon->getContentSize().width/2,50); rightIcon->setPosition(visibleSize.width-rightIcon->getContentSize().width/2,50); this->addChild(leftIcon); this->addChild(rightIcon); auto gameOver = GameOver::getInstance(); this->addChild(gameOver); gameOver->callBackFun = CC_CALLBACK_0(HelloWorld::onRest,this); gameOver->setAnchorPoint(Vec2(0,0.5)); gameOver->setVisible(false); gameOver->setPosition(visibleSize.width/2,visibleSize.height+gameOver->getContentSize().height/2); auto play = MenuItemImage::create( "play.png", "play.png", CC_CALLBACK_0(HelloWorld::playGame, this)); play->setScale(0.5); menu = Menu::create(play, NULL); this->addChild(menu); menu->setPosition(visibleSize.width/2,play->getContentSize().height*2); logo = Sprite::create("logo.png"); logo->setPosition(visibleSize.width/2,visibleSize.height/2+logo->getContentSize().height); this->addChild(logo); CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("music/bgmusic.mp3", true); CocosDenshion::SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.5); ParticleSystem* pl = ParticleSnow::create(); pl->setTexture(Director::getInstance()->getTextureCache()->addImage("particle.png")); pl->setPosition(visibleSize.width/2,visibleSize.height); this->addChild(pl,10); return true; } bool HelloWorld::onTouchBegans(Touch *touch, Event *event) { auto pos = touch->getLocation(); Size visibleSize = Director::getInstance()->getVisibleSize(); auto model = TreeModel::getInstance(); auto isRight = pos.x > visibleSize.width/2; timber->playAction(isRight ? RIGHT : LEFT); if(isRight) { timber->setPosition(visibleSize.width/2+timber->getContentSize().width/2+20,150); } else { timber->setPosition(visibleSize.width/2-timber->getContentSize().width/2-20,150); } if(getIsOver()) { timber->setTimberDie(); gameOver(); return false; } auto dic = visibleSize.width*2; auto time = 0.5; auto tree = model->deleteTreeHeadNode(); if( isRight ) { tree->runAction(Spawn::create(RotateBy::create(time,-180),MoveBy::create(time,Vec2(-dic,0)),nullptr)); } else { tree->runAction(Spawn::create(RotateBy::create(time,180),MoveBy::create(time,Vec2(dic,0)),nullptr)); } _score++; score->setScore(_score); if(getIsOver()) { timber->setTimberDie(); gameOver(); } return true; } bool HelloWorld::getIsOver() { auto model = TreeModel::getInstance(); if(model->getFirstBranch() == timber->getTimberDir()) return true; return false; } void HelloWorld::menuCloseCallback() { if(!GameOver::getInstance()->isVisible()) { gameOver(); } } void HelloWorld::onRest() { _score = 0; TreeModel::getInstance()->onReset(); score->onReset(); timber->onReset(); list->setEnabled(true); auto isBgShow = (CCRANDOM_0_1()*10 < 5); bg1->setVisible(isBgShow); bg2->setVisible(!isBgShow); Size visibleSize = Director::getInstance()->getVisibleSize(); timber->setPosition(visibleSize.width/2-timber->getContentSize().width/2-20,150); } void HelloWorld::gameOver() { list->setEnabled(false); Size visibleSize = Director::getInstance()->getVisibleSize(); auto gameOver = GameOver::getInstance(); gameOver->setScore(_score); gameOver->setPositionY(visibleSize.height+gameOver->getContentSize().height/2); gameOver->setVisible(true); gameOver->runAction(MoveBy::create(0.5,Vec2(0,-gameOver->getContentSize().height))); } void HelloWorld::playGame() { menu->removeFromParent(); logo->removeFromParent(); list->setEnabled(true); score->onReset(); }
26.592784
104
0.719713
[ "model" ]
3547129c7b7ef3a7275aaf231921eb32eff966e0
2,959
cpp
C++
PostView2/TimePanel.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
9
2020-03-22T08:27:03.000Z
2021-09-24T10:02:37.000Z
PostView2/TimePanel.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
1
2021-03-02T06:45:59.000Z
2021-03-02T06:45:59.000Z
PostView2/TimePanel.cpp
febiosoftware/PostView
45c60aec1ae8832d0e6f6410e774aeaded2037c0
[ "MIT" ]
2
2020-06-27T13:59:49.000Z
2021-09-08T16:39:39.000Z
/*This file is part of the PostView source code and is licensed under the MIT license listed below. See Copyright-PostView.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "stdafx.h" #include "TimePanel.h" #include "ui_timepanel.h" #include "MainWindow.h" #include "Document.h" using namespace Post; CTimePanel::CTimePanel(CMainWindow* wnd, QWidget* parent) : QWidget(parent), m_wnd(wnd), ui(new Ui::CTimePanel) { ui->setupUi(this); } void CTimePanel::Update(bool reset) { CDocument* doc = m_wnd->GetActiveDocument(); if (doc && doc->IsValid()) { FEPostModel* fem = doc->GetFEModel(); if (fem) { if (reset) { ui->timer->clearData(); FEPostModel& fem = *doc->GetFEModel(); vector<double> data(fem.GetStates()); int nstates = fem.GetStates(); for (int i = 0; i < nstates; ++i) data[i] = fem.GetState(i)->m_time; ui->timer->setTimePoints(data); TIMESETTINGS& time = doc->GetTimeSettings(); time.m_start = 0; time.m_end = nstates - 1; ui->timer->setRange(time.m_start, time.m_end); } int ntime = doc->currentTime(); ui->timer->setSelection(ntime); double ftime = doc->GetTimeValue(); ui->timer->setCurrentTime(ftime); } else ui->timer->clearData(); } else ui->timer->clearData(); } void CTimePanel::SetRange(int nmin, int nmax) { ui->timer->setRange(nmin, nmax); } void CTimePanel::on_timer_pointClicked(int i) { m_wnd->SetCurrentTime(i); } void CTimePanel::on_timer_rangeChanged(int nmin, int nmax) { CDocument* doc = m_wnd->GetActiveDocument(); if (doc->IsValid()) { TIMESETTINGS& time = doc->GetTimeSettings(); time.m_start = nmin; time.m_end = nmax; int ntime = doc->currentTime(); if ((ntime < nmin) || (ntime > nmax)) { if (ntime < nmin) ntime = nmin; if (ntime > nmax) ntime = nmax; } m_wnd->SetCurrentTime(ntime); } }
28.728155
111
0.715782
[ "vector" ]
3549d6c2debb2cd59db2a8f139dc71fd73f3e5d5
4,188
tpp
C++
siclib/linalg/TensorView.tpp
ShameekConyers/sicnumerical
dc5035e5d922cb8e4341c5fbd88adba4f5d09bea
[ "MIT" ]
null
null
null
siclib/linalg/TensorView.tpp
ShameekConyers/sicnumerical
dc5035e5d922cb8e4341c5fbd88adba4f5d09bea
[ "MIT" ]
null
null
null
siclib/linalg/TensorView.tpp
ShameekConyers/sicnumerical
dc5035e5d922cb8e4341c5fbd88adba4f5d09bea
[ "MIT" ]
null
null
null
#pragma once #include "TensorView.hpp" namespace sic { class TensorView; template<typename Fn> TensorView TensorView::unary_op( const Fn& inp_unitary_op) const { int c_idx = 0; int counter = 1; std::vector<size_t> this_shape = m_shape; std::vector<size_t> cur_this(this_shape.size()); TensorView result_tensor = deep_copy(); bool flag = true; ssize_t lst_sig = this_shape.size() - 1; while (flag) { //! Insert unitary op here double result = inp_unitary_op(get_val(cur_this)); result_tensor.set_val(cur_this, result); cur_this[lst_sig]++; if (cur_this[lst_sig] == this_shape[lst_sig]) { c_idx = lst_sig; while (flag) { if (c_idx == -1) { flag = false; break; } if (cur_this[c_idx] == this_shape[c_idx]) { cur_this[c_idx] = 0; c_idx--; } else { cur_this[c_idx] += 1; if (cur_this[c_idx] < this_shape[c_idx]) { break; } else { continue; } } } } } return result_tensor; } template<typename Fn> TensorView TensorView::fold_op( const Fn& binary_op, double inital_value, size_t target_dim, bool left_op) { int c_idx = 0; int counter = 0; std::vector<size_t> this_shape = m_shape; std::vector<size_t> res_shape = m_shape; res_shape[target_dim] = 1; size_t res_size = res_shape.size(); TensorView res_tensor = generate_tensor(res_shape, inital_value); std::vector<size_t> cur_this(res_shape.size()); std::vector<size_t> cur_res(res_shape.size()); bool flag = true; ssize_t lst_sig = res_size - 1; while (flag) { //! Insert FOLD OP here double op_result = binary_op( get_val(cur_this), res_tensor.get_val(cur_res)); res_tensor.set_val(cur_res, op_result); cur_this[lst_sig]++; counter++; cur_res[lst_sig] = std::min(res_shape[lst_sig] - 1, cur_this[lst_sig]); if (cur_this[lst_sig] == this_shape[lst_sig]) { c_idx = lst_sig; while (flag) { if (c_idx == -1) { flag = false; break; } if (cur_this[c_idx] == this_shape[c_idx]) { cur_res[c_idx] = 0; cur_this[c_idx] = 0; c_idx--; } else { cur_this[c_idx] += 1; cur_res[c_idx] = std::min(res_shape[c_idx] - 1, cur_this[c_idx]); if (cur_this[c_idx] < this_shape[c_idx]) { break; } else { continue; } } } } } return res_tensor; } template<typename Fn> TensorView TensorView::binary_element_wise_op( const TensorView& other, const Fn& binary_op) const { int c_idx = 0; int counter = 0; size_t cumulative_prod = 1; std::vector<double> res_data; auto [res_shape, brd_this, brd_other] = do_broadcast(other); // std::vector<size_t> res_shape = do_broadcast(other); std::vector<size_t> this_shape = m_shape; std::vector<size_t> other_shape = other.m_shape; size_t res_size = std::max(this_shape.size(), other_shape.size()); for (auto item : res_shape) { cumulative_prod *= item; } res_data.resize(cumulative_prod); TensorView res_tensor{ res_data, res_shape }; if (res_data.size() == 0) { return res_tensor; } std::vector<size_t> cur_this(res_shape.size()); std::vector<size_t> cur_other(res_shape.size()); std::vector<size_t> cur_res(res_shape.size()); bool flag = true; ssize_t lst_sig = res_size - 1; while (flag) { double op_result = binary_op( get_val(cur_this), other.get_val(cur_other)); res_tensor.set_val(cur_res, op_result); cur_res[lst_sig]++; counter++; cur_other[lst_sig] = std::min(other_shape[lst_sig] - 1, cur_res[lst_sig]); cur_this[lst_sig] = std::min(this_shape[lst_sig] - 1, cur_res[lst_sig]); if (cur_res[lst_sig] == res_shape[lst_sig]) { c_idx = lst_sig; while (flag) { if (c_idx == -1) { flag = false; break; } if (cur_res[c_idx] == res_shape[c_idx]) { cur_res[c_idx] = 0; cur_other[c_idx] = 0; cur_this[c_idx] = 0; c_idx--; } else { cur_res[c_idx] += 1; cur_other[c_idx] = std::min(cur_res[c_idx], other_shape[c_idx] - 1); cur_this[c_idx] = std::min(cur_res[c_idx], this_shape[c_idx] - 1); if (cur_res[c_idx] < res_shape[c_idx]) { break; } else { continue; } } } } } return res_tensor; } } //
20.94
76
0.641117
[ "vector" ]
8319e220a78a59ca42d3f31424738d542837ffb8
1,232
hpp
C++
Plugins/CameraControl/CameraControl.hpp
GlynnJKW/Stratum
ddc55796f3207fe3df23c455c6304cb72aebcb02
[ "MIT" ]
2
2019-10-01T22:55:47.000Z
2019-10-04T20:25:29.000Z
Plugins/CameraControl/CameraControl.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
null
null
null
Plugins/CameraControl/CameraControl.hpp
Shmaug/vkCAVE
e502aedaf172047557f0454acb170a46b9d350f8
[ "MIT" ]
null
null
null
#pragma once #include <Core/EnginePlugin.hpp> #include <Scene/Scene.hpp> #include <Input/MouseKeyboardInput.hpp> #include <Util/Profiler.hpp> class CameraControl : public EnginePlugin { private: Scene* mScene; float mCameraDistance; float3 mCameraEuler; MouseKeyboardInput* mInput; Object* mCameraPivot; std::vector<Camera*> mCameras; bool mShowPerformance; bool mSnapshotPerformance; ProfilerSample mProfilerFrames[PROFILER_FRAME_COUNT - 1]; uint32_t mSelectedFrame; public: PLUGIN_EXPORT CameraControl(); PLUGIN_EXPORT ~CameraControl(); PLUGIN_EXPORT bool Init(Scene* scene) override; PLUGIN_EXPORT void Update(CommandBuffer* commandBuffer) override; PLUGIN_EXPORT void DrawGizmos(CommandBuffer* commandBuffer, Camera* camera) override; PLUGIN_EXPORT void PreRenderScene(CommandBuffer* commandBuffer, Camera* camera, PassType pass) override; inline void CameraDistance(float d) { mCameraDistance = d; } inline float CameraDistance() const { return mCameraDistance; } inline float3 CameraEuler() const { return mCameraEuler; } inline void CameraEuler(const float3& e) { mCameraEuler = e; } inline Object* CameraPivot() const { return mCameraPivot; } inline int Priority() override { return 1000; } };
30.8
105
0.787338
[ "object", "vector" ]
831d9bd9b74c57fd6ad8a7c06f4576b0e4eaa47f
2,757
cpp
C++
collection/cp/bcw_codebook-master/Contest/XVIOpenCupSaratov/pA.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/bcw_codebook-master/Contest/XVIOpenCupSaratov/pA.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/bcw_codebook-master/Contest/XVIOpenCupSaratov/pA.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> #include<unistd.h> using namespace std; #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define F first #define S second #define PB push_back #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define IOS ios_base::sync_with_stdio(0); cin.tie(0) #ifdef ONLINE_JUDGE #define FILEIO(name) \ freopen(name".in", "r", stdin); \ freopen(name".out", "w", stdout); #else #define FILEIO(name) #endif template<typename A, typename B> ostream& operator <<(ostream &s, const pair<A,B> &p) { return s<<"("<<p.first<<","<<p.second<<")"; } template<typename T> ostream& operator <<(ostream &s, const vector<T> &c) { s<<"[ "; for (auto it : c) s << it << " "; s<<"]"; return s; } #define REP(i,n) for (int i=0;i<(n);i++) #define REP1(i,a,b) for (int i=(a);i<=(b);i++) // Let's Fight! const int MAXN = 404; const int MAXC = 33; const int MAXL = 4096; int N; int arr[MAXN]; int cnt[MAXC]; vector<int> cvec[MAXC]; bitset<MAXL> dp[MAXC][MAXL], tmp[MAXL]; int cpos[MAXC]; vector<int> vans[3]; bool used[MAXN]; void calc() { int tot = 0; for(int i=0; i<N; i++) tot += arr[i]; dp[0][0][0] = true; for(int i=1; i<MAXC; i++) { for(int j=0; j<MAXL; j++) dp[i][j] = dp[i-1][j]; for(int j=0; j<cnt[i-1]; j++) { for(int k=0; k<MAXL; k++) tmp[k] = dp[i][k]; for(int k=0; k<MAXL; k++) { tmp[k] |= dp[i][k] << (i-1); if(k+i-1 < MAXL) tmp[k+i-1] |= dp[i][k]; } for(int k=0; k<MAXL; k++) dp[i][k] = tmp[k]; } } int best = MAXL, bi = -1, bj = -1; for(int i=0; i<MAXL; i++) { for(int j=0; j<MAXL; j++) { if(!dp[MAXC-1][i][j]) continue; int k = tot - i - j; int dif = max(max(i, j), k) - min(min(i, j), k); if(dif < best) { best = dif; bi = i; bj = j; } } } for(int i=MAXC-2; i>=0; i--) { bool ok = false; int ni, nj; for(int j=0; j<=cnt[i]; j++) { if(ok) break; ni = bi - j * i; if(ni < 0) continue; for(int k=0; j+k<=cnt[i]; k++) { nj = bj - k * i; if(nj < 0) continue; if(dp[i][ni][nj]) { for(int l=0; l<j; l++) { int v = cvec[i][cpos[i]++]; used[v] = true; vans[0].PB(v); } for(int l=0; l<k; l++) { int v = cvec[i][cpos[i]++]; used[v] = true; vans[1].PB(v); } bi = ni; bj = nj; ok = true; break; } } } } for(int i=0; i<N; i++) if(!used[i]) vans[2].PB(i); cout<<best<<endl; for(int i=0; i<3; i++) { int S = vans[i].size(); cout<<S; for(int j=0; j<S; j++) cout<<" "<<vans[i][j]+1; cout<<endl; } } int main() { IOS; cin>>N; for(int i=0; i<N; i++) { cin>>arr[i]; cnt[arr[i]]++; cvec[arr[i]].PB(i); } calc(); return 0; }
17.787097
54
0.490751
[ "vector" ]
832146082ff4a740ee9be34a4694ffc83ae35f3a
2,199
cc
C++
worker/deps/libwebrtc/libwebrtc/modules/congestion_controller/rtp/control_handler.cc
kcking/mediasoup
f385349d0f06fe14a4e38d50f0212b48d588fa32
[ "ISC" ]
4,465
2017-04-05T20:00:24.000Z
2022-03-31T13:27:43.000Z
worker/deps/libwebrtc/libwebrtc/modules/congestion_controller/rtp/control_handler.cc
kcking/mediasoup
f385349d0f06fe14a4e38d50f0212b48d588fa32
[ "ISC" ]
617
2017-04-05T21:24:27.000Z
2022-03-31T06:17:25.000Z
worker/deps/libwebrtc/libwebrtc/modules/congestion_controller/rtp/control_handler.cc
kcking/mediasoup
f385349d0f06fe14a4e38d50f0212b48d588fa32
[ "ISC" ]
900
2017-04-11T09:25:27.000Z
2022-03-30T21:37:00.000Z
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #define MS_CLASS "webrtc::CongestionControlHandler" // #define MS_LOG_DEV_LEVEL 3 #include "modules/congestion_controller/rtp/control_handler.h" #include "api/units/data_rate.h" #include "rtc_base/numerics/safe_conversions.h" #include "rtc_base/numerics/safe_minmax.h" #include "system_wrappers/source/field_trial.h" #include "Logger.hpp" #include <algorithm> #include <vector> namespace webrtc { void CongestionControlHandler::SetTargetRate( TargetTransferRate new_target_rate) { last_incoming_ = new_target_rate; } void CongestionControlHandler::SetNetworkAvailability(bool network_available) { network_available_ = network_available; } absl::optional<TargetTransferRate> CongestionControlHandler::GetUpdate() { if (!last_incoming_.has_value()) return absl::nullopt; TargetTransferRate new_outgoing = *last_incoming_; DataRate log_target_rate = new_outgoing.target_rate; bool pause_encoding = false; if (!network_available_) pause_encoding = true; if (pause_encoding) new_outgoing.target_rate = DataRate::Zero(); if (!last_reported_ || last_reported_->target_rate != new_outgoing.target_rate || (!new_outgoing.target_rate.IsZero() && (last_reported_->network_estimate.loss_rate_ratio != new_outgoing.network_estimate.loss_rate_ratio || last_reported_->network_estimate.round_trip_time != new_outgoing.network_estimate.round_trip_time))) { if (encoder_paused_in_last_report_ != pause_encoding) MS_DEBUG_TAG(bwe, "Bitrate estimate state changed, BWE: %s", ToString(log_target_rate).c_str()); encoder_paused_in_last_report_ = pause_encoding; last_reported_ = new_outgoing; return new_outgoing; } return absl::nullopt; } } // namespace webrtc
33.830769
79
0.749886
[ "vector" ]