hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8be613f577fd369a92cf747a51ff5fc0ac3c9ded
678
hpp
C++
include/sprout/preprocessor/u16str.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/preprocessor/u16str.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/preprocessor/u16str.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_PREPROCESSOR_U16STR_HPP #define SPROUT_PREPROCESSOR_U16STR_HPP #include <sprout/config.hpp> // // SPROUT_PP_U16STR // #define SPROUT_PP_U16STR(str) SPROUT_PP_U16STR_I(str) #define SPROUT_PP_U16STR_I(str) u ## str #endif // #ifndef SPROUT_PREPROCESSOR_U16STR_HPP
33.9
79
0.60767
thinkoid
8bf69f8423f32cfb609cfdb6b7f59e56fe348989
324
cc
C++
leetcode/1164-missing-number-in-arithmetic-progression.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
leetcode/1164-missing-number-in-arithmetic-progression.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
leetcode/1164-missing-number-in-arithmetic-progression.cc
Magic07/online-judge-solutions
02a289dd7eb52d7eafabc97bd1a043213b65f70a
[ "MIT" ]
null
null
null
class Solution { public: int missingNumber(vector<int>& arr) { int diff=abs(arr[arr.size()-1]-arr[0])/arr.size(); if(arr[0]>arr[1]){ diff=0-diff; } for(int i=0;i<arr.size();i++){ if(arr[i]!=arr[0]+diff*i){ return arr[0]+diff*i; } } return 0; } };
21.6
56
0.469136
Magic07
8bfc7e95107e1db49c1a3c010f370e23e3a56f3f
3,138
hpp
C++
Inc/Inner/ImplHudNode.hpp
MJYCo-Ltd/Map
48ccc120a3c2cd3080fb046da72c7588b1faebc0
[ "MIT" ]
7
2021-11-25T02:12:09.000Z
2022-03-20T12:48:18.000Z
Inc/Inner/ImplHudNode.hpp
MJYCo-Ltd/Map
48ccc120a3c2cd3080fb046da72c7588b1faebc0
[ "MIT" ]
1
2022-03-25T20:47:21.000Z
2022-03-29T02:02:44.000Z
Inc/Inner/ImplHudNode.hpp
MJYCo-Ltd/Map
48ccc120a3c2cd3080fb046da72c7588b1faebc0
[ "MIT" ]
2
2021-12-07T06:22:47.000Z
2021-12-30T05:54:04.000Z
#ifndef IMPL_HUD_NODE_H #define IMPL_HUD_NODE_H #include <osgEarth/Controls> #include <Inner/ImplSceneNode.hpp> /** * 实现IHudNode所有的接口 */ template <typename T> class ImplHudNode:public ImplSceneNode<T> { public: CONSTRUCTOR(ImplHudNode,ImplSceneNode<T>) protected: void SetControlNode(osgEarth::Controls::Control* pControl) { m_pControl = pControl; m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_BOTTOM); m_pProgramNode=pControl; } /// 位置更改 void HudPosChanged()SET_TRUE_NODE_UPDATE(m_bPosChanged) /// 状态更改 void HudTypeChanged()SET_TRUE_NODE_UPDATE(m_bTypeChanged) void FrameCall() { if(m_bPosChanged) { if(HUD_FIXED == T::m_emHudPosType) { m_pControl->setPosition(T::m_stHudPos.nX,T::m_stHudPos.nY); } m_bPosChanged = false; } if(m_bTypeChanged) { switch (T::m_emHudPosType) { case HUD_FIXED: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_NONE,osgEarth::Controls::Control::ALIGN_NONE); m_pControl->setPosition(T::m_stHudPos.nX,T::m_stHudPos.nY); break; case HUD_UP_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_CENTER,osgEarth::Controls::Control::ALIGN_TOP); break; case HUD_DOWN_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_CENTER,osgEarth::Controls::Control::ALIGN_BOTTOM); break; case HUD_UP_RIGHT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_RIGHT,osgEarth::Controls::Control::ALIGN_TOP); break; case HUD_DOWN_RIGHT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_RIGHT,osgEarth::Controls::Control::ALIGN_BOTTOM); break; case HUD_UP_LEFT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_TOP); break; case HUD_DOWN_LEFT: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_BOTTOM); break; case HUD_RIGHT_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_RIGHT,osgEarth::Controls::Control::ALIGN_CENTER); break; case HUD_LEFT_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_LEFT,osgEarth::Controls::Control::ALIGN_CENTER); break; case HUD_CENTER_CENTER: m_pControl->setAlign(osgEarth::Controls::Control::ALIGN_CENTER,osgEarth::Controls::Control::ALIGN_CENTER); break; } m_bTypeChanged = false; } ImplSceneNode<T>::FrameCall(); } protected: osg::observer_ptr<osgEarth::Controls::Control> m_pControl; bool m_bPosChanged{false}; bool m_bTypeChanged{false}; }; #endif // IMPL_HUD_NODE_H
35.659091
122
0.620459
MJYCo-Ltd
8bff2df37bf13bddbad8bdcf563fab3550a4754a
1,948
cpp
C++
libraries/Crypto/SHA384.cpp
rweather/arduinolibs
662329f1fd1ba57d1312253dfe81ff0e0e2ec706
[ "MIT" ]
356
2015-01-11T15:34:14.000Z
2022-03-30T13:57:24.000Z
libraries/Crypto/SHA384.cpp
rweather/arduinolibs
662329f1fd1ba57d1312253dfe81ff0e0e2ec706
[ "MIT" ]
57
2015-09-25T09:34:37.000Z
2022-01-30T19:51:50.000Z
libraries/Crypto/SHA384.cpp
rweather/arduinolibs
662329f1fd1ba57d1312253dfe81ff0e0e2ec706
[ "MIT" ]
174
2015-01-11T15:42:25.000Z
2022-03-26T21:46:08.000Z
/* * Copyright (C) 2015 Southern Storm Software, Pty Ltd. * * 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 "SHA384.h" #include "Crypto.h" #include "utility/ProgMemUtil.h" /** * \class SHA384 SHA384.h <SHA384.h> * \brief SHA-384 hash algorithm. * * Reference: http://en.wikipedia.org/wiki/SHA-2 * * \sa SHA256, SHA512, SHA3_256, BLAKE2s */ /** * \brief Constructs a SHA-384 hash object. */ SHA384::SHA384() { reset(); } size_t SHA384::hashSize() const { return 48; } void SHA384::reset() { static uint64_t const hashStart[8] PROGMEM = { 0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL, 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL }; memcpy_P(state.h, hashStart, sizeof(hashStart)); state.chunkSize = 0; state.lengthLow = 0; state.lengthHigh = 0; }
31.419355
78
0.728439
rweather
bddb33ff331e58560b240663f7ed3c75f8e633f3
955
cpp
C++
Rubbish/ht6/ht6/6588.cpp
albarkan/school.tests
07861b884f1bc6ccf852ac60074afaeeccf40ef2
[ "Apache-2.0" ]
null
null
null
Rubbish/ht6/ht6/6588.cpp
albarkan/school.tests
07861b884f1bc6ccf852ac60074afaeeccf40ef2
[ "Apache-2.0" ]
null
null
null
Rubbish/ht6/ht6/6588.cpp
albarkan/school.tests
07861b884f1bc6ccf852ac60074afaeeccf40ef2
[ "Apache-2.0" ]
null
null
null
/* Дан целочисленный массив из 30 элементов. Элементы массива могут принимать целые значения от 0 до 10000 включительно. Опишите на естественном языке или на // одном из языков программирования алгоритм, позволяющий найти и вывести произведение двузначных элементов массива, с суммой цифр не кратной 6. Гарантируется, что в исходном массиве есть хотя бы один элемент, значение которого является двузначным числом, и при этом сумма его цифр не делится на 6. Исходные данные объявлены так, как показано ниже на примерах для некоторых языков программирования и естественного языка. */ #include <iostream> #define N 6 using namespace std; int task6588() { int i, p; p = 1; i = 0; int A[N]; for (i = 0; i < N; i++) cin >> A[i]; for ( i= 0; i < N; i++) { if(((A[i] % 10 + A[i] / 10) % 6 != 0) && A[i] >= 10 && A[i] <= 99) { p *= A[i]; } } cout << p; return 0; }
31.833333
423
0.628272
albarkan
bddcb6b4bca10f4244aea6e556ec8fd0b2b3e1da
6,687
cxx
C++
src-plugins/libs/vtkInria/Examples/CompareImageManager/CompareImageManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/libs/vtkInria/Examples/CompareImageManager/CompareImageManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/libs/vtkInria/Examples/CompareImageManager/CompareImageManager.cxx
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <vtkRenderingAddOn/vtkViewImage3D.h> #include <vtkRenderingAddOn/vtkViewImage2D.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkStructuredPointsReader.h> #include <vtkStructuredPoints.h> #include "vtkImageFuse.h" #include "vtkImageMapToColors.h" #include "vtkLookupTable.h" #include "vtkImageBlend.h" #include "vtkImageCheckerboard.h" #include "vtkImageClamp.h" #include "vtkImageMapToColors.h" #include "vtkLookupTableManager.h" int main (int argc, char*argv[]) { if( argc<3 ) { std::cout << "Usage: " << std::endl; std::cout << "\t" << argv[0] << " <image file 1> <image file 2>" << std::endl; std::cout << "Example: " << std::endl; std::cout << "\t" << argv[0] << " [vtkINRIA3D_DATA_DIR]/MRI.vtk vtkINRIA3D_DATA_DIR]/MRI2.vtk" << std::endl; exit (-1); } /** In this example, we illustrate the use of the vtkCompareImageManager. We first set up four vtkImageView2D/3D to display an image. */ vtkViewImage2D* view1 = vtkViewImage2D::New(); vtkViewImage2D* view2 = vtkViewImage2D::New(); vtkViewImage2D* view3 = vtkViewImage2D::New(); vtkViewImage3D* view4 = vtkViewImage3D::New(); vtkRenderWindowInteractor* iren1 = vtkRenderWindowInteractor::New(); vtkRenderWindowInteractor* iren2 = vtkRenderWindowInteractor::New(); vtkRenderWindowInteractor* iren3 = vtkRenderWindowInteractor::New(); vtkRenderWindowInteractor* iren4 = vtkRenderWindowInteractor::New(); vtkRenderWindow* rwin1 = vtkRenderWindow::New(); vtkRenderWindow* rwin2 = vtkRenderWindow::New(); vtkRenderWindow* rwin3 = vtkRenderWindow::New(); vtkRenderWindow* rwin4 = vtkRenderWindow::New(); vtkRenderer* renderer1 = vtkRenderer::New(); vtkRenderer* renderer2 = vtkRenderer::New(); vtkRenderer* renderer3 = vtkRenderer::New(); vtkRenderer* renderer4 = vtkRenderer::New(); iren1->SetRenderWindow (rwin1); iren2->SetRenderWindow (rwin2); iren3->SetRenderWindow (rwin3); iren4->SetRenderWindow (rwin4); rwin1->AddRenderer (renderer1); rwin2->AddRenderer (renderer2); rwin3->AddRenderer (renderer3); rwin4->AddRenderer (renderer4); view1->SetRenderWindow ( rwin1 ); view2->SetRenderWindow ( rwin2 ); view3->SetRenderWindow ( rwin3 ); view4->SetRenderWindow ( rwin4 ); view1->SetRenderer ( renderer1 ); view2->SetRenderer ( renderer2 ); view3->SetRenderer ( renderer3 ); view4->SetRenderer ( renderer4 ); view1->SetAboutData ("Powered by vtkINRIA3D"); view2->SetAboutData ("Powered by vtkINRIA3D"); view3->SetAboutData ("Powered by vtkINRIA3D"); view4->SetAboutData ("Powered by vtkINRIA3D"); view1->AddChild (view2); view2->AddChild (view3); view3->AddChild (view4); view4->AddChild (view1); view1->SetLeftButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION); view1->SetMiddleButtonInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view1->SetWheelInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view1->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION); view2->SetLeftButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION); view2->SetMiddleButtonInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view2->SetWheelInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view2->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION); view3->SetLeftButtonInteractionStyle (vtkViewImage2D::ZOOM_INTERACTION); view3->SetMiddleButtonInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view3->SetWheelInteractionStyle (vtkViewImage2D::SELECT_INTERACTION); view3->SetRightButtonInteractionStyle (vtkViewImage2D::WINDOW_LEVEL_INTERACTION); view1->SetLinkZoom (true); view2->SetLinkZoom (true); view3->SetLinkZoom (true); view1->SetLinkWindowLevel (0); view2->SetLinkWindowLevel (0); view3->SetLinkWindowLevel (0); vtkStructuredPointsReader* reader1 = vtkStructuredPointsReader::New(); reader1->SetFileName (argv[1]); reader1->GetOutput()->Update(); vtkStructuredPointsReader* reader2 = vtkStructuredPointsReader::New(); reader2->SetFileName (argv[2]); reader2->GetOutput()->Update(); view1->SetImage (reader1->GetOutput()); view2->SetImage (reader2->GetOutput()); vtkLookupTable* spectrumlut = vtkLookupTableManager::GetSpectrumLookupTable(); vtkLookupTable* gelut = vtkLookupTableManager::GetGEColorLookupTable(); view2->SetLookupTable (gelut); view1->SyncReset(); vtkImageFuse* manager1 = vtkImageFuse::New(); vtkImageFuse* manager2 = vtkImageFuse::New(); manager1->UseClampOff(); manager1->UseColorMapsOn(); manager1->SetLookupTable1 (vtkLookupTable::SafeDownCast (view1->GetLookupTable())); manager1->SetLookupTable2 (vtkLookupTable::SafeDownCast (view2->GetLookupTable())); manager2->SetLookupTable1 (vtkLookupTable::SafeDownCast (view1->GetLookupTable())); manager2->SetLookupTable2 (vtkLookupTable::SafeDownCast (view2->GetLookupTable())); manager1->SetInput ( 0, reader1->GetOutput() ); manager1->SetInput ( 1, reader2->GetOutput() ); manager2->SetInput ( 0, reader1->GetOutput() ); manager2->SetInput ( 1, reader2->GetOutput() ); manager1->SetFuseMode ( vtkImageFuse::FUSEMODE_BLEND ); manager2->SetFuseMode ( vtkImageFuse::FUSEMODE_GRID ); manager1->SetBlendAlpha (0.5); manager2->SetCheckerAlpha (0.06); manager1->Update(); manager2->Update(); view3->SetImage (manager1->GetOutput()); view4->SetImage (manager2->GetOutput()); view1->SyncReset(); rwin1->Render(); rwin2->Render(); rwin3->Render(); rwin4->Render(); iren1->Start(); iren2->Start(); iren3->Start(); iren4->Start(); spectrumlut->Delete(); gelut->Delete(); manager1->Delete(); manager2->Delete(); view1->Detach(); view2->Detach(); view3->Detach(); view4->Detach(); view1->Delete(); view2->Delete(); view3->Delete(); view4->Delete(); iren1->Delete(); iren2->Delete(); iren3->Delete(); iren4->Delete(); rwin1->Delete(); rwin2->Delete(); rwin3->Delete(); rwin4->Delete(); renderer1->Delete(); renderer2->Delete(); renderer3->Delete(); renderer4->Delete(); reader1->Delete(); reader2->Delete(); return 0; }
29.073913
112
0.701959
ocommowi
bddd56037c47e9677b2602fdb4e9233b0568a832
29,999
cc
C++
TimingAnalyzer/plugins/CommonUtils.cc
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
2
2017-10-19T12:28:53.000Z
2019-05-22T14:36:05.000Z
TimingAnalyzer/plugins/CommonUtils.cc
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
null
null
null
TimingAnalyzer/plugins/CommonUtils.cc
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
6
2017-09-13T13:16:10.000Z
2019-01-28T17:39:51.000Z
#include "Timing/TimingAnalyzer/plugins/CommonUtils.hh" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" namespace oot { /////////////////////////// // Object Prep Functions // /////////////////////////// void ReadInTriggerNames(const std::string & inputPaths, std::vector<std::string> & pathNames, strBitMap & triggerBitMap) { if (Config::file_exists(inputPaths)) { std::ifstream pathStream(inputPaths.c_str(),std::ios::in); std::string path; while (pathStream >> path) { if (path != "") { pathNames.emplace_back(path); triggerBitMap[path] = false; } } } // check to make sure text file exists } void ReadInFilterNames(const std::string & inputFilters, std::vector<std::string> & filterNames, std::map<std::string,std::vector<pat::TriggerObjectStandAlone> > & triggerObjectsByFilterMap) { if (Config::file_exists(inputFilters)) { std::ifstream filterStream(inputFilters.c_str(),std::ios::in); std::string label;// instance, processName; while (filterStream >> label) { if (label != "") { filterNames.emplace_back(label); triggerObjectsByFilterMap[label].clear(); } } } // check to make sure text file exists } void PrepNeutralinos(const edm::Handle<std::vector<reco::GenParticle> > & genparticlesH, std::vector<reco::GenParticle> & neutralinos) { auto nNeutoPhGr = 0; for (const auto & genparticle : *genparticlesH) // loop over gen particles { if (nNeutoPhGr == 2) break; if (genparticle.pdgId() == 1000022 && genparticle.numberOfDaughters() == 2) { if ((genparticle.daughter(0)->pdgId() == 22 && genparticle.daughter(1)->pdgId() == 1000039) || (genparticle.daughter(1)->pdgId() == 22 && genparticle.daughter(0)->pdgId() == 1000039)) { nNeutoPhGr++; neutralinos.emplace_back(genparticle); } // end conditional over matching daughter ids } // end conditional over neutralino id } // end loop over gen particles std::sort(neutralinos.begin(),neutralinos.end(),oot::sortByPt); } void PrepVPions(const edm::Handle<std::vector<reco::GenParticle> > & genparticlesH, std::vector<reco::GenParticle> & vPions) { for (const auto & genparticle : *genparticlesH) // loop over gen particles { if (genparticle.pdgId() == 4900111 && genparticle.numberOfDaughters() == 2) { if (genparticle.daughter(0)->pdgId() == 22 && genparticle.daughter(1)->pdgId() == 22) { vPions.emplace_back(genparticle); } // end check over both gen photons } // end check over vPions } // end loop over gen particles std::sort(vPions.begin(),vPions.end(),oot::sortByPt); } void PrepToys(const edm::Handle<std::vector<reco::GenParticle> > & genparticlesH, std::vector<reco::GenParticle> & toys) { for (const auto & genparticle : *genparticlesH) // loop over gen particles { if (genparticle.pdgId() == 22) { toys.emplace_back(genparticle); } // end check over photons } // end loop over gen particles std::sort(toys.begin(),toys.end(),oot::sortByPt); } void PrepTriggerBits(edm::Handle<edm::TriggerResults> & triggerResultsH, const edm::Event & iEvent, strBitMap & triggerBitMap) { for (auto & triggerBitPair : triggerBitMap) { triggerBitPair.second = false; } const auto & triggerNames = iEvent.triggerNames(*triggerResultsH); for (auto itrig = 0U; itrig < triggerNames.size(); itrig++) { const auto & triggerName = triggerNames.triggerName(itrig); for (auto & triggerBitPair : triggerBitMap) { if (triggerName.find(triggerBitPair.first) != std::string::npos) triggerBitPair.second = triggerResultsH->accept(itrig); } // end loop over user path names } // end loop over trigger names } void PrepTriggerObjects(const edm::Handle<edm::TriggerResults> & triggerResultsH, const edm::Handle<std::vector<pat::TriggerObjectStandAlone> > & triggerObjectsH, const edm::Event & iEvent, std::map<std::string,std::vector<pat::TriggerObjectStandAlone> > & triggerObjectsByFilterMap) { // clear first for (auto & triggerObjectsByFilterPair : triggerObjectsByFilterMap) { triggerObjectsByFilterPair.second.clear(); } // store all the trigger objects needed to be checked later const auto & triggerNames = iEvent.triggerNames(*triggerResultsH); for (pat::TriggerObjectStandAlone triggerObject : *triggerObjectsH) { triggerObject.unpackPathNames(triggerNames); triggerObject.unpackFilterLabels(iEvent, *triggerResultsH); for (auto & triggerObjectsByFilterPair : triggerObjectsByFilterMap) { if (triggerObject.hasFilterLabel(triggerObjectsByFilterPair.first)) triggerObjectsByFilterPair.second.emplace_back(triggerObject); } // end loop over user filter names } // end loop over trigger objects for (auto & triggerObjectsByFilterPair : triggerObjectsByFilterMap) { std::sort(triggerObjectsByFilterPair.second.begin(),triggerObjectsByFilterPair.second.end(),oot::sortByPt); } } void PrepJets(const edm::Handle<std::vector<pat::Jet> > & jetsH, std::vector<pat::Jet> & jets, const float jetpTmin, const float jetEtamax, const int jetIDmin) { for (const auto & jet : *jetsH) { if (jet.pt() < jetpTmin) continue; if (std::abs(jet.eta()) > jetEtamax) continue; const auto jetID = oot::GetPFJetID(jet); if (jetID < jetIDmin) continue; // save the jets, and then store the ID jets.emplace_back(jet); jets.back().addUserInt(Config::JetID,jetID); std::sort(jets.begin(),jets.end(),oot::sortByPt); } } void PrepRecHits(const EcalRecHitCollection * recHitsEB, const EcalRecHitCollection * recHitsEE, uiiumap & recHitMap, const float rhEmin) { auto i = 0; for (const auto & recHit : *recHitsEB) { if (recHit.energy() > rhEmin) { recHitMap[recHit.detid().rawId()] = i++; } } for (const auto & recHit : *recHitsEE) { if (recHit.energy() > rhEmin) { recHitMap[recHit.detid().rawId()] = i++; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Photon Cross-Cleaning and MET Corrections // // // // The photon cross-cleaning is applied to remove overlapping photon objects from the two photon collections (GED and OOT). // // If photond in one collection overlaps with photons in the other collection, the one with higher pT is kept, and the other photons are dropped. // // // // Since OOT photons are not used in the computation of the MET, we have to apply the appropriate correction to the MET when an OOT photon is // // either completely unmatched or is matched to a GED photon and is higher in pT than the GED photon. // // // // Namely, we __subtract__ the 4-vector of any added OOT photons, and __add__ the 4-vector of any dropped GED photons. // // // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void PrepPhotonsCorrectMET(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, std::vector<pat::Photon> & photons, pat::MET & t1pfMET, const float rho, const float dRmin, const float phpTmin, const std::string & phIDmin) { // container for which photons to keep/drop std::vector<oot::ReducedPhoton> reducedPhotons; /////////////////// // Find overlaps // /////////////////// oot::FindOverlapPhotons(gedPhotonsH,ootPhotonsH,reducedPhotons,dRmin); /////////////////////////////// // Produce merged collection // /////////////////////////////// oot::MergePhotons(gedPhotonsH,ootPhotonsH,reducedPhotons,photons,rho,phpTmin,phIDmin); ///////////////////// // Correct the MET // ///////////////////// oot::CorrectMET(gedPhotonsH,ootPhotonsH,reducedPhotons,t1pfMET); } void FindOverlapPhotons(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, std::vector<oot::ReducedPhoton> & reducedPhotons, const float dRmin) { /////////////////////////////////////////////////// // First, store all photons in single collection // /////////////////////////////////////////////////// // loop over all GED photons const auto nGED = gedPhotonsH->size(); for (auto iGED = 0U; iGED < nGED; iGED++) { reducedPhotons.emplace_back(iGED,false,false); } // loop over all OOT photons const auto nOOT = ootPhotonsH->size(); for (auto iOOT = 0U; iOOT < nOOT; iOOT++) { reducedPhotons.emplace_back(iOOT,true ,false); } /////////////////////////////////// // Second, sort the vector by pT // /////////////////////////////////// std::sort(reducedPhotons.begin(),reducedPhotons.end(), [&](const auto & i_reducedPhoton, const auto & j_reducedPhoton) { // tmps const auto i_idx = i_reducedPhoton.idx; const auto j_idx = j_reducedPhoton.idx; const auto i_isOOT = i_reducedPhoton.isOOT; const auto j_isOOT = j_reducedPhoton.isOOT; const auto & i_photon = (i_isOOT ? (*ootPhotonsH)[i_idx] : (*gedPhotonsH)[i_idx]); const auto & j_photon = (j_isOOT ? (*ootPhotonsH)[j_idx] : (*gedPhotonsH)[j_idx]); return oot::GetPhotonPt(i_photon) > oot::GetPhotonPt(j_photon); }); ////////////////////////////////////////////////////////// // Mark for removal overlaps from different collections // ////////////////////////////////////////////////////////// // loop over full merged collection const auto nPHO = reducedPhotons.size(); for (auto iPHO = 0U; iPHO < nPHO; iPHO++) { // get tmps for 1st photon const auto & i_reducedPhoton = reducedPhotons[iPHO]; const auto i_idx = i_reducedPhoton.idx; // skip if already marked for removal! if (i_reducedPhoton.toRemove) continue; // get remainder of tmps for 1st photon const auto i_isOOT = i_reducedPhoton.isOOT; const auto & i_photon = (i_isOOT ? (*ootPhotonsH)[i_idx] : (*gedPhotonsH)[i_idx]); // only check those that are lower in pT for (auto jPHO = iPHO+1; jPHO < nPHO; jPHO++) { // get tmps for 2nd photon auto & j_reducedPhoton = reducedPhotons[jPHO]; const auto j_idx = j_reducedPhoton.idx; // skip if already marked for removal! if (j_reducedPhoton.toRemove) continue; // skip if from the same collection const auto j_isOOT = j_reducedPhoton.isOOT; if (i_isOOT == j_isOOT) continue; // get 2nd photon const auto & j_photon = (j_isOOT ? (*ootPhotonsH)[j_idx] : (*gedPhotonsH)[j_idx]); // if photons overlap, mark lower pT one for removal if (reco::deltaR(i_photon,j_photon) < dRmin) { j_reducedPhoton.toRemove = true; } // end check over dR } // end loop over lower pT photons } // end loop over all photons } void MergePhotons(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, const std::vector<oot::ReducedPhoton> & reducedPhotons, std::vector<pat::Photon> & photons, const float rho, const float phpTmin, const std::string & phIDmin) { // loop over all photons, check if it passes cuts, then save it for (const auto & reducedPhoton : reducedPhotons) { // get tmps const auto idx = reducedPhoton.idx; const auto isOOT = reducedPhoton.isOOT; // get the photon const auto & photon = (isOOT ? (*ootPhotonsH)[idx] : (*gedPhotonsH)[idx]); // check to ensure it was not marked for removal! if (reducedPhoton.toRemove) continue; // cut on low pt if (oot::GetPhotonPt(photon) < phpTmin) continue; // store the GED and OOT VID std::vector<pat::Photon::IdPair> idpairs = {{Config::LooseGED,false}, {Config::MediumGED,false}, {Config::TightGED,false}, {Config::TightOOT,false}}; oot::GetGEDPhoVID(photon,idpairs); if (isOOT) oot::GetOOTPhoVID (photon,idpairs); else oot::GetOOTPhoVIDByHand(photon,idpairs,rho); // skip bad ID'ed photons if (phIDmin != Config::EmptyVID) { auto isGoodID = true; for (const auto & idpair : idpairs) { if (idpair.first.find(phIDmin) != std::string::npos) // correct for GED or OOT! { if ((isOOT && idpair.first.find("oot")) || (!isOOT && idpair.first.find("ged"))) { if (!idpair.second) isGoodID = false; break; } } } if (!isGoodID) continue; } // end check for bad ID // save it in the final vector! photons.emplace_back(photon); // and then modify it! auto & tmpphoton = photons.back(); tmpphoton.setPhotonIDs(idpairs); tmpphoton.addUserData<bool>(Config::IsOOT,isOOT); } // end loop over photons } void CorrectMET(const edm::Handle<std::vector<pat::Photon> > & gedPhotonsH, const edm::Handle<std::vector<pat::Photon> > & ootPhotonsH, const std::vector<ReducedPhoton> & reducedPhotons, pat::MET & t1pfMET) { //////////////////////////////// // Compute Correction Factors // //////////////////////////////// // inputs to MET correction auto t1pfMETpx = t1pfMET.px(); auto t1pfMETpy = t1pfMET.py(); auto t1pfMETsumEt = t1pfMET.sumEt(); // loop over all photons, correct for DROPPED GED and STORED OOT for (const auto & reducedPhoton : reducedPhotons) { // get tmps const auto idx = reducedPhoton.idx; const auto isOOT = reducedPhoton.isOOT; const auto toRemove = reducedPhoton.toRemove; // get the photon const auto & photon = (isOOT ? (*ootPhotonsH)[idx] : (*gedPhotonsH)[idx]); // apply met corrections as needed if (isOOT && !toRemove) // add the OOT photons if being stored! { // get inputs const auto pt = oot::GetPhotonPt(photon); const auto phi = photon.phi(); // set MET t1pfMETpx -= pt*std::cos(phi); t1pfMETpy -= pt*std::sin(phi); t1pfMETsumEt += oot::GetPhotonEt(photon); } else if (!isOOT && toRemove) // subtract the GED photons if being dropped! { // get inputs const auto pt = oot::GetPhotonPt(photon); const auto phi = photon.phi(); // set MET t1pfMETpx += pt*std::cos(phi); t1pfMETpy += pt*std::sin(phi); t1pfMETsumEt -= oot::GetPhotonEt(photon); } } // end loop over all photons //////////////////// // Set MET Object // //////////////////// t1pfMET.addUserFloat(Config::OOTMETPt,Config::hypo(t1pfMETpx,t1pfMETpy)); t1pfMET.addUserFloat(Config::OOTMETPhi,Config::phi(t1pfMETpx,t1pfMETpy)); t1pfMET.addUserFloat(Config::OOTMETSumEt,t1pfMETsumEt); } /////////////////////// // Pruning Functions // /////////////////////// void PrunePhotons(std::vector<pat::Photon> & photons, const EcalRecHitCollection * recHitsEB, const EcalRecHitCollection * recHitsEE, const float seedTimemin) { photons.erase(std::remove_if(photons.begin(),photons.end(), [seedTimemin,&recHitsEB,&recHitsEE](const auto & photon) { const auto & phosc = photon.superCluster().isNonnull() ? photon.superCluster() : photon.parentSuperCluster(); const auto & seedDetId = phosc->seed()->seed(); // get seed detid const auto recHits = ((seedDetId.subdetId() == EcalSubdetector::EcalBarrel) ? recHitsEB : recHitsEE); // which recHits to use const auto seedHit = recHits->find(seedDetId); // get the underlying rechit const auto seedTime = ((seedHit != recHits->end()) ? seedHit->time() : -9999.f); return (seedTime < seedTimemin); }),photons.end()); } void PruneJets(std::vector<pat::Jet> & jets, const std::vector<pat::Photon> & photons, const int nPhosmax, const float dRmin) { // clean out w.r.t. to nMaxPhos const auto nPhos = std::min<int>(photons.size(),nPhosmax); // loop over at most the leading photons and clean... for (auto ipho = 0; ipho < nPhos; ipho++) { const auto & photon = photons[ipho]; // apply loose selection on photon const auto HoverE = photon.hadTowOverEm(); const auto Sieie = photon.full5x5_sigmaIetaIeta(); const auto eta = std::abs(photon.superCluster()->eta()); // cuts set to be looser than trigger values by .05 in H/E and 0.005 in Sieie if ( ((eta < Config::etaEBcutoff) && (HoverE < 0.25) && (Sieie < 0.019)) || ((eta >= Config::etaEBcutoff && eta < Config::etaEEmax) && (HoverE < 0.2) && (Sieie < 0.04)) ) { jets.erase(std::remove_if(jets.begin(),jets.end(), [dRmin,&photon](const auto & jet) { return (reco::deltaR(jet,photon) < dRmin); }),jets.end()); } } } /////////////////////////////// // Effective Areas Functions // /////////////////////////////// float GetChargedHadronEA(const float eta) { if (eta < 1.0 ) return 0.0112; else if (eta >= 1.0 && eta < 1.479) return 0.0108; else if (eta >= 1.479 && eta < 2.0 ) return 0.0106; else if (eta >= 2.0 && eta < 2.2 ) return 0.01002; else if (eta >= 2.2 && eta < 2.3 ) return 0.0098; else if (eta >= 2.3 && eta < 2.4 ) return 0.0089; else if (eta >= 2.4 ) return 0.0087; else return 0.; } float GetNeutralHadronEA(const float eta) { if (eta < 1.0 ) return 0.0668; else if (eta >= 1.0 && eta < 1.479) return 0.1054; else if (eta >= 1.479 && eta < 2.0 ) return 0.0786; else if (eta >= 2.0 && eta < 2.2 ) return 0.0233; else if (eta >= 2.2 && eta < 2.3 ) return 0.0078; else if (eta >= 2.3 && eta < 2.4 ) return 0.0028; else if (eta >= 2.4 ) return 0.0137; else return 0.; } float GetGammaEA(const float eta) { if (eta < 1.0 ) return 0.1113; else if (eta >= 1.0 && eta < 1.479) return 0.0953; else if (eta >= 1.479 && eta < 2.0 ) return 0.0619; else if (eta >= 2.0 && eta < 2.2 ) return 0.0837; else if (eta >= 2.2 && eta < 2.3 ) return 0.1070; else if (eta >= 2.3 && eta < 2.4 ) return 0.1212; else if (eta >= 2.4 ) return 0.1466; else return 0.; } float GetEcalPFClEA(const float eta) { if (eta < 0.8 ) return 0.1324; else if (eta >= 0.8 && eta < 1.4422) return 0.08638; else return 0.f; } float GetHcalPFClEA(const float eta) { if (eta < 0.8 ) return 0.1094; else if (eta >= 0.8 && eta < 1.4422) return 0.09392; else return 0.f; } float GetTrackEA(const float eta) { if (eta < 0.8 ) return 0.02276; else if (eta >= 0.8 && eta < 1.4422) return 0.00536; else return 0.f; } ////////////////////////// // pT Scaling Functions // ////////////////////////// float GetNeutralHadronPtScale(const float eta, const float pt) { if (eta < Config::etaEBcutoff) return 0.01512*pt+0.00002259*pt*pt; else if (eta >= Config::etaEBcutoff && eta < Config::etaEEmax) return 0.0117 *pt+0.00002305*pt*pt; else return 0.f; } float GetGammaPtScale(const float eta, const float pt) { if (eta < Config::etaEBcutoff) return 0.004017*pt; else if (eta >= Config::etaEBcutoff && eta < Config::etaEEmax) return 0.0037 *pt; else return 0.f; } float GetEcalPFClPtScale(const float eta, const float pt) { if (eta < 1.4442) return 0.003008*pt; else return 0.f; } float GetHcalPFClPtScale(const float eta, const float pt) { if (eta < 1.4442) return 0.00002921*pt*pt-0.005802*pt; else return 0.f; } ////////////////////////// // Object VID Functions // ////////////////////////// void GetGEDPhoVID(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs) { idpairs[2].second = photon.photonID(Config::GEDPhotonTightVID); idpairs[1].second = photon.photonID(Config::GEDPhotonMediumVID); idpairs[0].second = photon.photonID(Config::GEDPhotonLooseVID); } void GetGEDPhoVIDByHand(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs, const float rho) { // needed for cuts const auto eta = std::abs(photon.superCluster()->eta()); const auto pt = photon.pt(); // uncorrected pt: https://twiki.cern.ch/twiki/bin/view/CMS/EgammaPostRecoRecipes#Advanced_usage_of_EgammaPostReco // cut variables const auto HoverE = photon.hadTowOverEm(); const auto Sieie = photon.full5x5_sigmaIetaIeta(); const auto ChgHadIso = std::max(photon.chargedHadronIso() - (rho * oot::GetChargedHadronEA(eta)) ,0.f); const auto NeuHadIso = std::max(photon.neutralHadronIso() - (rho * oot::GetNeutralHadronEA(eta)) - (oot::GetNeutralHadronPtScale(eta,pt)),0.f); const auto PhoIso = std::max(photon.photonIso() - (rho * oot::GetGammaEA (eta)) - (oot::GetGammaPtScale (eta,pt)),0.f); if (eta < Config::etaEBcutoff) { if ((HoverE < 0.02148) && (Sieie < 0.0096) && (ChgHadIso < 0.65) && (NeuHadIso < 0.317) && (PhoIso < 2.044)) { idpairs[2].second = true; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.02197) && (Sieie < 0.0105) && (ChgHadIso < 1.141) && (NeuHadIso < 1.189) && (PhoIso < 2.08)) { idpairs[2].second = false; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.04596) && (Sieie < 0.0106) && (ChgHadIso < 1.694) && (NeuHadIso < 24.032) && (PhoIso < 2.876)) { idpairs[2].second = false; idpairs[1].second = false; idpairs[0].second = true; } } else if (eta >= Config::etaEBcutoff && eta < Config::etaEEmax) { if ((HoverE < 0.0321) && (Sieie < 0.0271) && (ChgHadIso < 0.517) && (NeuHadIso < 2.716) && (PhoIso < 3.032)) { idpairs[2].second = true; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.0326) && (Sieie < 0.0272) && (ChgHadIso < 1.051) && (NeuHadIso < 2.718) && (PhoIso < 3.867)) { idpairs[2].second = false; idpairs[1].second = true; idpairs[0].second = true; } else if ((HoverE < 0.059) && (Sieie < 0.0272) && (ChgHadIso < 2.089) && (NeuHadIso < 19.722) && (PhoIso < 4.162)) { idpairs[2].second = false; idpairs[1].second = false; idpairs[0].second = true; } } } void GetOOTPhoVID(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs) { idpairs[3].second = photon.photonID(Config::OOTPhotonTightVID); } void GetOOTPhoVIDByHand(const pat::Photon & photon, std::vector<pat::Photon::IdPair> & idpairs, const float rho) { // needed for cuts const auto eta = std::abs(photon.superCluster()->eta()); const auto pt = photon.pt(); // cut variables const auto HoverE = photon.hadTowOverEm(); const auto Sieie = photon.full5x5_sigmaIetaIeta(); const auto EcalPFClIso = std::max(photon.ecalPFClusterIso() - (rho * oot::GetEcalPFClEA(eta)) - (oot::GetEcalPFClPtScale(eta,pt)),0.f); const auto HcalPFClIso = std::max(photon.hcalPFClusterIso() - (rho * oot::GetHcalPFClEA(eta)) - (oot::GetHcalPFClPtScale(eta,pt)),0.f); const auto TrkIso = std::max(photon.trackIso() - (rho * oot::GetTrackEA (eta)) ,0.f); if ((HoverE < 0.02148) && (Sieie < 0.014) && (EcalPFClIso < 5.f) && (HcalPFClIso < 4.f) && (TrkIso < 4.f)) { idpairs[3].second = true; } } int GetPFJetID(const pat::Jet & jet) // https://twiki.cern.ch/twiki/bin/view/CMS/JetID13TeVRun2017 { const auto eta = std::abs(jet.eta()); const auto NHF = jet.neutralHadronEnergyFraction(); const auto NEMF = jet.neutralEmEnergyFraction(); const auto CHF = jet.chargedHadronEnergyFraction(); const auto CEMF = jet.chargedEmEnergyFraction(); const auto NHM = jet.neutralMultiplicity(); const auto CHM = jet.chargedMultiplicity(); const auto SHM = jet.chargedMultiplicity()+jet.neutralMultiplicity(); const auto MUF = jet.muonEnergyFraction(); // 2 == TightLepVeto // 1 == Tight if (eta <= 2.4) { if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1) && (MUF < 0.80) && (CHF > 0) && (CHM > 0) && (CEMF < 0.80)) return 2; else if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1) && (CHF > 0) && (CHM > 0)) return 1; else return 0; } else if (eta > 2.4 && eta <= 2.7) { if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1) && (MUF < 0.80)) return 2; else if ((NHF < 0.90) && (NEMF < 0.90) && (SHM > 1)) return 1; else return 0; } else if (eta > 2.7 && eta <= 3.0) { if ((NEMF > 0.02) && (NEMF < 0.99) && (NHM > 2)) return 1; else return 0; } else { if ((NEMF < 0.90) && (NHF > 0.02) && (NHM > 10)) return 1; else return 0; } return -1; // should not happen } /////////////////////// // Storing Functions // /////////////////////// void SplitPhotons(std::vector<pat::Photon> & photons, const int nmax) { std::vector<int> gedphos; std::vector<int> ootphos; auto ipho = 0; for (const auto & photon : photons) { (!*(photon.userData<bool>(Config::IsOOT)) ? gedphos : ootphos).emplace_back(ipho++); } std::vector<pat::Photon> tmpphotons; const int ngedphos = gedphos.size(); for (auto i = 0; i < nmax; i++) { if (ngedphos > i) tmpphotons.emplace_back(photons[gedphos[i]]); } const int nootphos = ootphos.size(); for (auto i = 0; i < nmax; i++) { if (nootphos > i) tmpphotons.emplace_back(photons[ootphos[i]]); } photons.swap(tmpphotons); } void StoreOnlyPho(std::vector<pat::Photon> & photons, const int nmax, const bool isOOT) { std::vector<pat::Photon> tmpphotons; auto ipho = 0; for (const auto & photon : photons) { if (ipho >= nmax) break; ipho++; if (*(photon.userData<bool>(Config::IsOOT)) == isOOT) tmpphotons.emplace_back(photon); } photons.swap(tmpphotons); } ///////////////////// // Debug Functions // ///////////////////// void DumpPhoton(const pat::Photon & photon, const bool isOOT, const EcalRecHitCollection * recHitsEB, const EcalRecHitCollection * recHitsEE) { std::cout << (isOOT ? "OOT" : "GED") << " Photon Info -->" << " pT: " << std::setprecision(3) << oot::GetPhotonPt(photon) << " phi: " << std::setprecision(3) << photon.phi() << " eta: " << std::setprecision(3) << photon.eta() << std::endl; const auto & phosc = photon.superCluster().isNonnull() ? photon.superCluster() : photon.parentSuperCluster(); const auto & seedDetId = phosc->seed()->seed(); // get seed detid const auto isEB = (seedDetId.subdetId() == EcalSubdetector::EcalBarrel); std::cout << " isEB: " << isEB << " seedId: " << seedDetId.rawId() << std::endl; const auto recHits = (isEB ? recHitsEB : recHitsEE); // get rechits const auto & hitsAndFractions = phosc->hitsAndFractions(); // get vector of detids // loop over all rec hits in SC for (auto hafitr = hitsAndFractions.begin(); hafitr != hitsAndFractions.end(); ++hafitr) { const auto & recHitDetId = hafitr->first; // get detid of crystal const auto & recHit = recHits->find(recHitDetId); const auto recHitId = recHitDetId.rawId(); // standard check if (recHit != recHits->end()) { if (recHit->energy() < 1) continue; std::cout << " rhId: " << recHitId; if (isEB) { const EBDetId recHitEB(recHitId); std::cout << " ieta: " << recHitEB.ieta() << " iphi: " << recHitEB.iphi(); } else { const EEDetId recHitEE(recHitId); std::cout << " ix: " << recHitEE.ix() << " iy: " << recHitEE.iy(); } std::cout << " isOOT: " << recHit->checkFlag(EcalRecHit::kOutOfTime) << " energy: " << std::setprecision(3) << recHit->energy() << " time: " << std::setprecision(3) << recHit->time() << std::endl; } } // end loop over hits and fractions } };
37.173482
176
0.560985
kmcdermo
bdde2152b74138579d8da71f7595eb4d4ae8c05c
527
hpp
C++
include/mgcpp/expressions/placeholder.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
48
2018-01-02T03:47:18.000Z
2021-09-09T05:55:45.000Z
include/mgcpp/expressions/placeholder.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
24
2017-12-27T18:03:13.000Z
2018-07-02T09:00:30.000Z
include/mgcpp/expressions/placeholder.hpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
6
2018-01-14T14:06:10.000Z
2018-10-16T08:43:01.000Z
#ifndef PLACEHOLDER_HPP #define PLACEHOLDER_HPP #include <mgcpp/expressions/forward.hpp> namespace mgcpp { struct placeholder_node_type; template <size_t PlaceholderID, typename ResultType> using placeholder_node = generic_expr<placeholder_node_type, PlaceholderID, ResultType::template result_expr_type, ResultType, 0>; } // namespace mgcpp #endif // PLACEHOLDER_HPP
27.736842
76
0.582543
MGfoundation
bddfc32b9fb917c116a4db07b56e45c23dd2481f
1,622
hpp
C++
rsked/inetcheck.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
rsked/inetcheck.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
null
null
null
rsked/inetcheck.hpp
farlies/rsked
cd2004bed454578f4d2ac25996dc1ced98d4fa58
[ "Apache-2.0" ]
1
2020-10-04T22:14:55.000Z
2020-10-04T22:14:55.000Z
#pragma once /// You may optionally configure this in rsked.json like: /// { ... /// "Inet_checker" : { /// "enabled" : true, /// "status_path" : "/run/user/1000/netstat", /// "refresh" : 60 /// }, ... /// /// Without configuration, it will be enabled with reasonable defaults. /// /* Part of the rsked package. * Copyright 2020 Steven A. Harp farlies(at)gmail.com * * 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 <boost/filesystem.hpp> class Config; class Inet_checker { private: bool m_enabled {true}; boost::filesystem::path m_status_path; time_t m_last_check {0}; bool m_last_status {true}; time_t m_refresh_secs {60}; bool get_current_status(); public: time_t refresh_secs() const { return m_refresh_secs; } void set_refresh_secs(time_t); time_t last_check_time() const { return m_last_check; } boost::filesystem::path status_path() const { return m_status_path; } void configure( Config& ); bool enabled() const { return m_enabled; } bool inet_ready(); // Inet_checker(); };
30.037037
77
0.673243
farlies
bde11ce8b7ac613af0e4ce53a540b02c23a7f684
604
hpp
C++
third_party/boost/simd/arch/common/detail/scalar/exponential.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/arch/common/detail/scalar/exponential.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/arch/common/detail/scalar/exponential.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_EXPONENTIAL_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_EXPONENTIAL_HPP_INCLUDED #include <boost/simd/arch/common/detail/scalar/expo_base.hpp> #endif
33.555556
100
0.541391
SylvainCorlay
bde24956c5faa172c8cdfd4cba1977b538e2f62f
5,687
hpp
C++
include/cynodelic/metaflags/detail/string_parsing_helper.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
include/cynodelic/metaflags/detail/string_parsing_helper.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
include/cynodelic/metaflags/detail/string_parsing_helper.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODELIC_METAFLAGS_DETAIL_STRING_PARSING_HELPER_HPP #define CYNODELIC_METAFLAGS_DETAIL_STRING_PARSING_HELPER_HPP #include <cstdlib> #include <cstddef> #include <cstdint> #include <string> #include <stdexcept> #include <limits> #include <cynodelic/mulinum/if.hpp> #include <cynodelic/mulinum/integer_c.hpp> #include <cynodelic/mulinum/equals.hpp> #include <cynodelic/mulinum/logical_or.hpp> #include <cynodelic/metaflags/config.hpp> #include <cynodelic/metaflags/flag_arguments.hpp> namespace cynodelic { namespace metaflags { namespace detail { /** * @brief Tag selector for `string_parsing_helper` */ template <typename FlagArg> using select_sp_tag = mulinum::if_< mulinum::equals<typename FlagArg::value_type,std::int64_t>::value, mulinum::int_c<1>, mulinum::if_< mulinum::logical_or< mulinum::equals<typename FlagArg::value_type,std::int8_t>, mulinum::equals<typename FlagArg::value_type,std::int16_t>, mulinum::equals<typename FlagArg::value_type,std::int32_t> >::value, mulinum::int_c<2>, mulinum::if_< mulinum::equals<typename FlagArg::value_type,std::uint64_t>::value, mulinum::int_c<3>, mulinum::if_< mulinum::logical_or< mulinum::equals<typename FlagArg::value_type,std::uint8_t>, mulinum::equals<typename FlagArg::value_type,std::uint16_t>, mulinum::equals<typename FlagArg::value_type,std::uint32_t> >::value, mulinum::int_c<4>, mulinum::int_c<0> > > > >; /** * @brief Undefined */ template <typename,typename> struct string_parsing_helper_impl; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<1>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { return static_cast<typename FlagArg<Chars...>::value_type>(std::stoll(x)); } }; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<2>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { using val_type_ = typename FlagArg<Chars...>::value_type; long res = std::stol(x); if (res < static_cast<long>(std::numeric_limits<val_type_>::min()) || res > static_cast<long>(std::numeric_limits<val_type_>::max())) { throw std::out_of_range("[cynodelic::metaflags::detail::string_parsing_helper_impl<...,cynodelic::mulinum::int_c<2>>::call()] The parsed value is outside the range for the specified argument type."); } else { return static_cast<val_type_>(res); } } }; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<3>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { return static_cast<typename FlagArg<Chars...>::value_type>(std::stoull(x)); } }; /** * @brief Helper for `string_parsing_helper` */ template <template <char...> class FlagArg,char... Chars> struct string_parsing_helper_impl<FlagArg<Chars...>,mulinum::int_c<4>> { static inline typename FlagArg<Chars...>::value_type call(const std::string& x) { using val_type_ = typename FlagArg<Chars...>::value_type; unsigned long res = std::stoul(x); if (res < static_cast<unsigned long>(std::numeric_limits<val_type_>::min()) || res > static_cast<unsigned long>(std::numeric_limits<val_type_>::max())) { throw std::out_of_range("[cynodelic::metaflags::detail::string_parsing_helper_impl<...,cynodelic::mulinum::int_c<4>>::call()] The parsed value is outside the range for the specified argument type."); } else { return static_cast<typename FlagArg<Chars...>::value_type>(res); } } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<flt_arg<Chars...>,mulinum::int_c<0>> { static inline typename flt_arg<Chars...>::value_type call(const std::string& x) { return std::stof(x); } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<dbl_arg<Chars...>,mulinum::int_c<0>> { static inline typename dbl_arg<Chars...>::value_type call(const std::string& x) { return std::stod(x); } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<bln_arg<Chars...>,mulinum::int_c<0>> { static inline typename bln_arg<Chars...>::value_type call(const std::string& x) { if (x == "1" || x == "true") return true; else if (x == "0" || x == "false") return false; else throw std::invalid_argument("Not a valid boolean argument"); } }; /** * @brief Helper for `string_parsing_helper` */ template <char... Chars> struct string_parsing_helper_impl<str_arg<Chars...>,mulinum::int_c<0>> { static inline typename str_arg<Chars...>::value_type call(const std::string& x) { return x; } }; /** * @brief Helper type for string parsing */ template <typename FlagArg> using string_parsing_helper = string_parsing_helper_impl<FlagArg,select_sp_tag<FlagArg>>; } // end of "detail" namespace }} // end of "cynodelic::metaflags" namespace #endif // CYNODELIC_METAFLAGS_DETAIL_STRING_PARSING_HELPER_HPP
27.080952
203
0.697204
cynodelic
bde28cbdddddd64c2e0c9ccc289e5c8dd12c653b
197
c++
C++
Jcoord.c++
SRTCpp/Code
67c311566cee7b3e5cd8440ac2f7531f1737e293
[ "Apache-2.0" ]
1
2018-09-24T21:58:03.000Z
2018-09-24T21:58:03.000Z
Jcoord.c++
SRTCpp/Code
67c311566cee7b3e5cd8440ac2f7531f1737e293
[ "Apache-2.0" ]
null
null
null
Jcoord.c++
SRTCpp/Code
67c311566cee7b3e5cd8440ac2f7531f1737e293
[ "Apache-2.0" ]
null
null
null
#include "Jcoord.h" coord::coord() { x=0; y=0; z=0; } coord::coord(int a, int b, int c) { x=a; y=b; z=c; } int& coord::A() { if (a==X) return x; if (a==Y) return y; if (a==Z) return z; }
10.368421
33
0.507614
SRTCpp
bdf1f361639e5dc85e7bd8746cb23b34c63be69f
2,675
cpp
C++
Photon/Plugins/PhilipsHue/src/HueLight.cpp
rlisle/ProjectIoT
abdb7efa36657fcd942626975d2156ef5d02c8bc
[ "MIT" ]
null
null
null
Photon/Plugins/PhilipsHue/src/HueLight.cpp
rlisle/ProjectIoT
abdb7efa36657fcd942626975d2156ef5d02c8bc
[ "MIT" ]
null
null
null
Photon/Plugins/PhilipsHue/src/HueLight.cpp
rlisle/ProjectIoT
abdb7efa36657fcd942626975d2156ef5d02c8bc
[ "MIT" ]
null
null
null
/****************************************************************** HueLight plugin Features: - Control Philips Hue light. http://www.github.com/rlisle/Patriot Example code used from https://www.digikey.com/en/maker/blogs/2019/how-to-post-data-using-the-particle-photon Written by Ron Lisle BSD license, check license.txt for more information. All text above must be included in any redistribution. ******************************************************************/ #include "HueLight.h" #include "IoT.h" /** * Constructor * @param name String name of the checklist item */ HueLight::HueLight(String name, String room, String hueId, byte *server, String userid) : Device(name, room) { _hueId = hueId; memcpy(_server, server, 4); _userID = userid; _value = 0; _type = 'L'; } void HueLight::begin() { if(_tcpClient.connect(_server,80)) { Log("HueLight "+_name+" connected"); _tcpClient.stop(); } else { Log("HueLight "+_name+" failed to connect!"); } } /** * loop() * This is called repeatedly to allow device to do its work. */ void HueLight::loop() { //May want to implement fading? } /** * Set value * @param value Int 0 to 100 */ void HueLight::setValue(int value) { Log.info("HueLight " + _name + " setValue: " + String(value)); if(_value == value) { Log.info("HueLight value already set, but writing again!"); } _value = value; writeToHue(); } // Private Helper Methods // Using the HUE API, we'll set on/off and bri // Much more is possible through the API. void HueLight::writeToHue() { //TODO: lookup ID from name if(_tcpClient.connect(_server,80)) { String json; if(_value == 0) { json = "{\"on\":false}"; } else { // Convert 0-100% to 0-254 int newValue = (_value * 254) / 100; if(newValue > 254) newValue = 254; json = "{\"on\":true, \"bri\": " + String(newValue) + "}"; } Log.info("Hue json = " + json); _tcpClient.print("PUT /api/"); _tcpClient.print(_userID); _tcpClient.print("/lights/"); _tcpClient.print(_hueId); _tcpClient.println("/state HTTP/1.0"); _tcpClient.print("Content-Length: "); _tcpClient.println(json.length()); _tcpClient.println(); _tcpClient.println(json); } else { Log("HueLight "+_name+" not connected"); } } /** * notify() * Publish switch state */ void HueLight::notify() { String topic = "patriot/" + _name; String message = String(_value); IoT::mqttPublish(topic,message); }
23.883929
109
0.565607
rlisle
bdf71b4724a3c469b097fd77df4739bb67b89d75
482
cpp
C++
Arrays/169. Majority Element/Solution-sorting.cpp
VarunSAthreya/LeetCode-Solutions
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
[ "MIT" ]
1
2021-11-24T16:20:32.000Z
2021-11-24T16:20:32.000Z
Arrays/169. Majority Element/Solution-sorting.cpp
VarunSAthreya/LeetCode-Solutions
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
[ "MIT" ]
null
null
null
Arrays/169. Majority Element/Solution-sorting.cpp
VarunSAthreya/LeetCode-Solutions
aeab92df5bca208c2442ffdb1487fe5e3aadb3de
[ "MIT" ]
3
2021-09-03T15:14:12.000Z
2022-03-07T04:04:32.000Z
class Solution { public: int majorityElement(vector<int> &nums) { sort(nums.begin(), nums.end()); int ele = nums[0], count = 0; for (auto i : nums) { if (i == ele) { count++; if (count > (nums.size() / 2)) return i; } else { count = 1; ele = i; } } return -1; } };
18.538462
46
0.319502
VarunSAthreya
bdfa451f5aa3b83e21d923b2c5a222cb3a852e1e
2,371
cpp
C++
Source/Engine/src/util/CommandLine.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
null
null
null
Source/Engine/src/util/CommandLine.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
null
null
null
Source/Engine/src/util/CommandLine.cpp
DatZach/Swift
b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7
[ "MIT" ]
1
2021-10-30T20:43:01.000Z
2021-10-30T20:43:01.000Z
/* * cmdline.cpp * Command Line */ #include <algorithm> #include <Util/CommandLine.hpp> #ifdef WINDOWS #include <Windows.h> #include <io.h> #include <fcntl.h> #endif namespace Util { CommandLine::CommandLine(int argc, char* argv[]) : flags() { for(int i = 1; i < argc; ++i) { // Parse arguments starting with '--' as a flag std::string value = argv[i]; if (value.find_first_of("--") == std::string::npos) continue; // Parse argument if there is one std::string argument = ""; if (i + 1 < argc) { std::string tmp = argv[i + 1]; if (tmp.find_first_of("--") == std::string::npos) { argument = tmp; argument.erase(remove(argument.begin(), argument.end(), '"'), argument.end()); ++i; } } flags[value.substr(2)] = argument; } } bool CommandLine::RedirectIOToConsole() { #ifdef WINDOWS // Allocate a console for this app if (!AllocConsole()) return false; // Redirect unbuffered STDOUT to the console HANDLE lStdHandle = GetStdHandle(STD_OUTPUT_HANDLE); int hConHandle = _open_osfhandle(reinterpret_cast<intptr_t>(lStdHandle), _O_TEXT); FILE* fp = _fdopen(hConHandle, "w"); if (fp == NULL) return false; *stdout = *fp; setvbuf(stdout, NULL, _IONBF, 0); // Redirect unbuffered STDIN to the console lStdHandle = GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(reinterpret_cast<intptr_t>(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "r"); if (fp == NULL) return false; *stdin = *fp; setvbuf(stdin, NULL, _IONBF, 0); // Redirect unbuffered STDERR to the console lStdHandle = GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(reinterpret_cast<intptr_t>(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "w"); if (fp == NULL) return false; *stderr = *fp; setvbuf(stderr, NULL, _IONBF, 0); /* * Make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog * point to console as well. */ return std::ios::sync_with_stdio(); #else return true; #endif } std::string CommandLine::GetFlagArgument(const std::string& value) const { for(auto& flag : flags) { if (flag.first == value) return flag.second; } return ""; } bool CommandLine::IsFlagSet(const std::string& value) const { for(auto& flag : flags) { if (flag.first == value) return true; } return false; } }
20.982301
84
0.645719
DatZach
bdfc91c31dd3374b65f1939a4bae784cab8236ff
916
cpp
C++
_includes/leet755/leet755.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
_includes/leet755/leet755.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
8
2019-12-19T04:46:05.000Z
2022-02-26T03:45:22.000Z
_includes/leet755/leet755.cpp
mingdaz/leetcode
64f2e5ad0f0446d307e23e33a480bad5c9e51517
[ "MIT" ]
null
null
null
class Solution { public: vector<int> pourWater(vector<int>& heights, int count, int pos) { int n = (int)heights.size(); for (int k = 0; k < count; k++) { // drop to x int minIndex = pos, minHeight = heights[pos]; int i = pos; while (i - 1 >= 0 && heights[i] >= heights[i - 1]) { if (heights[i] > heights[i - 1]) { minIndex = i - 1; minHeight = heights[i - 1]; } i --; } if (minIndex < pos) { heights[minIndex] ++; continue; } i = pos; while (i + 1 < n && heights[i] >= heights[i + 1]) { if (heights[i] > heights[i + 1]) { minIndex = i + 1; minHeight = heights[i + 1]; } i ++; } heights[minIndex] ++; } return heights; } };
26.941176
69
0.394105
mingdaz
bdfce103ac76a7718ceeac654f2a674bb924bd68
12,678
cc
C++
crypto/openssl/bignum.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
crypto/openssl/bignum.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
10
2022-02-27T18:52:11.000Z
2022-03-21T14:11:35.000Z
crypto/openssl/bignum.cc
stablecc/scclib
cedcb3b37a814d3a393e128db7aa9753f518cbaf
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License Copyright (c) 2022, Stable Cloud Computing, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <crypto/bignum.h> #include <sstream> #include <openssl/bn.h> #include <openssl/err.h> #include <cctype> #include <crypto/random.h> struct BignumCtx { BIGNUM* m_bn; BN_CTX* m_ctx; BignumCtx() : m_ctx{nullptr} { m_bn = BN_new(); if (!m_bn) { auto e = ERR_get_error(); std::stringstream s; s << "BN_new: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } ~BignumCtx() { BN_free(m_bn); if (m_ctx) { BN_CTX_free(m_ctx); } } BIGNUM* bn() const { return m_bn; } BN_CTX* ctx() { if (!m_ctx) { m_ctx = BN_CTX_new(); if (!m_ctx) { auto e = ERR_get_error(); std::stringstream s; s << "BN_CTX_new: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } return m_ctx; } }; using namespace scc::crypto; Bignum exp(const Bignum& a, const Bignum& b) { scc::crypto::Bignum r(a); r.exp(b); return r; } Bignum exp(const Bignum& a, uint32_t b) { scc::crypto::Bignum r(a); r.exp(b); return r; } Bignum gcd(const Bignum& a, const Bignum& b) { Bignum r(a); r.gcd(b); return r; } Bignum gcd(const Bignum& a, uint32_t b) { Bignum r(a), bn(b); r.gcd(bn); return r; } std::ostream& operator <<(std::ostream& os, const scc::crypto::Bignum& sa) { std::string s; if (os.flags() & std::ios_base::hex) { s = sa.str(true); } else { s = sa.str(); } return os.write(s.c_str(), s.size()); } void scc::crypto::PrintTo(const scc::crypto::Bignum& bn, std::ostream* os) { *os << bn; } Bignum::Bignum() : m_bnctx(new BignumCtx()) { } Bignum::~Bignum() { } void* Bignum::bn() { return reinterpret_cast<void*>(m_bnctx->bn()); } const void* Bignum::const_bn() const { return reinterpret_cast<const void*>(m_bnctx->bn()); } void Bignum::copy(const Bignum& other) { if (!BN_copy(m_bnctx->bn(), other.m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_copy: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::move(Bignum& other) { m_bnctx.reset(other.m_bnctx.release()); other.m_bnctx.reset(new BignumCtx()); } void Bignum::clear() { BN_clear(m_bnctx->bn()); } int Bignum::width() const { if (BN_is_zero(m_bnctx->bn())) { return 1; } return BN_num_bits(m_bnctx->bn()); } void Bignum::exp(const Bignum& b) { Bignum orig(*this); if (!BN_exp(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_exp modulus: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::gcd(const Bignum& b) { Bignum orig(*this); if (!BN_gcd(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_gcd modulus: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } bool Bignum::is_prime(int trials) { int r = BN_is_prime_ex(m_bnctx->bn(), trials <= 0 ? BN_prime_checks : trials, m_bnctx->ctx(), nullptr); if (r == -1) { auto e = ERR_get_error(); std::stringstream s; s << "BN_is_prime_ex: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } return r == 1; } void Bignum::gen_rand(int bit_width, bool strong, bool odd) { if ((bit_width <= 0) || (strong && bit_width == 1)) { throw std::runtime_error("gen_rand bit width invalid"); } if (!BN_rand(m_bnctx->bn(), bit_width, strong ? BN_RAND_TOP_TWO : 0, odd ? BN_RAND_BOTTOM_ODD : 0)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_rand: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::gen_prime(int bit_width) { if (bit_width < 2) { throw std::runtime_error("gen_prime bit size too low"); } int r = BN_generate_prime_ex(m_bnctx->bn(), bit_width, 0, 0, 0, 0); if (r == 0) { auto e = ERR_get_error(); std::stringstream s; s << "BN_generate_prime_ex: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::negate() { BN_set_negative(m_bnctx->bn(), 1); } bool Bignum::is_negative() const { return BN_is_negative(m_bnctx->bn()) == 1 ? true : false; } int Bignum::cmp(const Bignum& other) const { return BN_cmp(m_bnctx->bn(), other.m_bnctx->bn()); } int Bignum::cmp(uint32_t w) const { if (is_negative()) { return -1; } if (w == 0) { if (BN_is_zero(m_bnctx->bn())) { return 0; } return 1; } if (w == 1) { if (BN_is_zero(m_bnctx->bn())) { return -1; } if (BN_is_one(m_bnctx->bn())) { return 0; } return 1; } Bignum b(w); return cmp(b); } void Bignum::lshift(int shift) { Bignum orig(*this); if (!BN_lshift(m_bnctx->bn(), orig.m_bnctx->bn(), shift)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_lshift: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::rshift(int shift) { Bignum orig(*this); if (!BN_rshift(m_bnctx->bn(), orig.m_bnctx->bn(), shift)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_rshift: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::add(const Bignum& b) { Bignum orig(*this); if (!BN_add(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_add: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::sub(const Bignum& b) { Bignum orig(*this); if (!BN_sub(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_sub: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::mul(const Bignum& b) { Bignum orig(*this); if (!BN_mul(m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_mul: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::div(const Bignum& b, Bignum* rem) { Bignum orig(*this); if (!BN_div(m_bnctx->bn(), rem?rem->m_bnctx->bn():nullptr, orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_div divide: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::mod(const Bignum& b) { Bignum orig(*this); if (!BN_div(nullptr, m_bnctx->bn(), orig.m_bnctx->bn(), b.m_bnctx->bn(), m_bnctx->ctx())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_div modulus: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } bool Bignum::is_bit_set(int bit_number) const { if (bit_number < 0) { throw std::runtime_error("is_bit_set() bit number invalid"); } if (bit_number >= width()) { return false; } return BN_is_bit_set(m_bnctx->bn(), bit_number) == 1; } void Bignum::set_bit(int bit_number) { if (bit_number < 0) { throw std::runtime_error("set_bit() bit number invalid"); } if (!BN_set_bit(m_bnctx->bn(), bit_number)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_set_bit: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::clear_bit(int bit_number) { if (bit_number < 0) { throw std::runtime_error("clear_bit() bit number invalid"); } if (bit_number >= width()) { return; } if (!BN_clear_bit(m_bnctx->bn(), bit_number)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_clear_bit: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } std::string Bignum::str(bool hex) const { char * bns; if (!hex) { bns = BN_bn2dec(m_bnctx->bn()); } else { bns = BN_bn2hex(m_bnctx->bn()); // library returns in upper case char* c = bns; for (; *c != 0; c++) { *c = static_cast<char>(std::tolower(static_cast<unsigned char>(*c))); } } if (!bns) { auto e = ERR_get_error(); std::stringstream s; s << (hex ? "BN_bn2hex" : "BN_bn2dec") << ": " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } std::string s(bns); OPENSSL_free(bns); return s; } int Bignum::len() const { if (BN_is_zero(m_bnctx->bn())) { return 1; } return BN_num_bytes(m_bnctx->bn()); } void Bignum::get(void * inloc, int inlen) const { if (inlen != len()) { std::stringstream s; s << "get() called with buffer len " << inlen << ", expected " << len(); throw std::runtime_error(s.str()); } if (BN_is_negative(m_bnctx->bn())) { throw std::runtime_error("get() called with negative number"); } if (BN_is_zero(m_bnctx->bn())) { *((char*)inloc) = 0; return; } if (!BN_bn2bin(m_bnctx->bn(), static_cast<unsigned char*>(inloc))) { auto e = ERR_get_error(); std::stringstream s; s << "BN_bn2bin: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::set(uint32_t w) { if (w == 0) { BN_zero(m_bnctx->bn()); } else if (w == 1) { if (!BN_one(m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_one: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } else if (!BN_set_word(m_bnctx->bn(), w)) { auto e = ERR_get_error(); std::stringstream s; s << "BN_set_word: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } void Bignum::set(const void * loc, int len) { if (!BN_bin2bn(reinterpret_cast<const unsigned char *>(loc), len, m_bnctx->bn())) { auto e = ERR_get_error(); std::stringstream s; s << "BN_bin2bn: " << ERR_error_string(e, nullptr); throw std::runtime_error(s.str()); } } int Bignum::len_2sc() const { int w = width(); int bitw = (w+7)&~7; if (!is_negative()) { return w == bitw ? bitw/8+1 : bitw/8; // will pad with 0 byte if the msb is set } if (w < bitw) return bitw/8; // msb is set, if any other bits are set, will add a byte when converted to 2s complement for (int i = 0; i < w-1; i++) { if (is_bit_set(i)) return bitw/8+1; } return bitw/8; } void Bignum::get_2sc(void * inloc, int len) const { int w = width(); int bitw = (w+7)&~7; uint8_t* loc = static_cast<uint8_t*>(inloc); if (len <= 0) return; if (!is_negative()) { if (w == bitw) // msb is set, pad with 0 { *loc = '\x00'; loc++; len--; } get(loc, len); return; } /* 128 0000 0000 1000 0000 - 00 80 127 0111 1111 - 7f -1 1111 1111 - ff -127 1000 0001 - 81 -128 1000 0000 - 80 -129 1111 1111 0111 1111 - ff 7f */ Bignum bn(1); bn <<= bitw; if (w == bitw) // if any other bits are on, add an additional byte, otherwise, this is the boundary value { for (int i = 0; i < w-1; i++) { if (is_bit_set(i)) { bn <<= 8; break; } } } bn += *this; // subtract the absolute value bn.get(loc, len); } void Bignum::set_2sc(const void * loc, int len) { if (len <= 0) return; bool neg = (*(uint8_t*)loc & 0x80) == 0x80 ? true : false; // check if msb is on set(loc, len); // sets as a positive number if (!neg) return; int w = width(); clear_bit(w-1); // clear the msb Bignum bn(1); // form the number with msb set bn <<= w-1; *this -= bn; // i.e. 10000001 = 00000001 - 10000000 }
20.614634
113
0.638508
stablecc
da06759d52886e8a3a347a2d69bc62b1c0c27bd3
657
cpp
C++
Raven.CppClient/ConflictSolver.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient/ConflictSolver.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient/ConflictSolver.cpp
maximburyak/ravendb-cpp-client
ab284d00bc659e8438c829f1b4a39aa78c31fa88
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
#include "stdafx.h" #include "ConflictSolver.h" #include "json_utils.h" namespace ravendb::client::serverwide { void to_json(nlohmann::json& j, const ConflictSolver& cs) { using ravendb::client::impl::utils::json_utils::set_val_to_json; set_val_to_json(j, "ResolveByCollection", cs.resolve_by_collection); set_val_to_json(j, "ResolveToLatest", cs.resolve_to_latest); } void from_json(const nlohmann::json& j, ConflictSolver& cs) { using ravendb::client::impl::utils::json_utils::get_val_from_json; get_val_from_json(j, "ResolveByCollection", cs.resolve_by_collection); get_val_from_json(j, "ResolveToLatest", cs.resolve_to_latest); } }
29.863636
72
0.767123
maximburyak
da15175ead432a169cc30b1e65f514ecb19d4f07
1,516
cpp
C++
Graphs/FloydWarshall.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
687
2015-02-23T17:31:00.000Z
2022-03-27T02:57:23.000Z
Graphs/FloydWarshall.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
9
2018-08-27T06:41:24.000Z
2020-12-17T13:39:07.000Z
Graphs/FloydWarshall.cpp
mayukhsen1301/algos
60db47ad9e7dc28271c1ce32ca705a771e682cda
[ "MIT" ]
253
2015-03-16T00:42:18.000Z
2022-03-23T06:01:36.000Z
/************************************************************************************** Floyd-Warshall algorithm finding shortest distance between all pairs of vertices in graph. Works in O(N^3) Based on problem 95 from informatics.mccme.ru http://informatics.mccme.ru/mod/statements/view.php?id=218#1 **************************************************************************************/ #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <cassert> #include <utility> #include <iomanip> using namespace std; const int MAXN = 55; const int INF = (int) 1e9; int n; int s, t; int d[MAXN][MAXN]; int main() { //assert(freopen("input.txt","r",stdin)); //assert(freopen("output.txt","w",stdout)); scanf("%d %d %d", &n, &s, &t); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { scanf("%d", &d[i][j]); if (d[i][j] == -1) d[i][j] = INF; } for (int k = 1; k <= n; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j]; if (d[s][t] == INF) printf("-1\n"); else printf("%d\n", d[s][t]); return 0; }
24.063492
88
0.435356
mayukhsen1301
da1964b39b65de793fa7b7f9e46652c840abb7e0
3,560
cpp
C++
riscv-sim/src/RISCVSTypeInstruction.cpp
tomli380576/riscv-console
a0129af4e41ecdde752f40c7b239c9bd98c1e049
[ "BSD-3-Clause" ]
9
2021-01-12T13:18:26.000Z
2022-03-10T20:20:45.000Z
riscv-sim/src/RISCVSTypeInstruction.cpp
helloparthshah/riscv-console
5b20edc4f54c8edf2f2f4e6769e2f02676eaf994
[ "BSD-3-Clause" ]
16
2021-01-17T04:17:21.000Z
2021-11-12T17:46:54.000Z
riscv-sim/src/RISCVSTypeInstruction.cpp
helloparthshah/riscv-console
5b20edc4f54c8edf2f2f4e6769e2f02676eaf994
[ "BSD-3-Clause" ]
21
2021-01-13T00:50:13.000Z
2022-03-14T21:30:53.000Z
#include "RISCVSTypeInstruction.h" class CRISCVSBInstruction : public CRISCVSTypeInstruction{ public: CRISCVSBInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CRISCVSTypeInstruction(addr,raw, pc, regs, mem){ }; bool Execute(){ DMemory->StoreUINT8(DSource1->load() + DOffset,DSource2->load()); DProgramCounter->fetch_add(DInstructionAlignment); return true; }; std::string ToString() const{ return CRISCVSTypeInstruction::ToString().replace(0,2,"sb"); }; }; class CRISCVSHInstruction : public CRISCVSTypeInstruction{ public: CRISCVSHInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CRISCVSTypeInstruction(addr,raw, pc, regs, mem){ }; bool Execute(){ DMemory->StoreUINT16(DSource1->load() + DOffset,DSource2->load()); DProgramCounter->fetch_add(DInstructionAlignment); return true; }; std::string ToString() const{ return CRISCVSTypeInstruction::ToString().replace(0,2,"sh"); }; }; class CRISCVSWInstruction : public CRISCVSTypeInstruction{ public: CRISCVSWInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CRISCVSTypeInstruction(addr,raw, pc, regs, mem){ }; bool Execute(){ DMemory->StoreUINT32(DSource1->load() + DOffset,DSource2->load()); DProgramCounter->fetch_add(DInstructionAlignment); return true; }; std::string ToString() const{ return CRISCVSTypeInstruction::ToString().replace(0,2,"sw"); }; }; CRISCVSTypeInstruction::CRISCVSTypeInstruction(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem) : CInstruction(addr,raw){ SRISCVSType *Encoded = (SRISCVSType *)&raw; DProgramCounter = pc; DSource1 = regs[Encoded->rs1]; DSource2 = regs[Encoded->rs2]; DMemory = mem; DOffset = (uint32_t(Encoded->imm11_5)<<5) | Encoded->imm4_0; DOffset |= DOffset & 0x800 ? 0xFFFFF000 : 0; } std::string CRISCVSTypeInstruction::ToString() const{ SRISCVSType *Encoded = (SRISCVSType *)&DRawInstruction; return std::string(" ") + RegisterName(Encoded->rs2) + "," + std::to_string(DOffset) + "(" + RegisterName(Encoded->rs1) + ")"; } std::shared_ptr< CRISCVCPU::CInstruction > CRISCVSTypeInstruction::DecodeSType(uint32_t addr, uint32_t raw, std::shared_ptr< CHardwareRegister< uint32_t > > pc, std::vector< std::shared_ptr< CHardwareRegister< uint32_t > > > &regs, std::shared_ptr< CMemoryDevice > mem){ SRISCVSType *Encoded = (SRISCVSType *)&raw; switch(Encoded->funct3){ case 0x0: return std::make_shared<CRISCVSBInstruction>(addr,raw,pc,regs,mem); case 0x1: return std::make_shared<CRISCVSHInstruction>(addr,raw,pc,regs,mem); case 0x2: return std::make_shared<CRISCVSWInstruction>(addr,raw,pc,regs,mem); default: return nullptr; } }
44.5
270
0.665449
tomli380576
da19a3b2024a92ac77b016b91b425d389397fbdb
2,689
cpp
C++
test/tstKokkosToolsDistributedAnnotations.cpp
dalg24/ArborX
d298c924ce93902a285168de5dc5003e4d761627
[ "BSD-3-Clause" ]
null
null
null
test/tstKokkosToolsDistributedAnnotations.cpp
dalg24/ArborX
d298c924ce93902a285168de5dc5003e4d761627
[ "BSD-3-Clause" ]
null
null
null
test/tstKokkosToolsDistributedAnnotations.cpp
dalg24/ArborX
d298c924ce93902a285168de5dc5003e4d761627
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Copyright (c) 2012-2020 by the ArborX authors * * All rights reserved. * * * * This file is part of the ArborX library. ArborX is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #include "ArborX_EnableDeviceTypes.hpp" // ARBORX_DEVICE_TYPES #include <ArborX_DistributedSearchTree.hpp> #include <boost/test/unit_test.hpp> #include <string> #include "Search_UnitTestHelpers.hpp" #if (KOKKOS_VERSION >= 30200) // callback registriation from within the program // was added in Kokkkos v3.2 BOOST_AUTO_TEST_SUITE(KokkosToolsDistributedAnnotations) namespace tt = boost::test_tools; bool isPrefixedWith(std::string const &s, std::string const &prefix) { return s.find(prefix) == 0; } BOOST_AUTO_TEST_CASE(is_prefixed_with) { BOOST_TEST(isPrefixedWith("ArborX::Whatever", "ArborX")); BOOST_TEST(!isPrefixedWith("Nope", "ArborX")); BOOST_TEST(!isPrefixedWith("Nope::ArborX", "ArborX")); } BOOST_AUTO_TEST_CASE_TEMPLATE(regions_prefixed, DeviceType, ARBORX_DEVICE_TYPES) { Kokkos::Tools::Experimental::set_push_region_callback([](char const *label) { std::cout << label << '\n'; BOOST_TEST((isPrefixedWith(label, "ArborX::") || isPrefixedWith(label, "Kokkos::"))); }); // DistributedSearchTree::DistriibutedSearchTree { // empty auto tree = makeDistributedSearchTree<DeviceType>(MPI_COMM_WORLD, {}); } // DistributedSearchTree::query auto tree = makeDistributedSearchTree<DeviceType>( MPI_COMM_WORLD, { {{{0, 0, 0}}, {{1, 1, 1}}}, {{{0, 0, 0}}, {{1, 1, 1}}}, }); // spatial predicates query(tree, makeIntersectsBoxQueries<DeviceType>({ {{{0, 0, 0}}, {{1, 1, 1}}}, {{{0, 0, 0}}, {{1, 1, 1}}}, })); // nearest predicates query(tree, makeNearestQueries<DeviceType>({ {{{0, 0, 0}}, 1}, {{{0, 0, 0}}, 2}, })); Kokkos::Tools::Experimental::set_push_region_callback(nullptr); } BOOST_AUTO_TEST_SUITE_END() #endif
33.6125
80
0.518408
dalg24
da1abc7efe31b4d8f3ca42ca3161429bbd16e6de
5,890
cpp
C++
swig/share/c++/examples/testsort.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
4
2021-01-23T14:36:34.000Z
2021-06-07T10:02:28.000Z
swig/share/c++/examples/testsort.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
1
2019-08-04T19:15:56.000Z
2019-08-04T19:15:56.000Z
swig/share/c++/examples/testsort.cpp
rdmenezes/exodusdb
f732e366b74ff4697890ec0682bc3697b8cb0bfb
[ "MIT" ]
1
2022-01-29T22:41:01.000Z
2022-01-29T22:41:01.000Z
#include <exodus/program.h> //for the sake of multivalue gurus new to exodus programming this is written //with multivalue-mimicking "everything is a global function" syntax //instead of exodus's OO-style syntax "xxx.yyy().zzz()" var filename="myclients"; programinit() function main() { if (not connect()) abort("Cannot connect to database. Please check configuration or run configexodus."); var dictfilename="dict_"^ filename; //leave the test data files around for playing with var cleanup=false; if (cleanup) { deletefile(filename); deletefile(dictfilename); } printl("\nOpen or create test file ", filename); var file; if (not open(filename, file)) { createfile(filename); if (not open(filename, file)) abort("Cannot open "^filename); } printl("\nOpen or create the test files dictionary ", dictfilename); var dictfile; if (not open(dictfilename, dictfile)) { createfile(dictfilename); if (not open(dictfilename, dictfile)) abort("Cannot open dictionary "^ dictfilename); } printl("\nPrepare some dictionary records"); var dictrecs = ""; dictrecs = "CLIENT_CODE |F|0|Code |||| ||L|8"; dictrecs ^= FM ^ "CLIENT_NAME |F|1|Name |||| ||T|15"; dictrecs ^= FM ^ "CLIENT_TYPE |F|2|Type |||| ||L|5"; dictrecs ^= FM ^ "DATE_CREATED|F|3|Date ||||D4 ||L|12"; dictrecs ^= FM ^ "TIME_CREATED|F|4|Time ||||MTH ||L|12"; dictrecs ^= FM ^ "BALANCE |F|5|Balance ||||MD20P ||R|10"; dictrecs ^= FM ^ "TIMESTAMP |F|6|Timestamp||||[DATETIME]||L|12"; dictrecs ^= FM ^ "@CRT |G| |CLIENT_CODE CLIENT_NAME CLIENT_TYPE BALANCE DATE_CREATED TIME_CREATED TIMESTAMP"; printl("\nWrite the dictionary records to the dictionary"); var nrecs=dcount(dictrecs, FM); for (var recn = 1; recn <= nrecs; recn++) { var dictrec=extract(dictrecs, recn); var key=field(dictrec, "|", 1); var rec=field(dictrec, "|", 2, 9999); printl(key, ": ", rec); key=trim(key); rec=trim(rec); rec=swap(rec, " |", "|"); rec=convert(rec, "|", FM); write(rec, dictfile, key); //check we can read the record back var rec2; dictfile.outputl("dictfile"); //key.outputl("key"); if (read(rec2,dictfile, key)) { if (rec2 ne rec) printl("record differs?!"); } else printl("Cant read ", key, " back"); } var rec; if (not read(rec,dictfile,"BALANCE")) printl("Cant read BALANCE record from dictionary"); printl("\nClear the client file"); clearfile(filename); printl("\nPrepare some data records in a readable format"); var recs = ""; recs ^= FM ^ "SB001|Client AAA |A |15070|76539|1000.00|15070.76539"; recs ^= FM ^ "JB002|Client BBB |B |15000|50539|200.00|15000.50539"; recs ^= FM ^ "JB001|Client CCC |B |15010|60539|2000.00|15010.60539"; recs ^= FM ^ "SB1 |Client SB1 |1 | | | | "; recs ^= FM ^ "JB2 |Client JB2 |2 |14000|10539|0 |14000.10539"; recs ^= FM ^ "JB10 |Client JB10|10|14010|10539|2000.00|14010.10539"; splicer(recs, 1, 1, ""); printl("\nWrite the data records to the data file"); nrecs=dcount(recs, FM); for (var recn = 1; recn <= nrecs; recn++) { var rec=extract(recs, recn); var key=field(rec, "|", 1); rec=field(rec, "|", 2, 9999); printl(key, ": ", rec); while (index(rec, " |")) swapper(rec, " |", "|"); write(trimb(convert(rec, "|", FM)), file, trim(key)); } var prefix="SELECT "^ filename; gosub sortselect(file, prefix^ " BY CLIENT_CODE"); gosub sortselect(file, prefix^ " BY BALANCE BY CLIENT_CODE"); gosub sortselect(file, prefix^ " BY TIMESTAMP"); gosub sortselect(file, prefix^ " WITH CLIENT_TYPE 'B' BY BALANCE"); var cmd="list "^ filename^ " id-supp"; printl("\nList the file using ", quote(cmd)); osshell(cmd); cmd="list "^ dictfilename; printl("\nList the dict using ", quote(cmd)); osshell(cmd); if (cleanup) { printl("\nCleaning up. Delete the files"); deletefile(file); deletefile(dictfile); } printl("\nJust type 'list' to see the syntax of list"); printl("or list dict_"^ filename^ " to see the dictionary"); printl("Type edic cli/src/testsort to see or edit/recompile this program."); return 0; } subroutine sortselect(in file, in sortselectcmd) { printl("\nSSELECT the data - ", sortselectcmd); if (!select(sortselectcmd)) { printl("Cannot sselect"); return; } printl("Read the data"); var record; var key; //could also use the readnextrecord() function here // if we had used the new selectrecord() function above while (readnext(key)) { if (not read(record, file, key)) { printl(key, " missing from file"); continue; } print(key, ": "); printl(convert(record, FM, "|")); } } programexit()
33.657143
124
0.509847
rdmenezes
da25843555203655458f0226be20436cd630a792
32,935
hpp
C++
include/Crafterra/Terrain/FieldMap.hpp
AsPJT/CrafterraProterozoic
d0531d2052b1bb5c10b6763f74034e6e3c678d1f
[ "CC0-1.0" ]
null
null
null
include/Crafterra/Terrain/FieldMap.hpp
AsPJT/CrafterraProterozoic
d0531d2052b1bb5c10b6763f74034e6e3c678d1f
[ "CC0-1.0" ]
null
null
null
include/Crafterra/Terrain/FieldMap.hpp
AsPJT/CrafterraProterozoic
d0531d2052b1bb5c10b6763f74034e6e3c678d1f
[ "CC0-1.0" ]
null
null
null
/*########################################################################################## Crafterra Library 🌏 [Planning and Production] 2017-2022 Kasugaccho 2018-2022 As Project [Contact Us] [email protected] https://github.com/AsPJT/Crafterra [License] Distributed under the CC0 1.0. https://creativecommons.org/publicdomain/zero/1.0/ ##########################################################################################*/ #ifndef INCLUDED_CRAFTERRA_LIBRARY_CRAFTERRA_TERRAIN_FIELD_MAP_HPP #define INCLUDED_CRAFTERRA_LIBRARY_CRAFTERRA_TERRAIN_FIELD_MAP_HPP #include <Crafterra/Terrain/TerrainInformation.hpp> #include <AsLib2/DataType/ArrayDataType.hpp> #include <Crafterra/Terrain/MapChip.hpp> #include <AsLib2/DataType/PrimitiveDataType.hpp> #include <Crafterra/DataType/CrafterraPrimitiveDataType.hpp> #include <memory> #include <Crafterra/Macro/New.hpp> // CRAFTERRA_NEW #include <Crafterra/Terrain/TileConnection.hpp> // パーリンノイズ #include <Crafterra/TerrainGeneration/PerlinNoise2D.hpp> // パーリンノイズをフィールドマップ上に生成 #include <Crafterra/TerrainGeneration/TerrainPerlinNoise.hpp> namespace Crafterra { unsigned int getDxColor(const int r_, const int g_, const int b_) { return (r_ * 256 + g_) * 256 + b_; } class XorShift32 { private: ::As::Uint32 seed; public: ::As::Uint32 getRand() { seed ^= seed << 13; seed ^= seed >> 17; seed ^= seed << 5; return seed; } double getRand2() { return double(getRand() - 1) / 4294967295.0; } bool getProbability(const double probability_) { return (probability_ > getRand2()); } As::Int32 getProbabilityDivision(const double probability_, const As::Int32 division_) { if (probability_ <= getRand2() || division_ <= 0) return -1; return As::Int32(getRand2() / probability_ * double(division_)); } void setSeed(const ::As::Uint32 seed_) { seed = seed_; } XorShift32(const ::As::Uint32 seed_) : seed(seed_) {} }; class Terrain { // 暫定的なマップデータ using MapMat = ::As::UniquePtrMatrix<::Crafterra::TerrainInformation>; using ObjectMapMat = ::As::UniquePtrMatrix4D<TerrainObject>; using DrawMapMat = ::As::UniquePtrMatrix<DrawMapChip>; using shape_t = ElevationUint; public: // 描画マップの描画範囲を作成 void setDrawRange(DrawMapMat& draw_map_matrix) const { // 崖上のバイオームオートタイルを調べる #ifdef _OPENMP #pragma omp parallel for for (::As::Int64 col{}; col < ::As::Int64(draw_map_matrix.getWidth()); ++col) #else for (::As::IndexUint col{}; col < draw_map_matrix.getWidth(); ++col) #endif for (::As::IndexUint row{}; row < draw_map_matrix.getDepth(); ++row) for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { DrawMapChipUnit& draw_map = draw_map_matrix[row][col].getTile(layer); draw_map.setIsBiomeCliffTop(isBiomeCliff(draw_map.getBiomeAutoTile(), draw_map)); } } // 描画マップのオートタイルの接続を計算する void setDrawAutoTileConnection(DrawMapMat& draw_map_matrix) const { // 崖のオートタイルを計算 for (::As::IndexUint col{ 1 }; col < draw_map_matrix.getWidth() - 1; ++col) for (::As::IndexUint row{}; row < draw_map_matrix.getDepth() - 1; ++row) for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { DrawMapChipUnit& draw_map_tile = draw_map_matrix[row][col].getTile(layer); if (draw_map_tile.getTerrainObject() != TerrainObject::cliff) continue; // 崖じゃなかったら返す bool is_left = true; bool is_right = true; bool is_down = true; for (::As::IndexUint layer2 = 0; layer2 < draw_map_layer_max; ++layer2) { const DrawMapChipUnit& left_tile = draw_map_matrix[row][col - 1].cgetTile(layer2); const DrawMapChipUnit& right_tile = draw_map_matrix[row][col + 1].cgetTile(layer2); const DrawMapChipUnit& down_tile = draw_map_matrix[row + 1][col].cgetTile(layer2); if (is_left) is_left = (left_tile.getIsCliff() || ((!left_tile.getIsCliff()) && draw_map_tile.getElevation() < left_tile.getElevation())); if (is_right) is_right = (right_tile.getIsCliff() || ((!right_tile.getIsCliff()) && draw_map_tile.getElevation() < right_tile.getElevation())); if (is_down) is_down = (down_tile.getIsCliff()); } draw_map_tile.setCliff( getHomogeneousConnectionCliff( is_left , is_right , is_down ) ); } for (::As::IndexUint col{ 1 }; col < draw_map_matrix.getWidth() - 1; ++col) for (::As::IndexUint row{ 1 }; row < draw_map_matrix.getDepth() - 1; ++row) { for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { DrawMapChipUnit& draw_map_tile = draw_map_matrix[row][col].getTile(layer); if (draw_map_tile.getIsCliff()) continue; bool is_cliff_top_up = false; bool is_cliff_top_left = false; bool is_cliff_top_right = false; bool is_cliff_top_down = false; bool is_cliff_top_upper_left = false; bool is_cliff_top_upper_right = false; bool is_cliff_top_lower_left = false; bool is_cliff_top_lower_right = false; bool is_biome_auto_tile_up = false; bool is_biome_auto_tile_left = false; bool is_biome_auto_tile_right = false; bool is_biome_auto_tile_down = false; bool is_biome_auto_tile_upper_left = false; bool is_biome_auto_tile_upper_right = false; bool is_biome_auto_tile_lower_left = false; bool is_biome_auto_tile_lower_right = false; bool is_auto_tile_up = false; bool is_auto_tile_left = false; bool is_auto_tile_right = false; bool is_auto_tile_down = false; bool is_auto_tile_upper_left = false; bool is_auto_tile_upper_right = false; bool is_auto_tile_lower_left = false; bool is_auto_tile_lower_right = false; const ElevationUint center_elevation = draw_map_matrix[row][col].getTile(layer).getElevation(); for (::As::IndexUint layer2 = 0; layer2 < draw_map_layer_max; ++layer2) { const ElevationUint up_elevation = draw_map_matrix[row - 1][col].getTile(layer2).getElevation(); const ElevationUint left_elevation = draw_map_matrix[row][col - 1].getTile(layer2).getElevation(); const ElevationUint right_elevation = draw_map_matrix[row][col + 1].getTile(layer2).getElevation(); const ElevationUint down_elevation = draw_map_matrix[row + 1][col].getTile(layer2).getElevation(); const ElevationUint upper_left_elevation = draw_map_matrix[row - 1][col - 1].getTile(layer2).getElevation(); const ElevationUint upper_right_elevation = draw_map_matrix[row - 1][col + 1].getTile(layer2).getElevation(); const ElevationUint lower_left_elevation = draw_map_matrix[row + 1][col - 1].getTile(layer2).getElevation(); const ElevationUint lower_right_elevation = draw_map_matrix[row + 1][col + 1].getTile(layer2).getElevation(); if (!is_cliff_top_up) is_cliff_top_up = (center_elevation == up_elevation); if (!is_cliff_top_left) is_cliff_top_left = (center_elevation == left_elevation); if (!is_cliff_top_right) is_cliff_top_right = (center_elevation == right_elevation); if (!is_cliff_top_down) is_cliff_top_down = (center_elevation == down_elevation); if (!is_cliff_top_upper_left) is_cliff_top_upper_left = (center_elevation == upper_left_elevation); if (!is_cliff_top_upper_right) is_cliff_top_upper_right = (center_elevation == upper_right_elevation); if (!is_cliff_top_lower_left) is_cliff_top_lower_left = (center_elevation == lower_left_elevation); if (!is_cliff_top_lower_right) is_cliff_top_lower_right = (center_elevation == lower_right_elevation); if (!is_biome_auto_tile_up) is_biome_auto_tile_up = draw_map_matrix[row - 1][col].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row - 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_left) is_biome_auto_tile_left = draw_map_matrix[row][col - 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col - 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_right) is_biome_auto_tile_right = draw_map_matrix[row][col + 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col + 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_down) is_biome_auto_tile_down = draw_map_matrix[row + 1][col].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row + 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_upper_left) is_biome_auto_tile_upper_left = draw_map_matrix[row - 1][col - 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row - 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col - 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_upper_right) is_biome_auto_tile_upper_right = draw_map_matrix[row - 1][col + 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row - 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col + 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_lower_left) is_biome_auto_tile_lower_left = draw_map_matrix[row + 1][col - 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row + 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col - 1].getTile(layer2).getIsCliff()); if (!is_biome_auto_tile_lower_right) is_biome_auto_tile_lower_right = draw_map_matrix[row + 1][col + 1].getTile(layer2).getDrawBiome() == draw_map_tile.getDrawBiome() && draw_map_matrix[row + 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col + 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_up) is_auto_tile_up = draw_map_matrix[row - 1][col].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row - 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col].getTile(layer2).getIsCliff()); if (!is_auto_tile_left) is_auto_tile_left = draw_map_matrix[row][col - 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col - 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_right) is_auto_tile_right = draw_map_matrix[row][col + 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row][col + 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_down) is_auto_tile_down = draw_map_matrix[row + 1][col].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row + 1][col].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col].getTile(layer2).getIsCliff()); if (!is_auto_tile_upper_left) is_auto_tile_upper_left = draw_map_matrix[row - 1][col - 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row - 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col - 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_upper_right) is_auto_tile_upper_right = draw_map_matrix[row - 1][col + 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row - 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row - 1][col + 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_lower_left) is_auto_tile_lower_left = draw_map_matrix[row + 1][col - 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row + 1][col - 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col - 1].getTile(layer2).getIsCliff()); if (!is_auto_tile_lower_right) is_auto_tile_lower_right = draw_map_matrix[row + 1][col + 1].getTile(layer2).getTerrainObject() == draw_map_tile.getTerrainObject() && draw_map_matrix[row + 1][col + 1].getTile(layer2).getElevation() == draw_map_tile.getElevation() && (!draw_map_matrix[row + 1][col + 1].getTile(layer2).getIsCliff()); } // 崖上のオートタイルを計算 ( 一部バグがあり、未完成 ) draw_map_matrix[row][col].getTile(layer).setCliffTop( getHomogeneousConnection( is_cliff_top_up , is_cliff_top_left , is_cliff_top_right , is_cliff_top_down , is_cliff_top_upper_left , is_cliff_top_upper_right , is_cliff_top_lower_left , is_cliff_top_lower_right ) ); // ウディタ規格オートタイルの計算 // 同質接続の条件:同じバイオーム&同じ標高&崖ではない draw_map_tile.setBiomeAutoTile( getHomogeneousConnectionAutoTile( is_biome_auto_tile_up , is_biome_auto_tile_left , is_biome_auto_tile_right , is_biome_auto_tile_down , is_biome_auto_tile_upper_left , is_biome_auto_tile_upper_right , is_biome_auto_tile_lower_left , is_biome_auto_tile_lower_right ) ); // ウディタ規格オートタイルの計算 // 同質接続の条件:同じバイオーム&同じ標高&崖ではない draw_map_tile.setAutoTile( getHomogeneousConnectionAutoTile( is_auto_tile_up , is_auto_tile_left , is_auto_tile_right , is_auto_tile_down , is_auto_tile_upper_left , is_auto_tile_upper_right , is_auto_tile_lower_left , is_auto_tile_lower_right ) ); } } } // 地形から描画マップを作成 void setDrawMapFromTerrain(ObjectMapMat& terrain_object_matrix, const MapMat& terrain_information_matrix, DrawMapMat& draw_map_matrix, const ::As::IndexUint start_x_, const ::As::IndexUint start_z_, const ::As::IndexUint width_, const ::As::IndexUint depth_) const { for (::As::IndexUint row{ start_z_ }, mat_index{}; row < depth_; ++row) { for (::As::IndexUint col{ start_x_ }; col < width_; ++col, ++mat_index) { const ::As::IndexUint index_zx = terrain_object_matrix.getIndexMulZX(mat_index); const TerrainInformation& terrain_info = terrain_information_matrix[row][col]; DrawMapChip& draw_map = draw_map_matrix[row][col]; draw_map.setTileNum(0); draw_map.clearTile(); for (::As::Int64 layer{}; layer < ::As::Int64(draw_map_layer_max); ++layer) draw_map.getTile(::As::IndexUint(layer)).setElevation(0); // 初期化 for (::As::IndexUint row3{ ::As::IndexUint(row) }, terrain_obj_index{}; terrain_obj_index < terrain_object_matrix.getHeight(); --row3, ++terrain_obj_index) { const ::As::IndexUint index_zxy = terrain_object_matrix.getIndexMulZXY(index_zx, terrain_obj_index); for (::As::IndexUint terrain_obj_layer_index = 0; terrain_obj_layer_index < terrain_object_matrix.getLayer(); ++terrain_obj_layer_index) { const TerrainObject terrain_obj = terrain_object_matrix.getValueZXYL(index_zxy + ::As::IndexUint(terrain_obj_layer_index)); if (terrain_obj != TerrainObject::empty) { DrawMapChip& draw_map_2 = draw_map_matrix[row3][col]; draw_map_2.setNextTile(); draw_map_2.setIsCliff(terrain_obj == TerrainObject::cliff); // どこが崖になっているか調べる draw_map_2.setIsCliffTop(terrain_obj_index == ::As::IndexUint(terrain_info.getBlockElevation())); // どこが崖上になっているか調べる draw_map_2.setTerrainObject(terrain_obj); // ブロックを格納 draw_map_2.setX(col); draw_map_2.setY(terrain_obj_index); draw_map_2.setZ(row); if (ElevationUint(terrain_obj_index) <= terrain_info.getBlockElevation()) { if (draw_map_2.getTile().getElevation() < ElevationUint(terrain_obj_index)) draw_map_2.setElevation(ElevationUint(terrain_obj_index)); } } } if (row3 == 0) break; } const As::Int32 row2 = As::Int32(row) - As::Int32(terrain_info.getBlockElevation()); if (row2 >= 0) { for (::As::IndexUint layer = 0; layer < draw_map_layer_max; ++layer) { draw_map_matrix[row2][col].getTile(layer).setDrawBiome(terrain_info.getBiome()); } } } } } // フィールドマップの下半分の地形が上半分へ移動する void moveUp(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_height_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(field_height_half_); ++row) for (::As::Int32 col{}; col < ::As::Int32(terrain_information_matrix.getWidth()); ++col) { #else for (::As::IndexUint row{}; row < field_height_half_; ++row) for (::As::IndexUint col{}; col < terrain_information_matrix.getWidth(); ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row + field_height_half_, col); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row][col]; const TerrainInformation& field_map_before = terrain_information_matrix[row + field_height_half_][col]; field_map_after = field_map_before; } } // フィールドマップの上半分の地形が下半分へ移動する void moveDown(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_height_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(field_height_half_); ++row) for (::As::Int32 col{}; col < ::As::Int32(terrain_information_matrix.getWidth()); ++col) { #else for (::As::IndexUint row{}; row < field_height_half_; ++row) for (::As::IndexUint col{}; col < terrain_information_matrix.getWidth(); ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row + field_height_half_, col); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row + field_height_half_][col]; const TerrainInformation& field_map_before = terrain_information_matrix[row][col]; field_map_after = field_map_before; } } // フィールドマップの右半分の地形が左半分へ移動する void moveLeft(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_width_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(terrain_information_matrix.getDepth()); ++row) for (::As::Int32 col{}; col < ::As::Int32(field_width_half_); ++col) { #else for (::As::IndexUint row{}; row < terrain_information_matrix.getDepth(); ++row) for (::As::IndexUint col{}; col < field_width_half_; ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col + field_width_half_); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row][col]; const TerrainInformation& field_map_before = terrain_information_matrix[row][col + field_width_half_]; field_map_after = field_map_before; } } // フィールドマップの左半分の地形が右半分へ移動する void moveRight(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, const ::As::IndexUint field_width_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(terrain_information_matrix.getDepth()); ++row) for (::As::Int32 col{}; col < ::As::Int32(field_width_half_); ++col) { #else for (::As::IndexUint row{}; row < terrain_information_matrix.getDepth(); ++row) for (::As::IndexUint col{}; col < field_width_half_; ++col) { #endif const ::As::IndexUint before_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col); const ::As::IndexUint after_bo_index_2d = terrain_object_matrix.getIndexMulZX(row, col + field_width_half_); for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { const TerrainObject& obj = terrain_object_matrix.getValueMulZXYL(before_bo_index_2d, i, layer); terrain_object_matrix.setValueMulZXYL(obj, after_bo_index_2d, i, layer); } TerrainInformation& field_map_after = terrain_information_matrix[row][col + field_width_half_]; const TerrainInformation& field_map_before = terrain_information_matrix[row][col]; field_map_after = field_map_before; } } // フィールドマップの左半分の地形が右半分へ移動する void moveRightDraw(DrawMapMat& draw_map_matrix, const ::As::IndexUint field_width_half_) const { #ifdef _OPENMP #pragma omp parallel for for (::As::Int32 row{}; row < ::As::Int32(draw_map_matrix.getDepth()); ++row) for (::As::Int32 col{}; col < ::As::Int32(field_width_half_); ++col) { #else for (::As::IndexUint row{}; row < draw_map_matrix.getDepth(); ++row) for (::As::IndexUint col{}; col < field_width_half_; ++col) { #endif DrawMapChip& field_map_after = draw_map_matrix[row][col + field_width_half_]; const DrawMapChip& field_map_before = draw_map_matrix[row][col]; field_map_after = field_map_before; } } // 木の生成 void generationTree(ObjectMapMat& terrain_object_matrix, const ::As::IndexUint bo_index_2d, TerrainInformation& field_map) const { const ElevationUint temperature = field_map.getTemperature(); const ElevationUint elevation = field_map.getElevation(); const ElevationUint block_elevation = elevation / 2; const ElevationUint amount_of_rainfall = field_map.getAmountOfRainfall(); const ::As::Uint32 flower_num = 9; const double flower_probability = 0.02; const double default_max = (flower_probability * flower_num); double coniferous_tree_generation_probability = 0.0; // 針葉樹の生成確率 double green_broadleaf_tree_generation_probability = 0.0; // 緑色の広葉樹の生成確率 double yellow_green_broadleaf_tree_generation_probability = 0.0; // 黄緑色の広葉樹の生成確率 if (amount_of_rainfall >= 100 && temperature >= 20) { if (temperature < 44) { coniferous_tree_generation_probability = ((temperature - 20.0) / (44.0 - 20.0)) * 0.3; // 針葉樹の生成確率 } else if (temperature < 64) { coniferous_tree_generation_probability = (1.0 - ((temperature - 44.0) / (64.0 - 44.0))) * 0.3; // 針葉樹の生成確率 } if (temperature >= 44) { if (temperature < 72) { green_broadleaf_tree_generation_probability = ((temperature - 44.0) / (72.0 - 44.0)) * 0.1; // 緑色の広葉樹の生成確率 } else { green_broadleaf_tree_generation_probability = 0.1 + ((temperature - 72.0) / (240.0 - 72.0)) * 0.6; // 緑色の広葉樹の生成確率 } } } // 生成される確率 const double probability_of_generation = (default_max + coniferous_tree_generation_probability + green_broadleaf_tree_generation_probability + yellow_green_broadleaf_tree_generation_probability); // 生成されない確率 const double probability_of_no_generation = (1.0 - probability_of_generation); double probability = field_map.getFlower(); //if (probability == 0.0) { // field_map.setBlock(TerrainObject::red_broadleaf_tree_down, block_elevation); // テスト // return; //} //if (probability == 1.0) { // field_map.setBlock(TerrainObject::red_broadleaf_tree_up, block_elevation); // テスト // return; //} if (probability < probability_of_no_generation) return; probability -= probability_of_no_generation; ::As::IndexUint block_layer_index = 0; for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { if (TerrainObject::empty == terrain_object_matrix.getValueMulZXYL(bo_index_2d, block_elevation, layer)) { block_layer_index = layer; break; } } // 草花の生成テスト if (probability < flower_probability) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_1, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 2)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_2, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 3)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_3, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 4)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::grass_4, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 5)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_1, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 6)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_2, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 7)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_3, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < (flower_probability * 8)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::flower_4, bo_index_2d, block_elevation, block_layer_index); return; } else if (probability < default_max) { terrain_object_matrix.setValueMulZXYL(TerrainObject::cultivated_land, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::planted_carrot, bo_index_2d, block_elevation, block_layer_index + 1); return; } else if (probability < (default_max + coniferous_tree_generation_probability)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::green_coniferous_tree_down, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::green_coniferous_tree_up, bo_index_2d, block_elevation + 1, block_layer_index); return; } else if (probability < (default_max + coniferous_tree_generation_probability + green_broadleaf_tree_generation_probability)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::green_broadleaf_tree_down, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::green_broadleaf_tree_up, bo_index_2d, block_elevation + 1, block_layer_index); return; } else if (probability < (default_max + coniferous_tree_generation_probability + green_broadleaf_tree_generation_probability + yellow_green_broadleaf_tree_generation_probability)) { terrain_object_matrix.setValueMulZXYL(TerrainObject::yellow_green_broadleaf_tree_down, bo_index_2d, block_elevation, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::yellow_green_broadleaf_tree_up, bo_index_2d, block_elevation + 1, block_layer_index); return; } } // フィールドマップを生成 void generation(ObjectMapMat& terrain_object_matrix, MapMat& terrain_information_matrix, TerrainPerlinNoise& terrain_noise_, const ::As::IndexUint chunk_index_x_, const ::As::IndexUint chunk_index_y_, const ::As::IndexAreaXZ& area) const { constexpr ElevationUint sea_elevation = ElevationUint(::Crafterra::getElevationOfSeaLevel()); terrain_noise_.generation(terrain_information_matrix, chunk_index_x_, chunk_index_y_, area); XorShift32 xs32(terrain_noise_.getElevationSeed()); const ::As::IndexUint end_x_ = area.start_x + area.width; const ::As::IndexUint end_y_ = area.start_z + area.depth; //バイオームの分類分け #ifdef _OPENMP #pragma omp parallel for for (::As::Int64 row{ ::As::Int64(area.start_z) }; row < ::As::Int64(end_y_); ++row) for (::As::Int64 col{ ::As::Int64(area.start_x) }; col < ::As::Int64(end_x_); ++col) { #else for (::As::IndexUint row{ area.start_z }; row < end_y_; ++row) for (::As::IndexUint col{ area.start_x }; col < end_x_; ++col) { #endif const ::As::IndexUint bo_index_2d = terrain_object_matrix.getIndexMulZX(::As::IndexUint(row), ::As::IndexUint(col)); TerrainInformation& field_map = terrain_information_matrix[::As::IndexUint(row)][::As::IndexUint(col)]; const ElevationUint elevation = field_map.getElevation(); const ElevationUint block_elevation = elevation / 2; const ElevationUint amount_of_rainfall = field_map.getAmountOfRainfall(); const ElevationUint temperature = ((field_map.getTemperature() < block_elevation) ? 0 : (field_map.getTemperature() - block_elevation)); field_map.setTemperature(temperature); // 標高がある定数値よりも少ない場合は海になる if (elevation <= sea_elevation) field_map.setBiome(TerrainBiome::sea); // 気温が低い場合はツンドラになる else if (temperature < 24) field_map.setBiome(TerrainBiome::tundra); // 降水量が少ない場合は砂漠になる else if (amount_of_rainfall < 24) field_map.setBiome(TerrainBiome::desert); else if (amount_of_rainfall < 72) { if (temperature < 128) field_map.setBiome(TerrainBiome::rock); // ステップ? else field_map.setBiome(TerrainBiome::savannah); } else if (temperature < 69) field_map.setBiome(TerrainBiome::forest); // grass else if (temperature < 96) field_map.setBiome(TerrainBiome::normal); else if (temperature < 120) field_map.setBiome(TerrainBiome::forest); else if (amount_of_rainfall < 125) field_map.setBiome(TerrainBiome::mountain); else if (temperature < 132) field_map.setBiome(TerrainBiome::mountain); else field_map.setBiome(TerrainBiome::mountain); const ::As::IndexUint block_layer_index = 0; // ブロックを初期化 for (As::IndexUint i = 0; i < terrain_object_matrix.getHeight(); ++i) { const ::As::IndexUint bo_index_3d = terrain_object_matrix.getIndexMulZXY(bo_index_2d, i); if (i < block_elevation) { terrain_object_matrix.setValueMulZXYL(TerrainObject::cliff, bo_index_3d, block_layer_index); // 崖 for (As::IndexUint layer = block_layer_index + 1; layer < terrain_object_matrix.getLayer(); ++layer) { terrain_object_matrix.setValueMulZXYL(TerrainObject::empty, bo_index_3d, layer); // から } } else for (As::IndexUint layer = 0; layer < terrain_object_matrix.getLayer(); ++layer) { terrain_object_matrix.setValueMulZXYL(TerrainObject::empty, bo_index_3d, layer); // からの場合 ( 崖上を除く ) } } terrain_object_matrix.setValueMulZXYL(TerrainObject::cliff_top, bo_index_2d, block_elevation, block_layer_index); // からだけど崖上の場合 // 海 if (field_map.getBiome() == TerrainBiome::sea) { field_map.setElevation(sea_elevation); field_map.setBlockElevation(sea_elevation / 2); for (As::IndexUint i = block_elevation; i <= sea_elevation / 2; ++i) { terrain_object_matrix.setValueMulZXYL(TerrainObject::cliff_top, bo_index_2d, i, block_layer_index); terrain_object_matrix.setValueMulZXYL(TerrainObject::sea, bo_index_2d, i, block_layer_index + 1); } } // 陸 else { field_map.setBlockElevation(block_elevation); this->generationTree(terrain_object_matrix, bo_index_2d, field_map); // 木の生成 } } } void initialGeneration(ObjectMapMat& terrain_object_matrix, MapMat& field_map_matrix_, TerrainPerlinNoise& terrain_noise_, const TerrainChunk& chunk) const { generation(terrain_object_matrix, field_map_matrix_, terrain_noise_, chunk.getX(), chunk.getZ(), ::As::IndexAreaXZ(0, 0, field_map_matrix_.getWidth(), field_map_matrix_.getDepth())); } }; } #endif //Included Crafterra Library
53.120968
343
0.717565
AsPJT
da2785de81a97e7d470bbcaa04b0d76c76b27def
216
cpp
C++
src/engine/network/NetAdr.cpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
1
2018-06-22T15:46:42.000Z
2018-06-22T15:46:42.000Z
src/engine/network/NetAdr.cpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
3
2018-05-13T14:15:53.000Z
2018-05-29T08:06:26.000Z
src/engine/network/NetAdr.cpp
BlackPhrase/V-Engine
ee9a9c63a380732dace75bcc1e398cabc444feba
[ "MIT" ]
null
null
null
#include "NetAdr.hpp" CNetAdr::CNetAdr() = default; CNetAdr::~CNetAdr() = default; bool CNetAdr::IsLocal() const { return false; // TODO }; INetAdr::Type CNetAdr::GetType() const { return INetAdr::Type::Temp; };
15.428571
38
0.680556
BlackPhrase
da2d7f858984a4d3bb09ca8e485fe1599bea7ded
3,568
cc
C++
tensorflow/contrib/lite/kernels/comparisons_test.cc
tucaiyong/tensorflow
3cc3c87f375f1bc292bd58db4928b810ac888bc6
[ "Apache-2.0" ]
14
2018-12-06T06:51:33.000Z
2021-03-23T11:29:24.000Z
tensorflow/contrib/lite/kernels/comparisons_test.cc
tucaiyong/tensorflow
3cc3c87f375f1bc292bd58db4928b810ac888bc6
[ "Apache-2.0" ]
10
2018-02-04T18:41:52.000Z
2018-05-02T09:00:46.000Z
tensorflow/contrib/lite/kernels/comparisons_test.cc
tucaiyong/tensorflow
3cc3c87f375f1bc292bd58db4928b810ac888bc6
[ "Apache-2.0" ]
4
2018-01-17T14:22:49.000Z
2018-02-27T15:06:41.000Z
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <gtest/gtest.h> #include "tensorflow/contrib/lite/interpreter.h" #include "tensorflow/contrib/lite/kernels/register.h" #include "tensorflow/contrib/lite/kernels/test_util.h" #include "tensorflow/contrib/lite/model.h" namespace tflite { namespace { using ::testing::ElementsAreArray; class LessOpModel : public SingleOpModel { public: LessOpModel(std::initializer_list<int> input1_shape, std::initializer_list<int> input2_shape, TensorType input_type) { input1_ = AddInput(input_type); input2_ = AddInput(input_type); output_ = AddOutput(TensorType_BOOL); SetBuiltinOp(BuiltinOperator_LESS, BuiltinOptions_LessOptions, CreateLessOptions(builder_).Union()); BuildInterpreter({input1_shape, input2_shape}); } int input1() { return input1_; } int input2() { return input2_; } std::vector<bool> GetOutput() { return ExtractVector<bool>(output_); } std::vector<int> GetOutputShape() { return GetTensorShape(output_); } private: int input1_; int input2_; int output_; }; TEST(ArgMaxOpTest, LessFloat) { LessOpModel model({1, 1, 1, 4}, {1, 1, 1, 4}, TensorType_FLOAT32); model.PopulateTensor<float>(model.input1(), {0.1, 0.9, 0.7, 0.3}); model.PopulateTensor<float>(model.input2(), {0.1, 0.2, 0.6, 0.5}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({false, false, false, true})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 1, 4})); } TEST(ArgMaxOpTest, LessInt) { LessOpModel model({1, 1, 1, 4}, {1, 1, 1, 4}, TensorType_INT32); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3}); model.PopulateTensor<int>(model.input2(), {1, 2, 6, 5}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({true, false, false, true})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 1, 4})); } TEST(ArgMaxOpTest, LessBroadcast) { LessOpModel model({1, 1, 1, 4}, {1, 1, 1, 1}, TensorType_INT32); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3}); model.PopulateTensor<int>(model.input2(), {7}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({true, false, false, true})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 1, 4})); } TEST(ArgMaxOpTest, LessBroadcastTwoD) { LessOpModel model({1, 1, 2, 4}, {1, 1, 1, 4}, TensorType_INT32); model.PopulateTensor<int>(model.input1(), {-1, 9, 7, 3, 2, 4, 6, 8}); model.PopulateTensor<int>(model.input2(), {7, 1, 2, 4}); model.Invoke(); EXPECT_THAT(model.GetOutput(), ElementsAreArray({true, false, false, true, true, false, false, false})); EXPECT_THAT(model.GetOutputShape(), ElementsAreArray({1, 1, 2, 4})); } } // namespace } // namespace tflite int main(int argc, char** argv) { ::tflite::LogToStderr(); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
36.040404
80
0.679933
tucaiyong
da3d9dc9ff9da2beb3fdccc4071f0cb40b44972f
1,846
cc
C++
lib/tensor/opdefs/tensor_shape.cc
cezheng/runtime
0866034bbc9bbe3ac513abf249edcaae13319909
[ "Apache-2.0" ]
2
2021-08-09T21:26:39.000Z
2021-11-17T10:57:43.000Z
lib/tensor/opdefs/tensor_shape.cc
cezheng/runtime
0866034bbc9bbe3ac513abf249edcaae13319909
[ "Apache-2.0" ]
null
null
null
lib/tensor/opdefs/tensor_shape.cc
cezheng/runtime
0866034bbc9bbe3ac513abf249edcaae13319909
[ "Apache-2.0" ]
1
2020-08-03T20:23:58.000Z
2020-08-03T20:23:58.000Z
// Copyright 2020 The TensorFlow Runtime Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //===- tensor_shape.cc ----------------------------------------------------===// // // This file implements MLIR operation functions for the tensor shape dialect. // //===----------------------------------------------------------------------===// #include "tfrt/tensor/opdefs/tensor_shape.h" #include "mlir/IR/Builders.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/StandardTypes.h" #include "mlir/IR/TypeUtilities.h" #include "tfrt/tensor/opdefs/tensor_shape.h" namespace tfrt { namespace ts { //===----------------------------------------------------------------------===// // TensorShape Dialect //===----------------------------------------------------------------------===// TensorShapeDialect::TensorShapeDialect(MLIRContext *context) : Dialect(/*name=*/"ts", context) { allowUnknownTypes(); addOperations< #define GET_OP_LIST #include "tfrt/tensor/opdefs/tensor_shape.cpp.inc" >(); } //===----------------------------------------------------------------------===// // TableGen'd op method definitions //===----------------------------------------------------------------------===// #define GET_OP_CLASSES #include "tfrt/tensor/opdefs/tensor_shape.cpp.inc" } // namespace ts } // namespace tfrt
34.185185
80
0.557421
cezheng
da4620def666b28d1fe5f0079b55004008292c2e
2,704
cpp
C++
chapter_5_meta_programming/ex_1_type_traits.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
chapter_5_meta_programming/ex_1_type_traits.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
chapter_5_meta_programming/ex_1_type_traits.cpp
joshlk/discovering_modern_cpp_peter_gottschling_exercises
ebd6a0f48d36ee85b7fac30a123038728ad9ffc2
[ "MIT" ]
null
null
null
// // Created by Josh Levy-Kramer on 02/04/2020. // #include <iostream> #include <typeinfo> // ---- remove_reference // Overload for a normal type, type reference and rvalue type reference template <typename T> struct remove_reference { using type = T; }; template <typename T> struct remove_reference<T&> { using type = T; }; template <typename T> struct remove_reference<T&&> { using type = T; }; template <typename T> struct remove_reference<T*> { using type = T; }; // ---- add_reference template <typename T> struct add_reference { using type = T&; }; template <typename T> struct add_reference<T&> { using type = T&; }; template <typename T> struct add_reference<T&&> { using type = T&; }; template <typename T> struct add_reference<T*> { using type = T&; }; int main() { // -- remove_reference // Could use `using` syntax here. Taken from cpp reference typedef int&& rval_int; typedef remove_reference<int>::type A; typedef remove_reference<int&>::type B; typedef remove_reference<int&&>::type C; typedef remove_reference<rval_int>::type D; typedef remove_reference<int*>::type E; std::cout << std::boolalpha; std::cout << "typedefs of int:" << std::endl; std::cout << "A: " << std::is_same<int,A>::value << std::endl; std::cout << "B: " << std::is_same<int,B>::value << std::endl; std::cout << "C: " << std::is_same<int,C>::value << std::endl; std::cout << "D: " << std::is_same<int,D>::value << std::endl; std::cout << "E: " << std::is_same<int,E>::value << std::endl << std::endl; // All these are executed at compile time. Will throw error at compile time if not true static_assert(std::is_same<int,A>::value, ""); static_assert(std::is_same<int,B>::value, ""); static_assert(std::is_same<int,C>::value, ""); static_assert(std::is_same<int,D>::value, ""); static_assert(std::is_same<int,E>::value, ""); //static_assert(std::is_same<int,double>::value, ""); // does not compile // -- add_reference typedef add_reference<int>::type A2; // int& typedef add_reference<int&>::type B2; // int& typedef add_reference<int&&>::type C2; // int& typedef add_reference<int*>::type D2; // int*& std::cout << std::boolalpha; std::cout << "typedefs of int&:" << std::endl; //std::cout << "A: " << typeid(tst::trans(A2)).name() << std::endl; std::cout << "A: " << std::is_same<int&,A2>::value << std::endl; std::cout << "B: " << std::is_same<int&,B2>::value << std::endl; std::cout << "C: " << std::is_same<int&,C2>::value << std::endl; std::cout << "D: " << std::is_same<int&,D2>::value << std::endl; return 0; }
29.075269
91
0.610577
joshlk
da47bb180c38a09c8d2c906289d0f5daabb813e5
1,931
hpp
C++
include/ast/ExpressionTypeNode.hpp
aviralg/tastr
184e6324de86831c1e4162112d446f537ad8f50c
[ "Apache-2.0" ]
1
2021-03-25T04:05:35.000Z
2021-03-25T04:05:35.000Z
include/ast/ExpressionTypeNode.hpp
aviralg/tastr
184e6324de86831c1e4162112d446f537ad8f50c
[ "Apache-2.0" ]
null
null
null
include/ast/ExpressionTypeNode.hpp
aviralg/tastr
184e6324de86831c1e4162112d446f537ad8f50c
[ "Apache-2.0" ]
null
null
null
#ifndef TASTR_AST_EXPRESSION_TYPE_NODE_HPP #define TASTR_AST_EXPRESSION_TYPE_NODE_HPP #include "ast/KeywordNode.hpp" #include "ast/TypeNode.hpp" namespace tastr { namespace ast { class ExpressionTypeNode final: public TypeNode { public: explicit ExpressionTypeNode(KeywordNodeUPtr keyword) : TypeNode(), keyword_(std::move(keyword)) { } ~ExpressionTypeNode() = default; ExpressionTypeNode(const ExpressionTypeNode& node) : TypeNode(node), keyword_(node.keyword_->clone()) { } ExpressionTypeNode(ExpressionTypeNode&& node) : TypeNode(std::move(node)), keyword_(std::move(node.keyword_)) { } ExpressionTypeNode& operator=(const ExpressionTypeNode& node) { if (&node == this) { return *this; } TypeNode::operator=(node); keyword_ = node.keyword_->clone(); return *this; } ExpressionTypeNode& operator=(ExpressionTypeNode&& node) { TypeNode::operator=(std::move(node)); keyword_ = std::move(node.keyword_); return *this; } void accept(tastr::visitor::ConstNodeVisitor& visitor) const override final; void accept(tastr::visitor::MutableNodeVisitor& visitor) override final; std::unique_ptr<ExpressionTypeNode> clone() const { return std::unique_ptr<ExpressionTypeNode>(this->clone_impl()); } Kind get_kind() const override final { return kind_; } const KeywordNode& get_keyword() const { return *keyword_.get(); } private: virtual ExpressionTypeNode* clone_impl() const override final { return new ExpressionTypeNode(*this); }; KeywordNodeUPtr keyword_; static const Kind kind_; }; using ExpressionTypeNodePtr = ExpressionTypeNode*; using ExpressionTypeNodeUPtr = std::unique_ptr<ExpressionTypeNode>; } // namespace ast } // namespace tastr #endif /* TASTR_AST_EXPRESSION_TYPE_NODE_HPP */
26.094595
80
0.681512
aviralg
da4fc46853af53398f362ade68d409801ac40d54
1,965
cpp
C++
mod/wrd/ast/exprs/getExpr.cpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/wrd/ast/exprs/getExpr.cpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/wrd/ast/exprs/getExpr.cpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#include "getExpr.hpp" #include "../../loader/interpreter/tverification.hpp" #include "../../loader/interpreter/verification.inl" #include "../../loader/interpreter/verifier.hpp" #include "../../frame/thread.hpp" #include "../node.inl" namespace wrd { WRD_DEF_ME(getExpr) const node& me::getFrom() const { if(!_from) return thread::get().getNowFrame(); return *_from; } const wtype& me::getEvalType() const { const node& got = _get(); if(nul(got)) return nulOf<wtype>(); return got.getEvalType(); } str me::run(const ucontainable& args) { // believe that this expression was checked to be valid. return str(_get()); } const std::string& me::getSubName() const { return _name; } /// @return nullable const narr& me::getSubArgs() const { return *_args; } node& me::_get() const { str evalMe = getFrom().isSub<expr>() ? getFrom().as<node>() : getFrom(); if(!evalMe) return WRD_E("from == null"), nulOf<node>(); WRD_DI("_name=%s", _name.c_str()); if(!_args) return evalMe->sub(_name); return evalMe->sub(_name, *_args); } WRD_VERIFY(getExpr, isRunnable, { // TODO: I have to check that the evalType has what matched to given _params. // Until then, I rather use as() func and it makes slow emmersively. if(nul(it.getEvalType())) return _srcErr(errCode::EVAL_NULL_TYPE); const node& got = it._get(); if(nul(got)) { const node& from = it.getFrom(); return _srcErr(errCode::CANT_ACCESS, from.getType().getName().c_str(), it._name.c_str()); WRD_DI("verify: getExpr: isRunnable: got=%s, it=%s", got.getType().getName().c_str(), it.getType().getName().c_str()); } }) WRD_VERIFY({ WRD_DI("verify: getExpr: visit 'from' subnodes"); verify((node&) it.getFrom()); }) }
30.230769
101
0.582697
kniz
da5877105526619ca73d5088738be3b076b79c7b
73
hh
C++
dependencies/include/pimpl_ptr.hh
Wedrew/rpclib
eff0f0c7270ca8c17d46edf5ebc4ee97e4b2444f
[ "MIT" ]
1,316
2016-07-03T10:01:37.000Z
2022-03-31T18:40:35.000Z
dependencies/include/pimpl_ptr.hh
Wedrew/rpclib
eff0f0c7270ca8c17d46edf5ebc4ee97e4b2444f
[ "MIT" ]
239
2016-06-29T07:16:26.000Z
2022-03-23T09:21:15.000Z
dependencies/include/pimpl_ptr.hh
Wedrew/rpclib
eff0f0c7270ca8c17d46edf5ebc4ee97e4b2444f
[ "MIT" ]
315
2016-08-24T13:08:20.000Z
2022-03-29T10:59:08.000Z
#ifndef PIMPL_PTR_HH_ #define PIMPL_PTR_HH_ #endif /* PIMPL_PTR_HH_ */
12.166667
26
0.767123
Wedrew
da601ca52d43594f01ab3b5b7d423f4843df7771
425
cpp
C++
dynamic/4811.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
dynamic/4811.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
dynamic/4811.cpp
SiverPineValley/algo
29c75c6b226fdb15a3b6695e763ee49d4871094e
[ "Apache-2.0" ]
null
null
null
// 알약 #include <iostream> #include <vector> using namespace std; int main(void) { int t, i, j; cin >> t; vector<vector<long long>> a(31,vector<long long> (31)); for(i = 1; i <= 30; i++) a[0][i] = 1; for(i = 1; i <= 30; i++) { for(j = 0; j <= 30 - i; j++) { if(j == 0) a[i][j] = a[i-1][1]; else a[i][j] = a[i-1][j+1] + a[i][j-1]; } } while(t) { cout << a[t][0] << "\n"; cin >> t; } return 0; }
15.178571
56
0.449412
SiverPineValley
da651f99e46e19ddd884a3bb312b7c74a2eb2cd4
427
hpp
C++
NWNXLib/API/Mac/API/IncrMerger.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/IncrMerger.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
NWNXLib/API/Mac/API/IncrMerger.hpp
Qowyn/unified
149d0b7670a9d156e64555fe0bd7715423db4c2a
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include "SorterFile.hpp" #include "unknown_sqlite_int64.hpp" namespace NWNXLib { namespace API { // Forward class declarations (defined in the source file) struct MergeEngine; struct SortSubtask; struct IncrMerger { SortSubtask* pTask; MergeEngine* pMerger; sqlite_int64 iStartOff; int32_t mxSz; int32_t bEof; int32_t bUseThread; SorterFile aFile[2]; }; } }
14.233333
58
0.721311
Qowyn
da6a4b71e2d7c27b5f5705ae22199d15008bb1d6
4,108
hpp
C++
Misc/APE Scripts/ShepardTone.hpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/APE Scripts/ShepardTone.hpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/APE Scripts/ShepardTone.hpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#include "../../../../RS-MET/Misc/APE Scripts/rapt_for_ape.cpp" // relative path from "Audio Programming Environment/includes" #include <effect.h> // or maybe we should use generator.h? //================================================================================================= // The core DSP object template<class T> class rsShepardToneGenerator { public: //----------------------------------------------------------------------------------------------- // \name Setup /** Sets the sample rate at which this object runs. This determines the time increment for our phasor */ inline void setSampleRate(T newRate) { dt = T(1) / newRate; } /** Sets the lower und upper cutoff frequency between which all the action happens. */ inline void setCutoffFrequencies(T lowCutoff, T highCutoff) { wLo = T(2) * PI * lowCutoff * dt; wHi = T(2) * PI * highCutoff * dt; } //----------------------------------------------------------------------------------------------- // \name Processing /** Computes the desired gain factor for a given radian frequency w. */ inline T getGainForOmega(T w) { return T(1); // preliminary - todo: implement a bell curve here } /** Produces one output sample at a time. */ inline T getSample() { T y = T(0); // output // Create all frequencies from wRef up to the upper cutoff: T w = wRef; while(w <= wHi) { y += getGainForOmega(w) * sin(w*t); w *= T(2); } // Create all frequencies from 0.5*wRef down to the lower cutoff: w = T(0.5)*wRef; while(w >= wLo) { y += getGainForOmega(w) * sin(w*t); w *= T(0.5); } // Increment time and return output: t += dt; return y; } inline void reset() { t = T(0); } protected: T t; // current time, normalized to 0..1. our phasor T dt; // time increment per sample for t. equal to 1/sampleRate T wRef; // current reference omega T wLo, wHi; // high and low cutoff omegas }; //================================================================================================= // The APE effect GlobalData(ShepardTone, "Endless glissando generator"); class ShepardTone : public ape::Effect { public: ShepardTone() {} // Shorthands for convenience to reduce boilerplate: using Par = ape::Param<float>; using Rng = ape::Range; using Map = Rng::Mapping; Par parGain{ "Gain", Rng(-48, 12) }; // in dB Par parFreqLo{ "FreqLo", Rng(20, 20000, Map::Exp) }; // lower cutoff in Hz Par parFreqHi{ "FreqHi", Rng(20, 20000, Map::Exp) }; // upper cutoff in Hz Par parFreq{ "Freq", Rng(20, 20000, Map::Exp) }; // current reference freq // this is preliminary - later this is the freq that should automatically increase or decrease // and wrap around when it reaches to times its original value private: rsShepardToneGenerator<float> core; /** Resets the internal state. */ void reset() { core.reset(); } //----------------------------------------------------------------------------------------------- // \name Overriden callbacks (why are they private?) void start(const ape::IOConfig& cfg) override { reset(); } void process(ape::umatrix<const float> ins, ape::umatrix<float> outs, size_t numFrames) override { // Pull the values of the parameters for this block and update the DSP object: const float gain = RAPT::rsDbToAmp((float)parGain); float s = 2*PI / config().sampleRate; float wl = s * (float)parFreqLo; float wh = s * (float)parFreqHi; //core.setOmegas(wl, wh); // Loop over the sample frames: const auto numChannels = sharedChannels(); // shared? with whom? for(size_t n = 0; n < numFrames; ++n) { float y = gain * core.getSample(); // compute output for(size_t c = 0; c < numChannels; ++c) // write generated sample into all channels outs[c][n] = y; } clear(outs, numChannels); // what does this do? clear unused channels? } };
27.756757
99
0.542113
RobinSchmidt
da6a5d89591ce71da2a1488e769d888696c4add6
9,277
cpp
C++
src/core/btrc/core/volume/bvh.cpp
AirGuanZ/Btrc
8865eb1506f96fb0230fb394b9fadb1e38f2b9d8
[ "MIT" ]
17
2022-02-03T09:35:14.000Z
2022-03-28T04:27:05.000Z
src/core/btrc/core/volume/bvh.cpp
AirGuanZ/Btrc
8865eb1506f96fb0230fb394b9fadb1e38f2b9d8
[ "MIT" ]
1
2022-02-09T15:11:55.000Z
2022-02-09T15:11:55.000Z
src/core/btrc/core/volume/bvh.cpp
AirGuanZ/Btrc
8865eb1506f96fb0230fb394b9fadb1e38f2b9d8
[ "MIT" ]
null
null
null
#include <bvh/bvh.hpp> #include <bvh/leaf_collapser.hpp> #include <bvh/locally_ordered_clustering_builder.hpp> #include <bvh/parallel_reinsertion_optimizer.hpp> #include <btrc/core/volume/bvh.h> #include <btrc/utils/enumerate.h> BTRC_BEGIN namespace { constexpr int TRAVERSAL_STACK_SIZE = 16; bvh::Vector3<float> convert(const Vec3f &v) { return bvh::Vector3<float>(v.x, v.y, v.z); } bvh::BoundingBox<float> convert(const AABB3f &bbox) { return bvh::BoundingBox(convert(bbox.lower), convert(bbox.upper)); } f32 max(f32 a, f32 b, f32 c, f32 d) { return cstd::max(cstd::max(a, b), cstd::max(c, d)); } f32 min(f32 a, f32 b, f32 c, f32 d) { return cstd::min(cstd::min(a, b), cstd::min(c, d)); } } // namespace anonymous volume::BVH::BVH(const std::vector<RC<VolumePrimitive>> &vols) { if(vols.empty()) return; AABB3f global_bbox; std::vector<bvh::BoundingBox<float>> aabbs(vols.size()); std::vector<bvh::Vector3<float>> centers(vols.size()); for(auto &&[i, vol] : enumerate(vols)) { const AABB3f aabb = vol->get_bounding_box(); aabbs[i] = convert(aabb); centers[i] = convert(0.5f * (aabb.lower + aabb.upper)); global_bbox = union_aabb(global_bbox, aabb); } bvh::Bvh<float> tree; bvh::LocallyOrderedClusteringBuilder<bvh::Bvh<float>, uint64_t> builder(tree); builder.build(convert(global_bbox), aabbs.data(), centers.data(), vols.size()); bvh::ParallelReinsertionOptimizer bvh_optimizer(tree); bvh_optimizer.optimize(); bvh::LeafCollapser leaf_collapser(tree); leaf_collapser.collapse(); std::vector<BVHNode> nodes(tree.node_count); std::vector<BVHPrimitive> prims; for(size_t ni = 0; ni < tree.node_count; ++ni) { auto &src_node = tree.nodes[ni]; auto &dst_node = nodes[ni]; dst_node.lower.x = src_node.bounds[0]; dst_node.lower.y = src_node.bounds[2]; dst_node.lower.z = src_node.bounds[4]; dst_node.upper.x = src_node.bounds[1]; dst_node.upper.y = src_node.bounds[3]; dst_node.upper.z = src_node.bounds[5]; if(src_node.is_leaf()) { const size_t prim_beg = prims.size(); const size_t i_end = src_node.first_child_or_primitive + src_node.primitive_count; for(size_t i = src_node.first_child_or_primitive; i < i_end; ++i) { const size_t pi = tree.primitive_indices[i]; auto &vol = vols[pi]; const VolumePrimitive::VolumeGeometryInfo geo = vol->get_geometry_info(); const BVHPrimitive prim_info = { .o = geo.o, .vol_id = static_cast<uint32_t>(pi), .x_div_x2 = geo.x / length_square(geo.x), .y_div_y2 = geo.y / length_square(geo.y), .z_div_z2 = geo.z / length_square(geo.z) }; prims.push_back(prim_info); } const size_t prim_end = prims.size(); assert(prim_end > prim_beg); dst_node.prim_beg = static_cast<int32_t>(prim_beg); dst_node.prim_end = static_cast<int32_t>(prim_end); } else { dst_node.prim_beg = -1; dst_node.prim_end = static_cast<int32_t>(src_node.first_child_or_primitive); } } nodes_.swap(nodes); prims_.swap(prims); } bool volume::BVH::is_empty() const { return nodes_.empty(); } boolean volume::BVH::find_closest_intersection(ref<CVec3f> a, ref<CVec3f> b, ref<CVec3f> output_position) const { if(nodes_.empty()) return false; boolean result; $scope { var nodes = cuj::const_data(nodes_); var prims = cuj::const_data(prims_); var dir = b - a; var inv_dir = 1.0f / dir; var final_t = btrc_max_float, t_max = 1.0f; cuj::arr<u32, TRAVERSAL_STACK_SIZE> traversal_stack; traversal_stack[0] = 0; var top = 1; $while(top > 0) { top = top - 1; var task_node_idx = traversal_stack[top]; ref<CBVHNode> node = nodes[task_node_idx]; $if(is_leaf_node(node)) { $forrange(i, node.prim_beg, node.prim_end) { var t = find_closest_intersection(a, dir, t_max, prims[i]); $if(t >= 0.0f) { final_t = cstd::min(final_t, t); t_max = final_t; }; }; } $else { var left = nodes[node.prim_end]; $if(intersect_ray_aabb(left.lower, left.upper, a, inv_dir, t_max)) { traversal_stack[top] = u32(node.prim_end); top = top + 1; }; var right = nodes[node.prim_end + 1]; $if(intersect_ray_aabb(right.lower, right.upper, a, inv_dir, t_max)) { traversal_stack[top] = u32(node.prim_end + 1); top = top + 1; }; }; }; $if(final_t > 10) { result = false; $exit_scope; }; CUJ_ASSERT(final_t >= 0.0f); CUJ_ASSERT(final_t <= 1.0f); output_position = a * (1.0f - final_t) + b * final_t; result = true; }; return result; } volume::BVH::Overlap volume::BVH::get_overlap(ref<CVec3f> position) const { Overlap result; result.count = 0; if(nodes_.empty()) return result; $scope { var nodes = cuj::const_data(nodes_); var prims = cuj::const_data(prims_); cuj::arr<u32, TRAVERSAL_STACK_SIZE> traversal_stack; traversal_stack[0] = 0; var top = 1; $while(top > 0) { top = top - 1; ref node = nodes[traversal_stack[top]]; $if(is_leaf_node(node)) { $forrange(i, node.prim_beg, node.prim_end) { ref prim = prims[i]; $if(is_in_prim(position, prim)) { result.data[result.count] = prim.vol_id; result.count = result.count + 1; $if(result.count >= MAX_OVERLAP_COUNT) { $exit_scope; }; }; }; } $else { var left = nodes[node.prim_end]; $if(is_in_aabb(position, left.lower, left.upper)) { traversal_stack[top] = u32(node.prim_end); top = top + 1; }; var right = nodes[node.prim_end + 1]; $if(is_in_aabb(position, right.lower, right.upper)) { traversal_stack[top] = u32(node.prim_end + 1); top = top + 1; }; }; }; }; return result; } boolean volume::BVH::is_leaf_node(ref<CBVHNode> node) const { return node.prim_beg >= 0; } boolean volume::BVH::is_in_prim(ref<CVec3f> pos, ref<CBVHPrimitive> prim) const { var op = pos - prim.o; var u = dot(op, prim.x_div_x2); var v = dot(op, prim.y_div_y2); var w = dot(op, prim.z_div_z2); return 0.0f <= u & u <= 1.0f & 0.0f <= v & v <= 1.0f & 0.0f <= w & w <= 1.0f; } boolean volume::BVH::is_in_aabb(ref<CVec3f> pos, ref<CVec3f> lower, ref<CVec3f> upper) const { return lower.x <= pos.x & pos.x <= upper.x & lower.y <= pos.y & pos.y <= upper.y & lower.z <= pos.z & pos.z <= upper.z; } boolean volume::BVH::intersect_ray_aabb(ref<CVec3f> lower, ref<CVec3f> upper, ref<CVec3f> o, ref<CVec3f> inv_d, f32 t_max) const { var n = inv_d * (lower - o); var f = inv_d * (upper - o); var t0 = max(0.0f, cstd::min(n.x, f.x), cstd::min(n.y, f.y), cstd::min(n.z, f.z)); var t1 = min(t_max, cstd::max(n.x, f.x), cstd::max(n.y, f.y), cstd::max(n.z, f.z)); return t0 <= t1; } f32 volume::BVH::find_closest_intersection(ref<CVec3f> p, ref<CVec3f> d, f32 t_max, ref<CBVHPrimitive> prim) const { var op = p - prim.o; var t0 = 0.0f, t1 = t_max; auto process_interval = [&](ref<CVec3f> d_div_d2) { var opd = dot(op, d_div_d2); var dd = dot(d, d_div_d2); var nd = (0.0f - opd) / dd; var fd = (1.0f - opd) / dd; t0 = cstd::max(t0, cstd::min(nd, fd)); t1 = cstd::min(t1, cstd::max(nd, fd)); }; process_interval(prim.x_div_x2); process_interval(prim.y_div_y2); process_interval(prim.z_div_z2); f32 result; $scope { $if(t0 > t1) { result = -1; $exit_scope; }; $if(t0 > 0) { result = t0; $exit_scope; }; $if(t1 < t_max) { result = t1; $exit_scope; }; result = -1; }; return result; } BTRC_END
28.283537
128
0.514067
AirGuanZ
da718d0199de3de971410d10c487de0b34a802ee
6,879
cxx
C++
ZDC/ZDCrec/AliZDCRecoParamPbPb.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
ZDC/ZDCrec/AliZDCRecoParamPbPb.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
ZDC/ZDCrec/AliZDCRecoParamPbPb.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////////// // // // Class with ZDC reconstruction parameters // // Origin: [email protected] // // // /////////////////////////////////////////////////////////////////////////////// #include <TFile.h> #include <TTree.h> #include <TH2F.h> #include <TH1D.h> #include "AliZDCRecoParam.h" #include "AliZDCRecoParamPbPb.h" ClassImp(AliZDCRecoParamPbPb) //_____________________________________________________________________________ AliZDCRecoParamPbPb::AliZDCRecoParamPbPb() : AliZDCRecoParam(), fhNpartDist(0x0), fhbDist(0x0), fClkCenter(0) { // //Default constructor } //_____________________________________________________________________________ AliZDCRecoParamPbPb::AliZDCRecoParamPbPb(TH1D *hNpart, TH1D *hb, Float_t clkCent) : AliZDCRecoParam(), fhNpartDist(hNpart), fhbDist(hb), fClkCenter(clkCent) { // //Standard constructor } //______________________________________________________________________________ AliZDCRecoParamPbPb::AliZDCRecoParamPbPb(const AliZDCRecoParamPbPb &oldrecopar) : AliZDCRecoParam(), fhNpartDist(0x0), fhbDist(0x0), fClkCenter(oldrecopar.fClkCenter) { //Copy constructor if(oldrecopar.fhNpartDist){ fhNpartDist = new TH1D(*oldrecopar.fhNpartDist); fhNpartDist->SetDirectory(0); } if(oldrecopar.fhbDist){ fhbDist = new TH1D(*oldrecopar.fhbDist); fhbDist->SetDirectory(0); } } //_____________________________________________________________________________ AliZDCRecoParamPbPb &AliZDCRecoParamPbPb::operator =(const AliZDCRecoParamPbPb &recpar) { // Equal operator. this->~AliZDCRecoParamPbPb(); new(this) AliZDCRecoParamPbPb(recpar); return *this; } //_____________________________________________________________________________ AliZDCRecoParamPbPb::~AliZDCRecoParamPbPb() { // destructor if(fhNpartDist) delete fhNpartDist; if(fhbDist) delete fhbDist; } //_____________________________________________________________________________ void AliZDCRecoParamPbPb::SetGlauberMCDist(Float_t beamEnergy) { // Setting Glauber MC distributions // from histos file stored in $ALICE_ROOT/ZDC TH1::AddDirectory(0); TH2::AddDirectory(0); TFile *fileGlauberMC = TFile::Open("$ALICE_ROOT/ZDC/GlauberMCDist.root"); if(!fileGlauberMC) { AliError((" Opening file $ALICE_ROOT/ZDC/GlauberMCDist.root failed\n")); return; } Float_t sqrtS = 2*beamEnergy; // if(TMath::Abs(sqrtS-5500) < 100.){ AliDebug(2, " ZDC -> Looking for energy5500 in file $ALICE_ROOT/ZDC/GlauberMCDist.root"); fileGlauberMC->cd("energy5500"); fileGlauberMC->GetObject("energy5500/hbGlauber;1", fhbDist); if(!fhbDist) AliError(" PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy5500/hNpartGlauber;1", fhNpartDist); if(!fhNpartDist) AliError(" PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); } else if(TMath::Abs(sqrtS-2760) < 100.){ AliDebug(2, " ZDC -> Looking for energy2760 in file $ALICE_ROOT/ZDC/GlauberMCDist.root"); fileGlauberMC->cd("energy2760"); fileGlauberMC->GetObject("energy2760/hbGlauber;1", fhbDist); if(!fhbDist) AliError(" PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy2760/hNpartGlauber;1", fhNpartDist); if(!fhNpartDist) AliError(" PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); } else AliError(Form(" No AliZDCRecoParam provided for Pb-Pb @ sqrt(s) = %1.0f GeV\n", sqrtS)); // fhNpartDist->SetDirectory(0); fhbDist->SetDirectory(0); fileGlauberMC->Close(); } //_____________________________________________________________________________ AliZDCRecoParamPbPb *AliZDCRecoParamPbPb::GetHighFluxParam(Float_t beamEnergy) { // Create high flux reco parameter TH1::AddDirectory(0); TH2::AddDirectory(0); TFile *fileGlauberMC = TFile::Open("$ALICE_ROOT/ZDC/GlauberMCDist.root"); if(!fileGlauberMC) { printf(" Opening file $ALICE_ROOT/ZDC/GlauberMCDist.root failed\n"); return NULL; } Float_t sqrtS = 2*beamEnergy; TH1D *hNpartDist=0x0, *hbDist=0x0; if(TMath::Abs(sqrtS-5500)<100.){ fileGlauberMC->cd("energy5500"); fileGlauberMC->GetObject("energy5500/hNpartGlauber;1", hNpartDist); if(!hNpartDist) printf(" AliZDCRecoParamPbPb::GetHighFluxParam() PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy5500/hbGlauber;1", hbDist); if(!hbDist) printf(" AliZDCRecoParamPbPb::GetHighFluxParam() PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); } else if(TMath::Abs(sqrtS-2760)<100.){ fileGlauberMC->cd("energy2760"); fileGlauberMC->GetObject("energy2760/hNpartGlauber;1", hNpartDist); if(!hNpartDist) printf(" PROBLEM!!! Can't get Glauber MC Npart distribution from file GlauberMCDist.root\n"); fileGlauberMC->GetObject("energy2760/hbGlauber;1", hbDist); if(!hbDist) printf(" AliZDCRecoParamPbPb::GetHighFluxParam() PROBLEM!!! Can't get Glauber MC b distribution from file GlauberMCDist.root\n"); } else printf(" No AliZDCRecoParam provided for Pb-Pb @ sqrt(s) = %1.0f GeV\n", sqrtS); // if(hNpartDist) hNpartDist->SetDirectory(0); if(hbDist) hbDist->SetDirectory(0); AliZDCRecoParamPbPb* zdcRecoParam = new AliZDCRecoParamPbPb(hNpartDist, hbDist, 0.1); // fileGlauberMC->Close(); return zdcRecoParam; }
39.763006
154
0.661579
AllaMaevskaya
da7555f9e196ed7ce8379f7f07916457df86e790
992
cpp
C++
libs/ncurses_lib/libncurses.cpp
elivet/Nibbler
9e2e07d9e3fa3dc86a8e25a6db419359fa0e0e8a
[ "Apache-2.0" ]
null
null
null
libs/ncurses_lib/libncurses.cpp
elivet/Nibbler
9e2e07d9e3fa3dc86a8e25a6db419359fa0e0e8a
[ "Apache-2.0" ]
null
null
null
libs/ncurses_lib/libncurses.cpp
elivet/Nibbler
9e2e07d9e3fa3dc86a8e25a6db419359fa0e0e8a
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libncurses.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: elivet <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/03/17 13:54:17 by elivet #+# #+# */ /* Updated: 2015/03/17 13:54:20 by elivet ### ########.fr */ /* */ /* ************************************************************************** */ #include "NcursesLib.hpp" extern "C" ILib * getInstance( void ) { return ( new NcursesLib() ); }
49.6
80
0.157258
elivet
da816a5740ebbd66adff15d7f6c185d906b311e1
41,955
cpp
C++
tests/tests.cpp
leopoldcambier/spaND_public
fc344dc1ff4b36832aad3f86adb4a23111c67366
[ "MIT" ]
6
2019-05-06T21:17:07.000Z
2022-02-11T14:56:30.000Z
tests/tests.cpp
leopoldcambier/spaND_public
fc344dc1ff4b36832aad3f86adb4a23111c67366
[ "MIT" ]
null
null
null
tests/tests.cpp
leopoldcambier/spaND_public
fc344dc1ff4b36832aad3f86adb4a23111c67366
[ "MIT" ]
1
2019-06-23T12:04:28.000Z
2019-06-23T12:04:28.000Z
#include <gtest/gtest.h> #include <iostream> #include <assert.h> #include <algorithm> #include <random> #include "spaND.h" #include "mmio.hpp" #include "cxxopts.hpp" #include <Eigen/SparseCholesky> using namespace std; using namespace Eigen; using namespace spaND; bool VERB = false; int N_THREADS = 4; int RUN_MANY = 4; SymmKind symm2syk(int symm) { switch(symm) { case 0: return SymmKind::SPD; case 1: return SymmKind::SYM; case 2: return SymmKind::GEN; default: assert(false); }; return SymmKind::SPD; } PartKind pki2pk(int pki) { switch(pki) { case 0: return PartKind::MND; case 1: return PartKind::RB; default: assert(false); }; return PartKind::MND; } ScalingKind ski2sk(int ski) { switch(ski) { case 0: return ScalingKind::LLT; case 1: return ScalingKind::EVD; case 2: return ScalingKind::SVD; case 3: return ScalingKind::PLU; case 4: return ScalingKind::PLUQ; case 5: return ScalingKind::LDLT; default: assert(false); }; return ScalingKind::LLT; } bool is_valid(SymmKind syk, ScalingKind sk, bool preserve) { if(syk == SymmKind::SPD) { if (sk != ScalingKind::LLT) return false; } if(syk == SymmKind::SYM) { if (sk != ScalingKind::LDLT) return false; } if(syk == SymmKind::GEN) { if (sk != ScalingKind::PLU && sk != ScalingKind::PLUQ) return false; } if(preserve) return false; return true; } struct params { SymmKind syk; PartKind pk; ScalingKind sk; bool preserve; }; vector<params> get_params() { vector<params> configs; for(int symm = 0; symm < 3; symm++) { for(int pki = 0; pki < 2; pki++) { for(int ski = 0; ski < 6; ski++) { for(int pres = 0; pres < 2; pres++) { PartKind pk = pki2pk(pki); ScalingKind sk = ski2sk(ski); SymmKind syk = symm2syk(symm); if(! is_valid(syk, sk, pres)) continue; configs.push_back({syk, pk, sk, pres == 1}); } } } } return configs; }; SpMat neglapl(int n, int d) { stringstream s; s << "../mats/neglapl_" << d << "_" << n << ".mm"; string file = s.str(); SpMat A = mmio::sp_mmread<double,int>(file); return A; } SpMat neglapl_unsym(int n, int d, int seed) { SpMat A = neglapl(n, d); default_random_engine gen; gen.seed(seed); uniform_real_distribution<double> rand(-0.1, 0.1); for(int k = 0; k < A.outerSize(); ++k) { for(SpMat::InnerIterator it(A, k); it; ++it) { A.coeffRef(it.row(), it.col()) += rand(gen); } } return A; } SpMat make_indef(SpMat& A, int seed) { Eigen::SimplicialLLT<SpMat, Eigen::Lower> sllt(A); VectorXd random_diagonal = random(A.rows(), seed); for(int i = 0; i < A.rows(); i++) { if(random_diagonal[i] <= 0.9) { random_diagonal[i] = -1; } else { random_diagonal[i] = 1; } } SpMat L = sllt.matrixL(); return L * (random_diagonal.asDiagonal() * L.transpose()); } SpMat random_SpMat(int n, double p, int seed) { default_random_engine gen; gen.seed(seed); uniform_real_distribution<double> dist(0.0,1.0); vector<Triplet<double>> triplets; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { auto v_ij = dist(gen); if(v_ij < p) { triplets.push_back(Triplet<double>(i,j,v_ij)); } } } SpMat A(n,n); A.setFromTriplets(triplets.begin(), triplets.end()); return A; } SpMat identity_SpMat(int n) { vector<Triplet<double>> triplets; for(int i = 0; i < n; ++i) { triplets.push_back(Triplet<double>(i,i,1.0)); } SpMat A(n,n); A.setFromTriplets(triplets.begin(), triplets.end()); return A; } TEST(MatrixMarket, Sparse) { // 1 SpMat A = mmio::sp_mmread<double,int>("../mats/test1.mm"); SpMat Aref(2, 3); Aref.insert(0, 0) = 1; Aref.insert(0, 1) = -2e2; Aref.insert(1, 1) = 3e3; Aref.insert(1, 2) = -4.4e4; EXPECT_EQ(A.nonZeros(), 4); EXPECT_EQ((Aref - A).norm(), 0.0); // 2 A = mmio::sp_mmread<double,int>("../mats/test2.mm"); Aref = SpMat(3, 3); Aref.insert(0, 0) = 1.1; Aref.insert(1, 1) = 2e2; Aref.insert(2, 0) = -3.3; Aref.insert(0, 2) = -3.3; EXPECT_EQ(A.nonZeros(), 4); EXPECT_EQ((Aref - A).norm(), 0.0); // 3 A = mmio::sp_mmread<double,int>("../mats/test3.mm"); Aref = SpMat(4, 1); Aref.insert(3, 0) = -1; EXPECT_EQ(A.nonZeros(), 1); EXPECT_EQ((Aref - A).norm(), 0.0); // 4 A = mmio::sp_mmread<double,int>("../mats/test4.mm"); Aref = SpMat(2, 2); Aref.insert(1, 0) = -3.3; Aref.insert(0, 1) = -3.3; EXPECT_EQ(A.nonZeros(), 2); EXPECT_EQ((Aref - A).norm(), 0.0); } TEST(MatrixMarket, Array) { // 5 MatrixXd A = mmio::dense_mmread<double>("../mats/test5.mm"); EXPECT_EQ(A.rows(), 2); EXPECT_EQ(A.cols(), 3); MatrixXd Aref(2, 3); Aref << 1, 3, -5, 2, 4, 1e6; // row-wise filling in eigen EXPECT_EQ((Aref - A).norm(), 0.0); // 6 A = mmio::dense_mmread<double>("../mats/test6.mm"); Aref = MatrixXd(2, 2); EXPECT_EQ(A.rows(), 2); EXPECT_EQ(A.cols(), 2); Aref << 1, -2, -2, 3; // row-wise filling in eigen EXPECT_EQ((Aref - A).norm(), 0.0); } /** Util.cpp tests **/ TEST(Util, AreConnected) { // 3x3 laplacian SpMat A = mmio::sp_mmread<double,int>("../mats/neglapl_2_3.mm"); VectorXi a(2); VectorXi b(3); a << 0, 1; b << 6, 7, 8; EXPECT_FALSE(are_connected(a, b, A)); a = VectorXi(2); b = VectorXi(3); a << 0, 1; b << 2, 5, 8; EXPECT_TRUE(are_connected(a, b, A)); a = VectorXi(2); b = VectorXi(1); a << 3, 4; b << 5; EXPECT_TRUE(are_connected(a, b, A)); a = VectorXi(1); b = VectorXi(1); a << 6; b << 6; EXPECT_TRUE(are_connected(a, b, A)); } TEST(Util, ShouldBeDisconnected) { EXPECT_TRUE(should_be_disconnected(0, 0, 0, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 1, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 4, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 5, 2)); EXPECT_TRUE(should_be_disconnected(0, 0, 1000, 2)); EXPECT_TRUE(should_be_disconnected(1, 2, 2, 0)); EXPECT_TRUE(should_be_disconnected(0, 1, 1, 1)); EXPECT_TRUE(should_be_disconnected(0, 2, 1, 1)); EXPECT_TRUE(should_be_disconnected(2, 0, 0, 5)); EXPECT_TRUE(should_be_disconnected(2, 2, 0, 1)); EXPECT_FALSE(should_be_disconnected(0, 1, 0, 0)); EXPECT_FALSE(should_be_disconnected(0, 2, 0, 0)); EXPECT_FALSE(should_be_disconnected(0, 10, 0, 0)); EXPECT_FALSE(should_be_disconnected(2, 0, 1, 5)); EXPECT_FALSE(should_be_disconnected(2, 0, 1, 6)); EXPECT_FALSE(should_be_disconnected(2, 1, 1, 2)); EXPECT_FALSE(should_be_disconnected(2, 1, 1, 3)); } TEST(Util, ChooseRank) { VectorXd errs = VectorXd(5); errs << 1.0, -0.1, 0.01, -0.001, 1e-4; EXPECT_EQ(choose_rank(errs, 1e-1), 2); EXPECT_EQ(choose_rank(errs, 1e-2), 3); EXPECT_EQ(choose_rank(errs, 1.0), 0); EXPECT_EQ(choose_rank(errs, 0), 5); EXPECT_EQ(choose_rank(errs, 1e-16), 5); } TEST(Util, Block2Dense) { // Usual case { SpMat A(5, 5); A.insert(0, 0) = 1.0; A.insert(2, 2) = -2.0; A.insert(1, 3) = 3.0; A.makeCompressed(); VectorXi rowval = Map<VectorXi>(A.innerIndexPtr(), A.nonZeros()); VectorXi colptr = Map<VectorXi>(A.outerIndexPtr(), 6); VectorXd nnzval = Map<VectorXd>(A.valuePtr(), A.nonZeros()); MatrixXd Ad = MatrixXd::Zero(3, 3); block2dense(rowval, colptr, nnzval, 1, 1, 3, 3, &Ad, false); MatrixXd Adref = MatrixXd::Zero(3, 3); Adref << 0, 0, 3, 0, -2, 0, 0, 0, 0; EXPECT_EQ((Adref - Ad).norm(), 0); } // Transpose { SpMat A(3, 4); A.insert(0, 1) = 1.0; A.insert(1, 0) = 2.0; A.insert(1, 2) = 3.0; A.insert(2, 1) = 4.0; A.insert(0, 3) = 5.0; A.makeCompressed(); VectorXi rowval = Map<VectorXi>(A.innerIndexPtr(), A.nonZeros()); VectorXi colptr = Map<VectorXi>(A.outerIndexPtr(), 5); VectorXd nnzval = Map<VectorXd>(A.valuePtr(), A.nonZeros()); MatrixXd Ad = MatrixXd::Zero(3, 2); block2dense(rowval, colptr, nnzval, 0, 0, 2, 3, &Ad, true); MatrixXd Adref = MatrixXd::Zero(3, 2); Adref << 0, 2, 1, 0, 0, 3; EXPECT_EQ((Adref - Ad).norm(), 0); } } TEST(Util, LinspaceNd) { MatrixXd X2 = linspace_nd(3, 2); MatrixXd X2ref(2, 9); X2ref << 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2; EXPECT_EQ((X2ref - X2).norm(), 0); MatrixXd X3 = linspace_nd(2, 3); MatrixXd X3ref(3, 8); X3ref << 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1; EXPECT_EQ((X3ref - X3).norm(), 0); } TEST(Util, SymmPerm) { vector<int> dims = {2, 2, 2, 3, 3, 3, 3 }; vector<int> sizes = {5, 10, 20, 5, 15, 25, 30}; for(int test = 0; test < dims.size(); test++) { int s = sizes[test]; int d = dims[test]; stringstream ss; ss << "../mats/neglapl_" << d << "_" << s << ".mm"; SpMat A = mmio::sp_mmread<double,int>(ss.str()); // Create random perm int N = A.rows(); VectorXi p = VectorXi::LinSpaced(N, 0, N-1); random_device rd; mt19937 g(rd()); shuffle(p.data(), p.data() + N, g); // Compare SpMat pAp = symm_perm(A, p); SpMat pApref = p.asPermutation().inverse() * A * p.asPermutation(); EXPECT_EQ((pAp - pApref).norm(), 0.0); } } TEST(Util, isperm) { VectorXi perm1(10); VectorXi perm2(10); VectorXi noperm1(10); VectorXi noperm2(5); perm1 << 0, 9, 8, 1, 4, 2, 3, 7, 5, 6; perm2 << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9; noperm1 << 0, 9, 8, 1, 4, 2, 3, 5, 5, 6; noperm2 << 0, 9, 8, 1, 4; EXPECT_TRUE(isperm(&perm1)); EXPECT_TRUE(isperm(&perm2)); EXPECT_FALSE(isperm(&noperm1)); EXPECT_FALSE(isperm(&noperm2)); } TEST(Util, swap2perm) { VectorXi swap(6); VectorXi perm(6); VectorXi permRef(6); swap << 3, 3, 2, 5, 4, 5; permRef << 3, 0, 2, 5, 4, 1; swap2perm(&swap, &perm); // perm.asPermutation().transpose() * x <=> x[perm] EXPECT_EQ((perm - permRef).norm(), 0.0); } SpMat symmetric_graph_ref(SpMat A) { SpMat ATabs = A.cwiseAbs().transpose(); return A.cwiseAbs() + ATabs + identity_SpMat(A.rows()); } TEST(Util, symmetric_graph) { for(int i = 1; i < 100; i++) { SpMat A = random_SpMat(i, 0.2, i); SpMat AAT = symmetric_graph(A); EXPECT_LT( (AAT - symmetric_graph_ref(A)).norm(), 1e-12); } } /** Partitioning tests **/ /** * Check the partitioning of a square laplacian 5x5 */ TEST(PartitionTest, Square) { SpMat A = mmio::sp_mmread<double,int>("../mats/neglapl_2_5.mm"); MatrixXd X = linspace_nd(5, 2); Tree t(3); t.set_verb(VERB); t.set_use_geo(true); t.set_Xcoo(&X); auto part = t.partition(A); vector<SepID> sepidref { SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1), SepID(2,0), SepID(2,0), SepID(2,0), SepID(2,0), SepID(2,0), SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), } ; vector<SepID> leftref { SepID(0,0), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(1,0), SepID(0,1), SepID(0,1), SepID(0,2), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), } ; vector<SepID> rightref { SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,1), SepID(0,0), SepID(0,0), SepID(0,1), SepID(0,1), SepID(0,1), SepID(0,2), SepID(0,2), SepID(1,1), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,3), SepID(0,2), SepID(0,2), SepID(0,3), SepID(0,3), SepID(0,3), } ; for(int i = 0; i < part.size(); i++) { ASSERT_TRUE(part[i].self == sepidref[i]); ASSERT_TRUE(part[i].l == leftref[i]); ASSERT_TRUE(part[i].r == rightref[i]); } } /** * Check consistency of the partitioning */ TEST(PartitionTest, Consistency) { vector<int> dims = {2, 2, 2, 3, 3, 3 }; vector<int> sizes = {5, 20, 100, 5, 15, 25}; for(int test = 0; test < dims.size(); test++) { int s = sizes[test]; int d = dims[test]; stringstream ss; ss << "../mats/neglapl_" << d << "_" << s << ".mm"; int n = pow(s, d); string file = ss.str(); for(int nlevels = 1; nlevels < 8; nlevels++) { for(int geoi = 0; geoi < 2; geoi++) { for(int pki = 0; pki < 2; pki++) { bool geo = (geoi == 0); PartKind pk = pki == 0 ? PartKind::MND : PartKind::RB; // Partition tree MatrixXd X = linspace_nd(s, d); Tree t(nlevels); t.set_verb(VERB); SpMat A = mmio::sp_mmread<double,int>(file); t.set_use_geo(geo); t.set_Xcoo(&X); t.set_part_kind(pk); auto part = t.partition(A); // (1) Lengths ASSERT_EQ(part.size(), n); // (2) Check ordering integrity for(int i = 0; i < n; i++) { auto pi = part[i].self; for (SpMat::InnerIterator it(A,i); it; ++it) { int j = it.row(); auto pj = part[j].self; ASSERT_FALSE(should_be_disconnected(pi.lvl, pj.lvl, pi.sep, pj.sep)); } } // (3) Check left/right integrity for(int i = 0; i < n; i++) { auto pi = part[i].self; auto li = part[i].l; auto ri = part[i].r; if(pi.lvl == 0) { ASSERT_TRUE(pi == li); ASSERT_TRUE(pi == ri); } else { ASSERT_TRUE(pi.lvl > li.lvl); ASSERT_TRUE(pi.lvl > ri.lvl); while(li.lvl < pi.lvl - 1) { li.lvl += 1; li.sep /= 2; } while(ri.lvl < pi.lvl - 1) { ri.lvl += 1; ri.sep /= 2; } ASSERT_TRUE(li.lvl == pi.lvl - 1); ASSERT_TRUE(ri.lvl == pi.lvl - 1); ASSERT_TRUE(li.sep == 2 * pi.sep); ASSERT_TRUE(ri.sep == 2 * pi.sep + 1); } } } } } } } /** Assembly tests **/ /** * Check assembly */ TEST(Assembly, Consistency) { vector<int> dims = {2, 2, 2, 3, 3, 3}; vector<int> sizes = {5, 10, 20, 5, 10, 15}; for(int spandlorasp = 0; spandlorasp < 2; spandlorasp++) { for(int test = 0; test < dims.size(); test++) { for(int pki = 0; pki < 2; pki++) { PartKind pk = pki == 0 ? PartKind::MND : PartKind::RB; int s = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test); for(int nlevels = 2; nlevels < 5 ; nlevels++) { /** * Symmetric case */ { // Partition and assemble Tree t(nlevels); t.set_verb(VERB); t.set_use_geo(false); t.set_part_kind(pk); if(spandlorasp == 0) t.partition(Aref); else t.partition_lorasp(Aref); t.assemble(Aref); // Get permutation VectorXi p = t.get_assembly_perm(); // Check it's indeed a permutation ASSERT_TRUE(isperm(&p)); auto P = p.asPermutation(); // Check get_mat() SpMat A2 = t.get_trailing_mat(); EXPECT_EQ((P.inverse() * Aref * P - A2).norm(), 0.0); } /** * Unsymmetric case */ { // Partition and assemble Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(SymmKind::GEN); t.set_use_geo(false); t.set_part_kind(pk); if(spandlorasp == 0) t.partition(Arefunsym); else t.partition_lorasp(Arefunsym); t.assemble(Arefunsym); // Get permutation VectorXi p = t.get_assembly_perm(); // Check it's indeed a permutation ASSERT_TRUE(isperm(&p)); auto P = p.asPermutation(); // Check get_mat() SpMat A2 = t.get_trailing_mat(); EXPECT_EQ((P.inverse() * Arefunsym * P - A2).norm(), 0.0); } } } } } } /** Factorization tests **/ TEST(ApproxTest, PrintConfigs) { vector<params> configs = get_params(); cout << "Preserve ? PartKind ? ScalingKind ? SymmKind ?" << endl; for(auto c: configs) { cout << c.preserve << " " << part2str(c.pk) << " " << scaling2str(c.sk) << " " << symm2str(c.syk) << endl; } } /** * Test that with eps=0, we get exact solutions */ TEST(ApproxTest, Exact) { vector<int> dims = {2, 2, 2, 3, 3}; vector<int> sizes = {5, 10, 20, 5, 15}; vector<double> tols = {1e-14, 1e-14, 0.0}; vector<int> skips = {0, 4, 1000}; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { cout << "Test " << test << "... "; int count = 0; int s = sizes[test]; int d = dims[test]; int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test); SpMat Arefsym = make_indef(Aref, 2019+test); for(int nlevels = nlevelsmin; nlevels < nlevelsmin+5 ; nlevels++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? Arefsym : Arefunsym)); assert(! c.preserve); MatrixXd phi = random(Aref.rows(), 3, test+nlevels+2019); for(int it = 0; it < tols.size(); it++) { double tol = tols[it]; double skip = skips[it]; Tree t(nlevels); t.set_verb(VERB); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); t.set_symm_kind(c.syk); t.partition(A); t.assemble(A); t.set_tol(tol); t.set_skip(skip); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); t.factorize(); VectorXd b = random(n, test+nlevels+2019+1); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); EXPECT_LE(err, 1e-10) << err; count++; } } } cout << count << " tested.\n"; } } /** * Test SPD on A (laplacian) and SYM+LDLT on -A (- laplacian) give the same, with or without compression */ TEST(ApproxTest, SPD_vs_LDLT) { vector<int> dims = {2, 3, 3}; vector<int> sizes = {128, 5, 15}; vector<double> tols = {0, 1e-4, 1e-14}; vector<int> skips = {100, 1, 0}; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { cout << "Test " << test << "... "; int count = 0; int s = sizes[test]; int d = dims[test]; int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; SpMat A = neglapl(s, d); SpMat Aneg = -A; for(int nlevels = nlevelsmin; nlevels < nlevelsmin+5 ; nlevels++) { for(auto c: configs) { if(c.sk != ScalingKind::LLT && !c.preserve) continue; for(int it = 0; it < tols.size(); it++) { double tol = tols[it]; double skip = skips[it]; VectorXd b = random(n, test+nlevels+2019+1); // Use LLT on A Tree t_llt(nlevels); t_llt.set_verb(VERB); t_llt.set_part_kind(c.pk); t_llt.set_scaling_kind(ScalingKind::LLT); t_llt.set_symm_kind(SymmKind::SPD); t_llt.partition(A); t_llt.assemble(A); t_llt.set_tol(tol); t_llt.set_skip(skip); t_llt.set_preserve(false); t_llt.factorize(); VectorXd x_llt = b; t_llt.solve(x_llt); // Use LDLT on -A Tree t_ldlt(nlevels); t_ldlt.set_verb(VERB); t_ldlt.set_part_kind(c.pk); t_ldlt.set_scaling_kind(ScalingKind::LDLT); t_ldlt.set_symm_kind(SymmKind::SYM); t_ldlt.partition(Aneg); t_ldlt.assemble(Aneg); t_ldlt.set_tol(tol); t_ldlt.set_skip(skip); t_ldlt.set_preserve(false); t_ldlt.factorize(); VectorXd x_ldlt = - b; t_ldlt.solve(x_ldlt); // Compare double err_llt = (A*x_llt-b).norm() / b.norm(); double err_ldlt = (A*x_ldlt-b).norm() / b.norm(); double diff = (x_llt - x_ldlt).norm() / x_llt.norm(); if (tol == 0.0) { EXPECT_LE(err_llt, 1e-12); EXPECT_LE(err_ldlt, 1e-12); EXPECT_LE(diff, 1e-12); } else { EXPECT_LE(err_llt, tol * 1e2); EXPECT_LE(err_ldlt, tol * 1e2); EXPECT_LE(diff, tol * 1e2); } count++; } } } cout << count << " tested.\n"; } } /** * Test conservation is correct */ TEST(ApproxTest, Preservation) { vector<int> dims = {2, 2, 2, 3, 3, 3}; vector<int> sizes = {5, 10, 20, 5, 10, 25}; for(int test = 0; test < dims.size(); test++) { cout << "Test " << test; int s = sizes[test]; int d = dims[test]; stringstream ss; ss << "../mats/neglapl_" << d << "_" << s << ".mm"; int n = pow(s, d); string file = ss.str(); SpMat A_spd = mmio::sp_mmread<double,int>(file); SpMat A_sym = - A_spd; int nlevelsmin = n < 1000 ? 1 : 8; vector<double> tols = {10, 1e-2, 1e-3, 1e-4, 1e-6, 0.0}; for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) { for(int it = 0; it < tols.size(); it++) { for(int skip = 0; skip < 3; skip++) { for(int symm = 0; symm < 2; symm++) { printf("."); fflush(stdout); SpMat A; if(symm == 0) A = A_spd; else A = A_sym; // Check a 1 is preserved { Tree t(nlevels); if(symm == 0) { t.set_scaling_kind(ScalingKind::LLT); t.set_symm_kind(SymmKind::SPD); } else { t.set_scaling_kind(ScalingKind::LDLT); t.set_symm_kind(SymmKind::SYM); } t.set_verb(VERB); t.partition(A); t.assemble(A); MatrixXd phi = MatrixXd::Ones(n, 1); t.set_tol(tols[it]); t.set_skip(skip); t.set_preserve(true); t.set_phi(&phi); t.factorize(); for(int c = 0; c < phi.cols(); c++) { VectorXd b = A * phi.col(c); VectorXd x = b; t.solve(x); double err1 = (A*x-b).norm() / b.norm(); double err2 = (x-phi.col(c)).norm() / phi.col(c).norm(); EXPECT_TRUE(err1 < 1e-12) << "err1 = " << err1 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; EXPECT_TRUE(err2 < 1e-12) << "err2 = " << err2 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; } VectorXd b = random(n, nlevels+it+skip+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); if (tols[it] == 0.0) { EXPECT_TRUE(err < 1e-12); } else { EXPECT_TRUE(err < tols[it] * 1e2); } } // Check that a multiple random b are preserved { Tree t(nlevels); if(symm == 0) { t.set_scaling_kind(ScalingKind::LLT); t.set_symm_kind(SymmKind::SPD); } else { t.set_scaling_kind(ScalingKind::LDLT); t.set_symm_kind(SymmKind::SYM); } t.set_verb(VERB); t.partition(A); t.assemble(A); MatrixXd phi = random(n, 5, nlevels+it+skip+2019); t.set_tol(tols[it]); t.set_skip(skip); t.set_preserve(true); t.set_phi(&phi); t.factorize(); for(int c = 0; c < phi.cols(); c++) { VectorXd b = A * phi.col(c); VectorXd x = b; t.solve(x); double err1 = (A*x-b).norm() / b.norm(); double err2 = (x-phi.col(c)).norm() / phi.col(c).norm(); EXPECT_TRUE(err1 < 1e-12) << "err1 = " << err1 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; EXPECT_TRUE(err2 < 1e-12) << "err2 = " << err2 << " | " << skip << " " << it << " " << nlevels << " " << test << endl; } VectorXd b = random(n, nlevels+it+skip+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); if (tols[it] == 0.0) { EXPECT_TRUE(err < 1e-12); } else { EXPECT_TRUE(err < tols[it] * 1e2); } } } } } } printf("\n"); } } /** * Test that the approximations are reasonnable accurate * with and without preservation */ TEST(ApproxTest, Approx) { vector<int> dims = {2, 2, 2, 2, 3, 3}; vector<int> sizes = {5, 10, 20, 128, 5, 15}; vector<double> tols = {0.0, 1e-10, 1e-6, 1e-2, 10}; matrix_hash<VectorXd> hash; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { vector<size_t> allhashes; int count = 0; cout << "Test " << test << "... "; int s = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test+2019); SpMat Arefsym = - Aref; int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) { for(int it = 0; it < tols.size(); it++) { for(int skip = 0; skip < 3; skip++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? Arefsym : Arefunsym)); assert(! c.preserve); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); t.partition(A); t.assemble(A); MatrixXd phi = random(A.rows(), 2, nlevels+it+skip+2019); t.set_tol(tols[it]); t.set_skip(skip); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); t.factorize(); VectorXd b = random(n, nlevels+it+skip+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); auto hb = hash(b); auto hx = hash(x); allhashes.push_back(hb); allhashes.push_back(hx); if (tols[it] == 0.0) { EXPECT_LE(err, 5e-12); } else { EXPECT_LE(err, tols[it] * 2e2); } count++; } } } } size_t h = hashv(allhashes); cout << count << " tested. Overall hash(x,b) = " << h << endl; } } TEST(ApproxTest, ApproxLoRaSp) { vector<int> dims = {2, 2, 2, 2, 3, 3}; vector<int> sizes = {5, 10, 20, 64, 5, 15}; vector<double> tols = {0.0, 1e-10, 1e-6, 1e-4}; matrix_hash<VectorXd> hash; vector<params> configs = get_params(); for(int test = 0; test < dims.size(); test++) { vector<size_t> allhashes; int count = 0; cout << "Test " << test << "... "; int s = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test+2019); int n = pow(s, d); int nlevelsmin = n < 1000 ? 1 : 8; for(int nlevels = nlevelsmin; nlevels < nlevelsmin + 5; nlevels++) { for(int it = 0; it < tols.size(); it++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym)); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_scaling_kind(c.sk); t.partition_lorasp(A); t.assemble(A); MatrixXd phi = random(A.rows(), 2, nlevels+it+2019); t.set_tol(tols[it]); try { t.factorize_lorasp(); VectorXd b = random(n, nlevels+it+2019); auto x = b; t.solve(x); double err = (A*x-b).norm() / b.norm(); auto hb = hash(b); auto hx = hash(x); allhashes.push_back(hb); allhashes.push_back(hx); if (tols[it] == 0.0) { EXPECT_LE(err, 5e-12); } else { EXPECT_LE(err, tols[it] * 2e2); } } catch (exception& ex) { cout << ex.what(); EXPECT_TRUE(false); } count++; } } } size_t h = hashv(allhashes); cout << count << " tested. Overall hash(x,b) = " << h << endl; } } /** * Test that the code produce reproducable results */ TEST(ApproxTest, Repro) { int dims[3] = {2, 2, 2}; int sizes[3] = {20, 64, 16}; double tols[4] = {1e-5, 10, 1e-8, 0.1}; double skips[4] = {1, 2, 0, 1}; int repeat = 10; vector<params> configs = get_params(); for(int test = 0; test < 3; test++) { printf("Tests "); fflush(stdout); int count = 0; int s = sizes[test]; int d = dims[test]; int n = pow(s, d); SpMat Aref = neglapl(s, d); SpMat Arefunsym = neglapl_unsym(s, d, test); for(int nlevels = 5; nlevels < 7; nlevels++) { for(int pr = 0; pr < 6; pr++) { for(auto c: configs) { for(int lrsp = 0; lrsp < 2; lrsp++) { printf("."); fflush(stdout); SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym)); MatrixXd phi = random(A.rows(), 3, test+nlevels+pr+2019); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); if(lrsp == 0) { t.partition(A); } else { t.partition_lorasp(A); } t.assemble(A); t.set_tol(tols[pr]); t.set_skip(skips[pr]); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); if(lrsp == 0) { t.factorize(); } else { t.factorize_lorasp(); } VectorXd b = random(n, nlevels+test); auto xref = b; t.solve(xref); count++; for(int i = 0; i < repeat; i++) { Tree t2(nlevels); t2.set_verb(VERB); t2.set_symm_kind(c.syk); t2.set_part_kind(c.pk); t2.set_scaling_kind(c.sk); if(lrsp == 0) { t2.partition(A); } else { t2.partition_lorasp(A); } t2.assemble(A); t2.set_tol(tols[pr]); t2.set_skip(skips[pr]); t2.set_preserve(c.preserve); t2.set_phi(&phi); if(lrsp == 0) { t2.factorize(); } else { t2.factorize_lorasp(); } auto x = b; t2.solve(x); EXPECT_EQ((xref - x).norm(), 0.0); } } } } } printf(": %d tested.\n", count); fflush(stdout); } } TEST(Run, Many) { vector<int> dims = {2, 2, 2, 3, 3, 3 }; vector<int> sizes = {5, 16, 64, 5, 10, 15}; vector<double> tols = {0.0, 1e-2, 1.0, 10.0}; RUN_MANY = RUN_MANY > dims.size() ? dims.size() : RUN_MANY; matrix_hash<VectorXd> hash; vector<size_t> allhashes; vector<params> configs = get_params(); for(int test = 0; test < RUN_MANY; test++) { cout << "Run " << test << "... \n"; int count = 0; int n = sizes[test]; int d = dims[test]; SpMat Aref = neglapl(n, d); SpMat Arefunsym = neglapl_unsym(n, d, test); int N = Aref.rows(); int nlevelsmin = N < 1000 ? 1 : 8; for(int nlevels = nlevelsmin; nlevels < nlevelsmin+3; nlevels++) { for(double tol : tols) { for(int skip = 0; skip < 3; skip++) { for(int geo = 0; geo < 2; geo++) { for(auto c: configs) { SpMat A = (c.syk == SymmKind::SPD ? Aref : (c.syk == SymmKind::SYM ? (-Aref) : Arefunsym)); MatrixXd phi = random(A.rows(), 3, test+nlevels+2019); MatrixXd X = linspace_nd(n, d); Tree t(nlevels); t.set_verb(VERB); t.set_symm_kind(c.syk); t.set_part_kind(c.pk); t.set_scaling_kind(c.sk); t.set_use_geo(geo); t.set_Xcoo(&X); t.set_tol(tol); t.set_skip(skip); t.set_preserve(c.preserve); if(c.preserve) t.set_phi(&phi); t.partition(A); t.assemble(A); t.factorize(); VectorXd b = random(N, nlevels+test); auto x = b; t.solve(x); double res = (A*x-b).norm() / b.norm(); auto h = hash(x); allhashes.push_back(h); printf("%6d %4d %d] %3d %3.2e %d %d %d %d %d %d %d %d | %3.2e | %lu\n", N, n, d, nlevels, tol, skip, geo, c.preserve, int(c.syk), int(c.pk), int(c.sk), 1, 1, res, h); count++; } } } } } cout << "Ran " << count << " tests\n"; size_t h = hashv(allhashes); cout << "Overall hash so far: " << h << endl; } size_t h = hashv(allhashes); cout << "Overall hash: " << h << endl; } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); cxxopts::Options options("spaND tests", "Test suite for the spaND algorithms."); options.add_options() ("help", "Print help") ("v,verb", "Verbose (default: false)", cxxopts::value<bool>()->default_value("false")) ("n_threads", "Number of threads", cxxopts::value<int>()->default_value("4")) ("run", "How many Run.Many to run", cxxopts::value<int>()->default_value("4")) ; auto result = options.parse(argc, argv); if (result.count("help")) { cout << options.help({"", "Group"}) << endl; exit(0); } VERB = result["verb"].as<bool>(); N_THREADS = result["n_threads"].as<int>(); RUN_MANY = result["run"].as<int>(); cout << "n_threads: " << N_THREADS << endl; cout << "verb: " << VERB << endl; cout << "run: " << RUN_MANY << endl; return RUN_ALL_TESTS(); }
38.526171
150
0.420307
leopoldcambier
da81b258e5dc04a7f321af81e570619d695af003
2,531
cpp
C++
COMToys/src/MfcModule.cpp
skst/Timekeeper
4aba38fe891cd8681f2ef290d47a147e2fef5f29
[ "MIT" ]
4
2021-05-28T03:27:21.000Z
2022-02-17T02:09:16.000Z
COMToys/src/MfcModule.cpp
skst/Timekeeper
4aba38fe891cd8681f2ef290d47a147e2fef5f29
[ "MIT" ]
2
2021-05-03T20:00:53.000Z
2021-10-31T16:05:39.000Z
COMToys/src/MfcModule.cpp
skst/Timekeeper
4aba38fe891cd8681f2ef290d47a147e2fef5f29
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////// // ComToys(TM) Copyright 1999 Paul DiLascia // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // #include "StdAfx.h" #include "COMtoys/ComToys.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNAMIC(CTMfcModule, COleControlModule); CTMfcModule::CTMfcModule() { } CTMfcModule::~CTMfcModule() { } BOOL CTMfcModule::InitInstance() { CTTRACEFN(_T(__FUNCTION__) _T("\n")); //skst /* CTRegistrar uses IRegistrar--a completely undocumented ATL interface. What's also undocumented is that it requires atl.dll, which is not present on Windows 98 with IE 5.0. It is present after we install IE 6.0. Who knows about IE 5.5? Thanks, Microsoft. */ CTTRACE(_T("\tbefore CTRegistrar ctor\n")); CTRegistrar r; CTTRACE(_T("\tafter CTRegistrar ctor\n")); if (!r) { ::AfxMessageBox(_T("This requires Microsoft Internet Explorer 6.0.")); return FALSE; } //skst if (!CTModule::InitInstance(CWinApp::m_hInstance)) return FALSE; return COleControlModule::InitInstance(); } int CTMfcModule::ExitInstance() { CTTRACEFN(_T("CTMfcModule::ExitInstance\n")); CTModule::ExitInstance(); return COleControlModule::ExitInstance(); } ///////////////////////////////////////////////////////////////////////////// // Implementation special DLL entry points. // Call MFC to do the work. HRESULT CTMfcModule::OnGetClassObject(REFCLSID clsid, REFIID iid, LPVOID* ppv) { CTTRACEFN(_T("CTMfcModule::OnGetClassObject\n")); HRESULT hr = AfxDllGetClassObject(clsid, iid, ppv); if (*ppv==NULL) { TRACE(_T("***CTMfcModule::OnGetClassObject failed\n")); TRACE(_T("***Did you create factories before calling CTMfcModule::InitInstance?\n")); } return hr; } HRESULT CTMfcModule::OnCanUnloadNow(void) { CTTRACEFN(_T("CTMfcModule::OnCanUnloadNow\n")); return AfxDllCanUnloadNow(); } HRESULT CTMfcModule::OnRegisterServer(BOOL bRegister) { CTTRACEFN(_T("CTMfcModule::OnRegisterServer\n")); HRESULT hr =CTModule::OnRegisterServer(bRegister); if (hr!=S_OK) return hr; return COleObjectFactory::UpdateRegistryAll(bRegister) ? S_OK : SELFREG_E_CLASS; } HRESULT CTMfcModule::OnInstall(BOOL bInstall, LPCWSTR pszCmdLine) { CTTRACEFN(_T("CTMfcModule::OnInstall\n")); return CTModule::OnInstall(bInstall, pszCmdLine); }
26.642105
88
0.657053
skst
da8713d45b134a834101c7b33493fbe16708ffaf
2,927
cpp
C++
DialogTools/GetisOrdChoiceDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
DialogTools/GetisOrdChoiceDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
DialogTools/GetisOrdChoiceDlg.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
/** * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved * * This file is part of GeoDa. * * GeoDa 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. * * GeoDa 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/>. */ #include <wx/xrc/xmlres.h> #include "../logger.h" #include "GetisOrdChoiceDlg.h" BEGIN_EVENT_TABLE( GetisOrdChoiceDlg, wxDialog ) EVT_BUTTON( wxID_OK, GetisOrdChoiceDlg::OnOkClick ) EVT_RADIOBUTTON( XRCID("IDC_W_ROW_STAND"), GetisOrdChoiceDlg::OnRadioWStand ) EVT_RADIOBUTTON( XRCID("IDC_W_BINARY"), GetisOrdChoiceDlg::OnRadioWBinary ) END_EVENT_TABLE() GetisOrdChoiceDlg::GetisOrdChoiceDlg( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { SetParent(parent); CreateControls(); Centre(); row_standardize_weights = true; } void GetisOrdChoiceDlg::CreateControls() { wxXmlResource::Get()->LoadDialog(this, GetParent(), "IDD_GETIS_ORD_CHOICE"); gi_clus_map_perm_check = wxDynamicCast(FindWindow(XRCID("IDC_GI_CHECK")), wxCheckBox); gi_star_clus_map_perm_check = wxDynamicCast(FindWindow(XRCID("IDC_GI_STAR_CHECK")), wxCheckBox); show_sig_map_check = wxDynamicCast(FindWindow(XRCID("IDC_SIG_MAPS_CHECK")), wxCheckBox); show_norm_pval_check = wxDynamicCast(FindWindow(XRCID("IDC_NORM_P_VAL_CHECK")), wxCheckBox); w_row_standardize = wxDynamicCast(FindWindow(XRCID("IDC_W_ROW_STAND")), wxRadioButton); w_binary = wxDynamicCast(FindWindow(XRCID("IDC_W_BINARY")), wxRadioButton); } void GetisOrdChoiceDlg::OnOkClick( wxCommandEvent& event ) { bool gi = gi_clus_map_perm_check->GetValue() == 1; bool gi_star = gi_star_clus_map_perm_check->GetValue() == 1; bool sig_map = show_sig_map_check->GetValue() == 1; bool norm_pval = show_norm_pval_check->GetValue() == 1; Gi_ClustMap_norm = norm_pval && gi; Gi_SigMap_norm = norm_pval && gi && sig_map; GiStar_ClustMap_norm = norm_pval && gi_star; GiStar_SigMap_norm = norm_pval && gi_star && sig_map; Gi_ClustMap_perm = gi; Gi_SigMap_perm = gi && sig_map; GiStar_ClustMap_perm = gi_star; GiStar_SigMap_perm = gi_star && sig_map; row_standardize_weights = w_row_standardize->GetValue() == 1; event.Skip(); EndDialog(wxID_OK); } void GetisOrdChoiceDlg::OnRadioWStand( wxCommandEvent& event ) { } void GetisOrdChoiceDlg::OnRadioWBinary( wxCommandEvent& event ) { }
31.138298
80
0.74479
chenyoujie
da893fc9e70304f1ab28d7209ee1b5c92a4589df
2,252
cpp
C++
tutorial/message/message_server.cpp
TencentOpen/Pebble
0f32f94db47b3bc1955ac2843bfa10372eeba1fb
[ "BSD-2-Clause" ]
233
2016-05-12T02:28:44.000Z
2020-08-24T18:11:49.000Z
tutorial/message/message_server.cpp
TencentOpen/Pebble
0f32f94db47b3bc1955ac2843bfa10372eeba1fb
[ "BSD-2-Clause" ]
1
2016-06-07T04:18:16.000Z
2016-06-07T06:09:08.000Z
tutorial/message/message_server.cpp
TencentOpen/Pebble
0f32f94db47b3bc1955ac2843bfa10372eeba1fb
[ "BSD-2-Clause" ]
116
2016-05-24T10:55:49.000Z
2019-11-24T06:57:08.000Z
/* * Tencent is pleased to support the open source community by making Pebble available. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ #include <stdlib.h> #include "source/message/http_driver.h" #include "source/message/message.h" #include "source/message/tcp_driver.h" using namespace std; using namespace pebble::net; #define CHECK(e) \ if ((e) != 0) {\ printf("file:%s, line:%d, error:%s\n", __FILE__, __LINE__, Message::LastErrorMessage());\ exit(1);\ } int on_message(int handle, const char *msg, size_t msg_len, uint64_t addr) { string str(msg, msg_len); printf("server handle:%d, msg:%s, len:%d\n", handle, str.c_str(), static_cast<int>(msg_len)); char ret_msg[512]; int ret_n = snprintf(ret_msg, sizeof(ret_msg), "your msg=%s", str.c_str()); CHECK(Message::SendTo(handle, ret_msg, ret_n, addr)); return 0; } int main(int argc, char **argv) { if (argc != 2) { printf("usage:%s tbusd_address(eg.:udp://127.0.0.1:11599)\n", argv[0]); exit(1); } HttpDriver driver3; CHECK(driver3.Init()); Message::RegisterDriver(&driver3); TcpDriver driver4; CHECK(driver4.Init()); Message::RegisterDriver(&driver4); int handle4 = Message::NewHandle(); CHECK(Message::Bind(handle4, "http://0.0.0.0:8250")); int handle5 = Message::NewHandle(); CHECK(Message::Bind(handle5, "tcp://0.0.0.0:8260")); printf("handle4:%d, handle5:%d\n", handle4, handle5); NetEventCallbacks net_event_callbacks; net_event_callbacks.on_message = on_message; while (true) { Message::Poll(net_event_callbacks, 100); usleep(100); } return 0; }
30.849315
100
0.667407
TencentOpen
da89c8934244a95ce9a950cdd8a37b003bbea530
333
cpp
C++
ProjectEuler/fibonacci.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
3
2020-10-19T10:03:20.000Z
2021-12-18T20:39:31.000Z
ProjectEuler/fibonacci.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
null
null
null
ProjectEuler/fibonacci.cpp
MFathirIrhas/ProgrammingChallenges
8c67bd71212a1941e5bcc0463095285859afa04d
[ "MIT" ]
null
null
null
/* Sum all even numbers of fibonacci until 4000000 */ #include <iostream> using namespace std; int main(){ int a = 0; int b = 1; int c; int sum = 0; do{ c = a + b; a = b; b = c; if(b % 2 == 0) //check if number is even sum += b; }while(b <= 4000000); cout << sum; //return sum of all even number return 0; }
12.807692
48
0.564565
MFathirIrhas
da9851cebef7ce2a96a6a97705266be324bf4867
9,422
hpp
C++
cartesian_trajectory_controller/include/cartesian_trajectory_controller/cartesian_trajectory_controller.hpp
christianlandgraf/Universal_Robots_ROS_controllers_cartesian
987e4539af011292b5b34c7f891fe9f274e00ddd
[ "Apache-2.0" ]
12
2021-06-09T15:05:28.000Z
2022-02-16T11:14:16.000Z
cartesian_trajectory_controller/include/cartesian_trajectory_controller/cartesian_trajectory_controller.hpp
christianlandgraf/Universal_Robots_ROS_controllers_cartesian
987e4539af011292b5b34c7f891fe9f274e00ddd
[ "Apache-2.0" ]
7
2021-08-03T10:06:13.000Z
2022-03-25T22:58:28.000Z
cartesian_trajectory_controller/include/cartesian_trajectory_controller/cartesian_trajectory_controller.hpp
christianlandgraf/Universal_Robots_ROS_controllers_cartesian
987e4539af011292b5b34c7f891fe9f274e00ddd
[ "Apache-2.0" ]
5
2021-06-21T06:21:52.000Z
2022-03-02T14:52:40.000Z
// -- BEGIN LICENSE BLOCK ---------------------------------------------- // Copyright 2020 FZI Forschungszentrum Informatik // Created on behalf of Universal Robots A/S // // 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. // -- END LICENSE BLOCK ------------------------------------------------ //----------------------------------------------------------------------------- /*!\file cartesian_trajectory_controller.hpp * * \author Stefan Scherzinger <[email protected]> * \date 2021/01/24 * */ //----------------------------------------------------------------------------- #include <cartesian_trajectory_controller/cartesian_trajectory_controller.h> #include "hardware_interface/robot_hw.h" namespace cartesian_trajectory_controller { template <class HWInterface> bool CartesianTrajectoryController<HWInterface>::init(hardware_interface::RobotHW* hw, ros::NodeHandle& nh, ros::NodeHandle& controller_nh) { if (!ControlPolicy::init(hw, nh, controller_nh)) { return false; } // Use speed scaling interface if available auto speed_scaling_interface = hw->get<scaled_controllers::SpeedScalingInterface>(); if (!speed_scaling_interface) { ROS_INFO_STREAM(controller_nh.getNamespace() << ": Your RobotHW seems not to provide speed scaling. Starting " "without this feature."); speed_scaling_ = nullptr; } else { speed_scaling_ = std::make_unique<scaled_controllers::SpeedScalingHandle>(speed_scaling_interface->getHandle("speed" "_scal" "ing_" "facto" "r")); } // Action server action_server_.reset(new actionlib::SimpleActionServer<cartesian_control_msgs::FollowCartesianTrajectoryAction>( controller_nh, "follow_cartesian_trajectory", std::bind(&CartesianTrajectoryController::executeCB, this, std::placeholders::_1), false)); action_server_->registerPreemptCallback(std::bind(&CartesianTrajectoryController::preemptCB, this)); action_server_->start(); return true; } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::starting(const ros::Time& time) { // Start where we are ControlPolicy::updateCommand(ControlPolicy::getState()); } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::stopping(const ros::Time& time) { if (action_server_->isActive()) { // Set canceled flag in the action result action_server_->setPreempted(); } } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::update(const ros::Time& time, const ros::Duration& period) { if (action_server_->isActive() && !done_.load()) { // Apply speed scaling if available. const double factor = (speed_scaling_) ? *speed_scaling_->getScalingFactor() : 1.0; trajectory_duration_.now += period * factor; // Sample the Cartesian trajectory's target state and command that to // the control policy. if (trajectory_duration_.now < trajectory_duration_.end) { std::lock_guard<std::mutex> lock_trajectory(lock_); ros_controllers_cartesian::CartesianState desired; trajectory_.sample(trajectory_duration_.now.toSec(), desired); ControlPolicy::updateCommand(desired); // Give feedback auto actual = ControlPolicy::getState(); auto error = desired - actual; cartesian_control_msgs::FollowCartesianTrajectoryFeedback f; auto now = trajectory_duration_.now.toSec(); f.desired = desired.toMsg(now); f.actual = actual.toMsg(now); f.error = error.toMsg(now); action_server_->publishFeedback(f); // Check tolerances and set terminal conditions for the // action server if special criteria are met. monitorExecution(error); } else // Time is up. Check goal tolerances and set terminal state. { timesUp(); } } } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::executeCB( const cartesian_control_msgs::FollowCartesianTrajectoryGoalConstPtr& goal) { // Upon entering this callback, the simple action server has already // preempted the previously active goal (if any) and has accepted the new goal. if (!this->isRunning()) { ROS_ERROR("Can't accept new action goals. Controller is not running."); cartesian_control_msgs::FollowCartesianTrajectoryResult result; result.error_code = cartesian_control_msgs::FollowCartesianTrajectoryResult::INVALID_GOAL; action_server_->setAborted(result); return; } path_tolerances_ = goal->path_tolerance; goal_tolerances_ = goal->goal_tolerance; // Start where we are by adding the current state as first trajectory // waypoint. auto state = ControlPolicy::getState(); { std::lock_guard<std::mutex> lock_trajectory(lock_); cartesian_control_msgs::CartesianTrajectory traj = goal->trajectory; traj.points.insert(traj.points.begin(), state.toMsg(0)); // start time zero if (!trajectory_.init(traj)) { ROS_ERROR("Action goal has invalid trajectory."); cartesian_control_msgs::FollowCartesianTrajectoryResult result; result.error_code = cartesian_control_msgs::FollowCartesianTrajectoryResult::INVALID_GOAL; action_server_->setAborted(result); return; } } // Time keeping trajectory_duration_.now = ros::Duration(0.0); trajectory_duration_.end = goal->trajectory.points.back().time_from_start + goal->goal_time_tolerance; done_ = false; while (!done_.load()) { ros::Duration(0.01).sleep(); } } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::preemptCB() { cartesian_control_msgs::FollowCartesianTrajectoryResult result; result.error_string = "preempted"; action_server_->setPreempted(result); done_ = true; } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::timesUp() { using Result = cartesian_control_msgs::FollowCartesianTrajectoryResult; Result result; // When time is over, sampling gives us the last waypoint. ros_controllers_cartesian::CartesianState goal; { std::lock_guard<std::mutex> lock_trajectory(lock_); trajectory_.sample(trajectory_duration_.now.toSec(), goal); } // TODO: What should happen when speed scaling was active? // Only check position and orientation in that case? // Address this once we know more edge cases during beta testing. // Check if goal was reached. // Abort if any of the dimensions exceeds its goal tolerance auto error = goal - ControlPolicy::getState(); if (!withinTolerances(error, goal_tolerances_)) { result.error_code = Result::GOAL_TOLERANCE_VIOLATED; action_server_->setAborted(result); } else // Succeed { result.error_code = Result::SUCCESSFUL; action_server_->setSucceeded(result); } done_ = true; } template <class HWInterface> void CartesianTrajectoryController<HWInterface>::monitorExecution( const ros_controllers_cartesian::CartesianState& error) { if (!withinTolerances(error, path_tolerances_)) { using Result = cartesian_control_msgs::FollowCartesianTrajectoryResult; Result result; result.error_code = Result::PATH_TOLERANCE_VIOLATED; action_server_->setAborted(result); done_ = true; } } template <class HWInterface> bool CartesianTrajectoryController<HWInterface>::withinTolerances( const ros_controllers_cartesian::CartesianState& error, const cartesian_control_msgs::CartesianTolerance& tolerance) { // Uninitialized tolerances do not need checking cartesian_control_msgs::CartesianTolerance uninitialized; std::stringstream str_1; std::stringstream str_2; str_1 << tolerance; str_2 << uninitialized; if (str_1.str() == str_2.str()) { return true; } auto not_within_limits = [](const auto& a, const auto& b) { return a.x() > b.x || a.y() > b.y || a.z() > b.z; }; // Check each individual dimension separately. if (not_within_limits(error.p, tolerance.position_error) || not_within_limits(error.rot(), tolerance.orientation_error) || not_within_limits(error.v, tolerance.twist_error.linear) || not_within_limits(error.w, tolerance.twist_error.angular) || not_within_limits(error.v_dot, tolerance.acceleration_error.linear) || not_within_limits(error.w_dot, tolerance.acceleration_error.angular)) { return false; } return true; } } // namespace cartesian_trajectory_controller
34.639706
120
0.674061
christianlandgraf
da98c63af88cc4832c59e649e342539bbdde2ab3
3,285
cpp
C++
src/main.cpp
gustavosinbandera1/mongoose_os_esp32_http_server
97a491e606b0508dbee37bf0ecdb91ae46e903be
[ "Apache-2.0" ]
null
null
null
src/main.cpp
gustavosinbandera1/mongoose_os_esp32_http_server
97a491e606b0508dbee37bf0ecdb91ae46e903be
[ "Apache-2.0" ]
null
null
null
src/main.cpp
gustavosinbandera1/mongoose_os_esp32_http_server
97a491e606b0508dbee37bf0ecdb91ae46e903be
[ "Apache-2.0" ]
null
null
null
#include "mgos.h" #include "mgos_mqtt.h" #include "mgos_wifi.h" static void timer_cb(void *arg) { static bool s_tick_tock = false; LOG(LL_INFO, ("%s uptime: %.2lf, RAM: %lu, %lu free", (s_tick_tock ? "Tick" : "Tock"), mgos_uptime(), (unsigned long) mgos_get_heap_size(), (unsigned long) mgos_get_free_heap_size())); s_tick_tock = !s_tick_tock; (void) arg; } static void wifi_cb(int ev, void *evd, void *arg) { switch (ev) { case MGOS_WIFI_EV_STA_DISCONNECTED: { struct mgos_wifi_sta_disconnected_arg *da = (struct mgos_wifi_sta_disconnected_arg *) evd; LOG(LL_INFO, ("WiFi STA disconnected, reason %d", da->reason)); break; } case MGOS_WIFI_EV_STA_CONNECTING: LOG(LL_INFO, ("WiFi STA connecting %p", arg)); break; case MGOS_WIFI_EV_STA_CONNECTED: LOG(LL_INFO, ("WiFi STA connected %p", arg)); break; case MGOS_WIFI_EV_STA_IP_ACQUIRED: LOG(LL_INFO, ("WiFi STA IP acquired %p", arg)); break; case MGOS_WIFI_EV_AP_STA_CONNECTED: { struct mgos_wifi_ap_sta_connected_arg *aa = (struct mgos_wifi_ap_sta_connected_arg *) evd; LOG(LL_INFO, ("WiFi AP STA connected MAC %02x:%02x:%02x:%02x:%02x:%02x", aa->mac[0], aa->mac[1], aa->mac[2], aa->mac[3], aa->mac[4], aa->mac[5])); break; } case MGOS_WIFI_EV_AP_STA_DISCONNECTED: { struct mgos_wifi_ap_sta_disconnected_arg *aa = (struct mgos_wifi_ap_sta_disconnected_arg *) evd; LOG(LL_INFO, ("WiFi AP STA disconnected MAC %02x:%02x:%02x:%02x:%02x:%02x", aa->mac[0], aa->mac[1], aa->mac[2], aa->mac[3], aa->mac[4], aa->mac[5])); break; } } (void) arg; } static void button_cb(int pin, void *arg) { char topic[100]; snprintf(topic, sizeof(topic), "/devices/%s/events", mgos_sys_config_get_device_id()); bool res = mgos_mqtt_pubf(topic, 0, false /* retain */, "{total_ram: %lu, free_ram: %lu}", (unsigned long) mgos_get_heap_size(), (unsigned long) mgos_get_free_heap_size()); char buf[8]; LOG(LL_INFO, ("Pin: %s, published: %s", mgos_gpio_str(pin, buf), res ? "yes" : "no")); (void) arg; } extern "C" enum mgos_app_init_result mgos_app_init(void) { char buf[8]; /* Simple repeating timer */ mgos_set_timer(1000, MGOS_TIMER_REPEAT, timer_cb, NULL); /* Publish to MQTT on button press */ int btn_pin = mgos_sys_config_get_board_btn1_pin(); if (btn_pin >= 0) { enum mgos_gpio_pull_type btn_pull; enum mgos_gpio_int_mode btn_int_edge; if (mgos_sys_config_get_board_btn1_pull_up()) { btn_pull = MGOS_GPIO_PULL_UP; btn_int_edge = MGOS_GPIO_INT_EDGE_NEG; } else { btn_pull = MGOS_GPIO_PULL_DOWN; btn_int_edge = MGOS_GPIO_INT_EDGE_POS; } LOG(LL_INFO, ("Button pin %s, active %s", mgos_gpio_str(btn_pin, buf), (mgos_sys_config_get_board_btn1_pull_up() ? "low" : "high"))); mgos_gpio_set_button_handler(btn_pin, btn_pull, btn_int_edge, 20, button_cb, NULL); } mgos_event_add_group_handler(MGOS_WIFI_EV_BASE, wifi_cb, NULL); return MGOS_APP_INIT_SUCCESS; }
33.865979
80
0.625571
gustavosinbandera1
daa652bebe679c616aa8e046a2b8f83d4b59e5f8
400
hpp
C++
src/Application.hpp
Thomas-Zorroche/Oryon
54237355055b262110346b33023d3cab63124fc0
[ "MIT" ]
null
null
null
src/Application.hpp
Thomas-Zorroche/Oryon
54237355055b262110346b33023d3cab63124fc0
[ "MIT" ]
null
null
null
src/Application.hpp
Thomas-Zorroche/Oryon
54237355055b262110346b33023d3cab63124fc0
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "Window.hpp" #include "Editor/Editor.hpp" #include "Events/Event.hpp" namespace oryon { class Application { public: Application(int argc, char** argv); Window& getWindow() { return * _window; } void run(); void onEvent(Event& e); private: std::unique_ptr<Window> _window = nullptr; std::unique_ptr<Editor> _editor = nullptr; }; }
12.5
44
0.6725
Thomas-Zorroche
daa7b48131608c28dadc74dc66c423d09fde1596
614
cpp
C++
Source.cpp
usamashafiq/print_right_triangle
78f7ae74ed2672235648793ba4ffc9f3d679a5ea
[ "MIT" ]
null
null
null
Source.cpp
usamashafiq/print_right_triangle
78f7ae74ed2672235648793ba4ffc9f3d679a5ea
[ "MIT" ]
null
null
null
Source.cpp
usamashafiq/print_right_triangle
78f7ae74ed2672235648793ba4ffc9f3d679a5ea
[ "MIT" ]
null
null
null
#include<iostream> #include<conio.h> using namespace std; void print_right_triangle(int, char = '*'); void main() { int a; char c,q; cout << "Enter a size " << endl; cin >> a; cout << "you want to enter char ans in (Y/N) " << endl; cin >> c; if (c == 'y'||c=='Y') { cout << "Enter a char '@,#,$,%' " << endl; cin >> q; print_right_triangle(a, q); } else { print_right_triangle(a); } _getch(); } void print_right_triangle(int a, char b) { for (int i = a; i >= 1; i--) { for (int j = a; j>i; j--) { cout << b; } cout << "\n"; } }
14.97561
59
0.486971
usamashafiq
daaa486a8d57cd530b323a1ffb7865177cae4357
3,168
cpp
C++
UnitTest/LibTest/sdl_test.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
UnitTest/LibTest/sdl_test.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
UnitTest/LibTest/sdl_test.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdint.h> #include <assert.h> #include <iostream> #include <iomanip> #define SDL_MAIN_HANDLED #include <SDL2/SDL.h> #include <glad/glad.h> #include <SDL2/SDL_opengl.h> //#include <GL/gl.h> typedef int32_t i32; typedef uint32_t u32; typedef int32_t b32; #define WinWidth 1280 #define WinHeight 720 int main(int argc, char* argv[]) { // int context_flags = SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG | SDL_GL_CONTEXT_DEBUG_FLAG; // SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, context_flags); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); // SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); // SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); // SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); u32 WindowFlags = SDL_WINDOW_OPENGL; SDL_Window *Window = SDL_CreateWindow("OpenGL Test", 0, 0, WinWidth, WinHeight, WindowFlags); assert(Window); SDL_GLContext Context = SDL_GL_CreateContext(Window); SDL_GL_MakeCurrent(Window, Context); if (!gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } std::cout << std::setw(34) << std::left << "OpenGL Version: " << GLVersion.major << "." << GLVersion.minor << std::endl; std::cout << std::setw(34) << std::left << "OpenGL Shading Language Version: " << (char *)glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; std::cout << std::setw(34) << std::left << "OpenGL Vendor:" << (char *)glGetString(GL_VENDOR) << std::endl; std::cout << std::setw(34) << std::left << "OpenGL Renderer:" << (char *)glGetString(GL_RENDERER) << std::endl; b32 Running = 1; b32 FullScreen = 0; while (Running) { SDL_Event Event; while (SDL_PollEvent(&Event)) { if (Event.type == SDL_KEYDOWN) { switch (Event.key.keysym.sym) { case SDLK_ESCAPE: Running = 0; break; case 'f': FullScreen = !FullScreen; if (FullScreen) { SDL_SetWindowFullscreen(Window, WindowFlags | SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowFullscreen(Window, WindowFlags); } break; default: break; } } else if (Event.type == SDL_QUIT) { Running = 0; } } glViewport(0, 0, WinWidth, WinHeight); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); SDL_GL_SwapWindow(Window); } return 0; }
34.064516
148
0.591856
rocketman123456
daab8cab39a6a8016de0c4dc9b727ff4756cbae1
6,616
cxx
C++
Libraries/ITK/Testing/Segmentation/MIDASIrregularVolumeEditor/itkMIDASRegionOfInterestCalculatorTest.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
Libraries/ITK/Testing/Segmentation/MIDASIrregularVolumeEditor/itkMIDASRegionOfInterestCalculatorTest.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
Libraries/ITK/Testing/Segmentation/MIDASIrregularVolumeEditor/itkMIDASRegionOfInterestCalculatorTest.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include <memory> #include <math.h> #include <itkImage.h> #include <itkMIDASHelper.h> #include <itkMIDASRegionOfInterestCalculator.h> /** * Basic tests for itkMIDASRegionOfInterestCalculator */ int itkMIDASRegionOfInterestCalculatorTest(int argc, char * argv[]) { typedef itk::Image<unsigned char, 3> ImageType; typedef itk::MIDASRegionOfInterestCalculator<unsigned char, 3> CalculatorType; typedef ImageType::RegionType RegionType; typedef ImageType::SizeType SizeType; typedef ImageType::IndexType IndexType; /********************************************************** * Normal, default ITK image, should be RAI * i.e. * 1 0 0 * 0 1 0 == RAI * 0 0 1 **********************************************************/ CalculatorType::Pointer calculator = CalculatorType::New(); //calculator->DebugOn(); ImageType::Pointer image = ImageType::New(); std::string orientation = calculator->GetOrientationString(image); if (orientation != "RAI") { std::cerr << "Expected RAI, but got:" << orientation << " from direction=\n" << image->GetDirection() << std::endl; return EXIT_FAILURE; } int axis = calculator->GetAxis(image, itk::ORIENTATION_AXIAL); if (axis != 2) { std::cerr << "Expected 2, but got:" << axis << std::endl; return EXIT_FAILURE; } axis = calculator->GetAxis(image, itk::ORIENTATION_SAGITTAL); if (axis != 0) { std::cerr << "Expected 0, but got:" << axis << std::endl; return EXIT_FAILURE; } axis = calculator->GetAxis(image, itk::ORIENTATION_CORONAL); if (axis != 1) { std::cerr << "Expected 1, but got:" << axis << std::endl; return EXIT_FAILURE; } int direction = 0; direction = calculator->GetPlusOrUpDirection(image, itk::ORIENTATION_AXIAL); if (direction != -1) { std::cerr << "Expected -1, but got:" << direction << std::endl; return EXIT_FAILURE; } direction = calculator->GetPlusOrUpDirection(image, itk::ORIENTATION_SAGITTAL); if (direction != -1) { std::cerr << "Expected -1, but got:" << direction << std::endl; return EXIT_FAILURE; } direction = calculator->GetPlusOrUpDirection(image, itk::ORIENTATION_CORONAL); if (direction != -1) { std::cerr << "Expected -1, but got:" << direction << std::endl; return EXIT_FAILURE; } SizeType size; size.Fill(256); IndexType voxelIndex; voxelIndex.Fill(0); RegionType region; region.SetSize(size); region.SetIndex(voxelIndex); image->SetRegions(region); image->Allocate(); image->FillBuffer(0); region = calculator->GetPlusOrUpRegion(image, itk::ORIENTATION_AXIAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 256 || size[2] != 10 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 256, 10, 0, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetMinusOrDownRegion(image, itk::ORIENTATION_AXIAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 256 || size[2] != 245 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 11) { std::cerr << "Expected 256, 256, 245, 0, 0, 11, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetPlusOrUpRegion(image, itk::ORIENTATION_CORONAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 10 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 10, 256, 0, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetMinusOrDownRegion(image, itk::ORIENTATION_CORONAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 245 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 11 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 245, 256, 0, 11, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetPlusOrUpRegion(image, itk::ORIENTATION_SAGITTAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 10 || size[1] != 256 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 10, 256, 256, 0, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetMinusOrDownRegion(image, itk::ORIENTATION_SAGITTAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 245 || size[1] != 256 || size[2] != 256 || voxelIndex[0] != 11 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 245, 256, 256, 11, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetSliceRegion(image, itk::ORIENTATION_AXIAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 256 || size[2] != 1 || voxelIndex[0] != 0 || voxelIndex[1] != 0 || voxelIndex[2] != 10) { std::cerr << "Expected 256, 256, 1, 0, 0, 10, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetSliceRegion(image, itk::ORIENTATION_CORONAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 256 || size[1] != 1 || size[2] != 256 || voxelIndex[0] != 0 || voxelIndex[1] != 10 || voxelIndex[2] != 0) { std::cerr << "Expected 256, 1, 256, 0, 10, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } region = calculator->GetSliceRegion(image, itk::ORIENTATION_SAGITTAL, 10); size = region.GetSize(); voxelIndex = region.GetIndex(); if (size[0] != 1 || size[1] != 256 || size[2] != 256 || voxelIndex[0] != 10 || voxelIndex[1] != 0 || voxelIndex[2] != 0) { std::cerr << "Expected 1, 256, 256, 10, 0, 0, but got:\n" << region << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
32.273171
124
0.60792
NifTK
daacc621b1123920e28327f57cac176717cd58d1
48
cpp
C++
Engine.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Engine.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
Engine.cpp
KarmaiSAYIn/recapp
c1a968214b4cf1b4d8befd1c72bedf64e1fc0813
[ "BSD-3-Clause" ]
null
null
null
#define OLC_PGE_APPLICATION #include "Engine.h"
16
27
0.8125
KarmaiSAYIn
dab0bfa6f03f9278a999b2e413f4be4e110e997b
384
hpp
C++
graphics/Axis.hpp
theoden8/plot
ff69782d43b45bf5f4f95ee3f79a08fd9ce0bed3
[ "WTFPL" ]
null
null
null
graphics/Axis.hpp
theoden8/plot
ff69782d43b45bf5f4f95ee3f79a08fd9ce0bed3
[ "WTFPL" ]
null
null
null
graphics/Axis.hpp
theoden8/plot
ff69782d43b45bf5f4f95ee3f79a08fd9ce0bed3
[ "WTFPL" ]
null
null
null
#pragma once #include "Types.hpp" struct axis { real_t winsize, gridsize, shift, thickness; real_t lborder, rborder; private: void reborder(); public: axis(real_t winsize, real_t thickness, real_t shift = 0.); real_t bold() const; void set_grid(real_t diff); void set_shift(real_t diff); void set_size(real_t newsize); bool in_grid(const real_t &val) const; };
16
59
0.713542
theoden8
dab8bade4524f62efde33035a7c18b38a05d091a
1,300
cc
C++
libmat/test/src/test_reItr_all.cc
stiegerc/winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
2
2020-10-06T09:14:23.000Z
2020-11-25T06:08:54.000Z
libmat/test/src/test_reItr_all.cc
stiegerc/Winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
1
2020-12-23T04:20:33.000Z
2020-12-23T04:20:33.000Z
libmat/test/src/test_reItr_all.cc
stiegerc/Winterface
b6d501df1d0c015f2cd7126ac6b4e746d541c80c
[ "BSD-2-Clause" ]
1
2020-07-14T13:53:32.000Z
2020-07-14T13:53:32.000Z
// 2014-2019, ETH Zurich, Integrated Systems Laboratory // Authors: Christian Stieger #include "testTools.h" #include "test_cpxItr_all.h" #include "test_cpxItr_all.cc" using namespace lm__; // tests template<> void test_cpxItr_all<0>::test_all_dereference() { // c_reItr { // lambda to generate const random range auto gen = [](const size_t L) -> const CPX__* { CPX__* res = new CPX__ [L]; rnd(res,L); return res; }; const size_t L = genRndST(); const CPX__* rg = gen(L); c_reItr tItr(rg,1); for (size_t i=0; i!=L; ++i,++tItr) CPPUNIT_ASSERT_EQUAL(std::real(rg[i]),*tItr); delete[] rg; } // reItr { // lambda to generate const random range auto gen = [](const size_t L) -> CPX__* { CPX__* res = new CPX__ [L]; rnd(res,L); return res; }; const size_t L = genRndST(); CPX__* rg = gen(L); reItr tItr(rg,1); for (size_t i=0; i!=L; ++i,++tItr) { CPPUNIT_ASSERT_EQUAL(std::real(rg[i]),*tItr); const auto tmp = rg[i]; *tItr = RE__(1.0); CPPUNIT_ASSERT_EQUAL(std::real(rg[i]),RE__(1.0)); CPPUNIT_ASSERT_EQUAL(std::imag(rg[i]),std::imag(tmp)); } delete[] rg; } } // test id template<> const char* test_cpxItr_all<0>::test_id() noexcept { return "test_reItr_all"; } // instantiation template class test_cpxItr_all<0>;
19.402985
57
0.636154
stiegerc
dabd5194efb503198df7e08bf34029a2b7e72213
8,699
cpp
C++
addglopeningbalance.cpp
bizjust/bizjust-erp
d3291e212bf89ab6e753194127b3951afcd02548
[ "MIT" ]
1
2022-02-16T13:02:43.000Z
2022-02-16T13:02:43.000Z
addglopeningbalance.cpp
bizjust/bizjust-erp
d3291e212bf89ab6e753194127b3951afcd02548
[ "MIT" ]
null
null
null
addglopeningbalance.cpp
bizjust/bizjust-erp
d3291e212bf89ab6e753194127b3951afcd02548
[ "MIT" ]
null
null
null
#include "addglopeningbalance.h" #include "ui_addglopeningbalance.h" AddGLOpeningBalance::AddGLOpeningBalance(QWidget *parent) : QWidget(parent), ui(new Ui::AddGLOpeningBalance) { ui->setupUi(this); loadform(); } AddGLOpeningBalance::~AddGLOpeningBalance() { delete ui; } void AddGLOpeningBalance::autocompleter(QString sql, QLineEdit *name_txt, QLineEdit *id_txt) { sch.name_txt = name_txt; sch.id_txt = id_txt; QMap<int, QString> data = sch.data; //conn.connOpen(); QSqlQuery qry; qry.prepare(sql); if(qry.exec()) { while(qry.next()) { data[qry.value(0).toInt()] = qry.value(1).toString(); } } //conn.connClose(); /*data[2] = "Moscow"; data[4] = "London"; data[6] = "Paris";*/ QCompleter *completer = new QCompleter(this); QStandardItemModel *model = new QStandardItemModel(completer); QMapIterator<int, QString> it(data); while (it.hasNext()) { it.next(); int code = it.key(); QString name = it.value(); QStandardItem *item = new QStandardItem; item->setText(name); item->setData(code, Qt::UserRole); model->appendRow(item); } completer->setModel(model); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setCurrentRow(0); completer->setFilterMode(Qt::MatchContains); name_txt->setCompleter(completer); connect(completer, SIGNAL(highlighted(QModelIndex)),this,SLOT(onItemHighlighted(QModelIndex)),Qt::QueuedConnection); connect(name_txt,SIGNAL(editingFinished()),this,SLOT(editingFinished() )); } void AddGLOpeningBalance::onItemHighlighted(const QModelIndex &index) { QString code = index.data(Qt::UserRole).toString(); QString sname = index.data(0).toString(); sch.searchname = sname; sch.searchid = code; sch.id_txt->setText(code); } void AddGLOpeningBalance::editingFinished() { QString sname = sch.name_txt->text(); QString sid = sch.id_txt->text(); if(sname!=sch.searchname || sid != sch.searchid) { sch.name_txt->setText(""); sch.id_txt->setText(""); } } void AddGLOpeningBalance::on_accountname_textEdited(const QString &arg1) { QString sql = sch.glaccount_generalize(arg1); autocompleter(sql,ui->accountname, ui->accountid); } void AddGLOpeningBalance::loadform() { ui->entrydate->setDate(QDate::currentDate()); ui->detailtable->setColumnCount(5); QStringList titles; titles <<"Account"<<"Account Id"<<"Description"<<"Debit"<<"Credit"; ui->detailtable->setHorizontalHeaderLabels(titles); ui->detailtable->hideColumn(ACCOUNTID); ui->detailtable->horizontalHeader()->setSectionResizeMode(ACCOUNTNAME, QHeaderView::Stretch); ui->detailtable->horizontalHeader()->setSectionResizeMode(DESCRIPTION, QHeaderView::Stretch); ui->detailtable->setColumnWidth(DEBIT,100); ui->detailtable->setColumnWidth(CREDIT,100); ui->btn_save->setEnabled(false); } void AddGLOpeningBalance::on_btn_add_clicked() { QString accountname = ui->accountname->text(); QString accountid = ui->accountid->text(); float debit = ui->debit->value(); float credit = ui->credit->value(); float total = debit+credit; if(accountid=="") { QMessageBox::critical(this,"","Please select Account"); ui->accountname->setFocus(); return; } else if(total<=0) { QMessageBox::critical(this,"","Please enter debit or credit"); ui->debit->setFocus(); return; } else { int row = ui->detailtable->rowCount(); ui->detailtable->insertRow(row); ui->detailtable->setItem(row,ACCOUNTNAME, new QTableWidgetItem(accountname)); ui->detailtable->setItem(row,ACCOUNTID, new QTableWidgetItem(accountid)); ui->detailtable->setItem(row,DESCRIPTION, new QTableWidgetItem(ui->description->text())); ui->detailtable->setItem(row,DEBIT, new QTableWidgetItem( erp.DecimalString(debit) )); ui->detailtable->setItem(row,CREDIT, new QTableWidgetItem( erp.DecimalString(credit) )); checktotal(); ui->accountname->clear(); ui->accountid->clear(); ui->debit->setValue(0.00); ui->credit->setValue(0.00); ui->accountname->setFocus(); } } void AddGLOpeningBalance::checktotal() { float tot_debit=0; float tot_credit=0; for(int i=0; i<ui->detailtable->rowCount(); i++) { float debit = ui->detailtable->item(i,DEBIT)->text().toFloat(); float credit = ui->detailtable->item(i,CREDIT)->text().toFloat(); tot_debit += debit; tot_credit += credit; } ui->total_debit->setValue(tot_debit); ui->total_credit->setValue(tot_credit); if(ui->detailtable->rowCount()>0) { ui->btn_save->setEnabled(true); } else { ui->btn_save->setEnabled(false); } } void AddGLOpeningBalance::on_btn_delete_row_clicked() { if(ui->detailtable->currentRow()>=0) { ui->detailtable->removeRow(ui->detailtable->currentRow()); checktotal(); } } void AddGLOpeningBalance::on_btn_save_clicked() { QString entrydate = ui->entrydate->date().toString("yyyy-MM-dd"); float total = ui->total_debit->value() + ui->total_credit->value(); if(entrydate=="") { QMessageBox::critical(this,"","Transaction date is required"); ui->entrydate->setFocus(); return; } else if(total==0) { QMessageBox::critical(this,"","Total Debit or Total Credit must not be 0.00"); return; } else { QString ob_code = "OB"; QString ob_num = erp.get_num(ob_code); QString vno = ob_code+"-"+ob_num; erp.update_ids_num(ob_code); float total_debit = ui->total_debit->value(); float total_credit = ui->total_credit->value(); float total_amount = total_debit+total_credit; QString wherefrom = "3"; QString description = "gl opening balance"; QString query_transaction = "INSERT INTO `tblgltransvoucher` " " ( `voucherno` ,`description` ,`entrydate` ,`total_debit` ,`total_credit` ,`wherefrom`, `financialyearid`) " " VALUES " " ('"+vno+"' ,'"+description+"', '"+entrydate+"', '"+erp.DecimalString(total_amount)+"', '"+erp.DecimalString(total_amount)+"', '"+wherefrom+"', '"+erp._yearid+"')"; if(!conn.execQuery(query_transaction)) { QMessageBox::critical(this,"","Some problem in record insertion"); return; } QString voucherid = erp.getvoucherid(vno); QString event = "Add"; QString transtype = "GL Opening Balance"; QString transid = vno ; erp.AddToEventLog(event,transtype,transid); QString voucher = vno; for(int i=0; i<ui->detailtable->rowCount(); i++) { QString glaccountid = ui->detailtable->item(i,ACCOUNTID)->text(); int ln = 0; if(glaccountid!="") { description = ui->detailtable->item(i,DESCRIPTION)->text(); float debit = ui->detailtable->item(i,DEBIT)->text().toFloat(); float credit = ui->detailtable->item(i,CREDIT)->text().toFloat(); ln++; QString query = "insert into tblgltransaction " " ( voucherno, voucherid, glaccountid, description, debit, credit, linenumber, `entrydate`, financialyearid) " " values " " ('"+voucher+"', '"+voucherid+"', '"+glaccountid+"', '"+description+"', '"+erp.DecimalString(debit)+"', '"+erp.DecimalString(credit)+"', '"+erp.intString(ln)+"', '"+entrydate+"', '"+erp._yearid+"')"; if(!conn.execQuery(query)) { QMessageBox::critical(this,"","Some problem in record insertion"); return; } } } QMessageBox::information(this,"","Opening balance "+voucher+" inserted successfully"); ui->detailtable->setRowCount(0); ui->accountname->clear(); ui->accountid->clear(); ui->debit->setValue(0.00); ui->credit->setValue(0.00); ui->entrydate->setFocus(); checktotal(); } } void AddGLOpeningBalance::on_debit_valueChanged(double arg1) { if(arg1>0) { ui->credit->setValue(0.00); } } void AddGLOpeningBalance::on_credit_valueChanged(double arg1) { if(arg1>0) { ui->debit->setValue(0.00); } }
33.457692
232
0.604667
bizjust
dac0f574f5bd7dc4f5546df185453a394d9ba17e
27,800
cpp
C++
externals/source/testdog/pack/src/html_reporter.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
externals/source/testdog/pack/src/html_reporter.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
externals/source/testdog/pack/src/html_reporter.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // PROJECT : TEST-DOG // FILENAME : html_reporter.hpp // DESCRIPTION : Concrete HTML reporting class. // COPYRIGHT : Andy Thomas (C) //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // LICENSE //--------------------------------------------------------------------------- // This file is part of the "TEST-DOG" program. // TEST-DOG 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. // TEST-DOG 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 TEST-DOG. If not, see <http://www.gnu.org/licenses/>. //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // INCLUDES //--------------------------------------------------------------------------- #include "html_reporter.hpp" #include "testdog/private/basic_test.hpp" #include "testdog/unit_test.hpp" #include "util.hpp" //--------------------------------------------------------------------------- // DECLARATIONS //--------------------------------------------------------------------------- using namespace testdog; namespace testdog { // Report tag names // Updating these can be used to form the basis for internationalization const char* const BASIC_TITLE = "Test Report"; const char* const PROJECT_NAME_LEADER = "PROJECT: "; const char* const PROJECT_VERSION_LEADER = "Version: "; const char* const REG_COUNT_LEADER = "Registered Tests: "; const char* const SCOPE_LEADER = "Run Scope: "; const char* const RUN_NONE_STR = "No Tests were Run"; const char* const RUN_ALL_STR = "All Tests"; const char* const RUN_SUITE_STR = "Specified Suite"; const char* const RUN_TEST_STR = "Specified Test Only"; const char* const START_TIME_LEADER = "Start Time: "; const char* const SUITE_LEADER = "TEST SUITE: "; const char* const DEF_SUITE_NAME = "[Default Suite]"; const char* const REPORT_CONTENTS = "Report Contents"; const char* const TEST_RESULTS = "Test Run Results"; const char* const TEST_STATS = "Statistical Results"; const char* const FAIL_DETAILS = "Test Failure Information"; const char* const ERROR_DETAILS = "Test Error Information"; const char* const PASS_DETAILS = "Test Pass Information"; const char* const DISABLED_TESTS = "Disabled Tests"; const char* const DISABLED_NOTES = "The following tests were skipped:"; const char* const END_TIME_LEADER = "End Time: "; const char* const DURATION_LEADER = "Run Duration: "; const char* const TAB_TEST_NAME = "Test Name"; const char* const TAB_AUTHOR = "Author"; const char* const TAB_START_TIME = "Start Time"; const char* const TAB_DURATION = "Duration"; const char* const TAB_RESULT = "Result"; const char* const STAT_TAB_METRIC = "Statistic"; const char* const STAT_TAB_VALUE = "Value"; const char* const STAT_TAB_RAN = "Tests Ran"; const char* const STAT_TAB_SKIPPED = "Skipped"; const char* const STAT_TAB_PASSED = "Passed"; const char* const STAT_TAB_FAILED = "Failed"; const char* const STAT_TAB_ERRORS = "Test Errors"; const char* const STAT_TAB_PERC = "Pass Rate"; const char* const NONE_STR = "NONE"; const char* const TEST_LEADER = "Test: "; const char* const BTS_NOT_RUN_STR = "NOT RUN"; const char* const BTS_SKIPPED_STR = "SKIPPED"; const char* const BTS_PASSED_STR = "PASSED"; const char* const BTS_FAILED_STR = "FAILED "; const char* const BTS_ERROR_STR = "TEST ERROR"; const char* const GENERATED_LEADER = "Test report generated by: "; } //--------------------------------------------------------------------------- // CLASS html_reporter : PROTECTED MEMBERS //--------------------------------------------------------------------------- std::string html_reporter::m_indent(int chrs) const { // Return indentation if (chrs < 0) chrs = m_indent_cnt; if (chrs > 0) return std::string(chrs, ' '); else return ""; } //--------------------------------------------------------------------------- std::ostream& html_reporter::m_generate_css(std::ostream& os) { // Generate interal CCS, or specify external sheet std::string temp_str = m_runner_ptr->html_report_stylesheet(); // Default styles os << m_indent() << "<style type=\"text/css\">\n"; m_indent_cnt += m_indent_step; os << m_indent() << "th {background-color:silver; font-weight:bold;"; os << " border-style:solid; border-width:thin}\n"; os << m_indent() << "td {border-style:solid; border-width:thin}\n"; os << m_indent() << ".pass-cell-col {background-color:lightgreen}\n"; os << m_indent() << ".fail-cell-col {background-color:red}\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</style>\n"; if (!temp_str.empty()) { os << m_indent() << "<link rel=\"stylesheet\" href=\""; os << temp_str; os << "\" type=\"text/css\" />\n"; } return os; } //--------------------------------------------------------------------------- std::string html_reporter::s_clean_id(const std::string& id_str) { // Clean up id_str and return result std::string rslt; std::size_t sz = id_str.size(); for(std::size_t n = 0; n < sz; ++n) { if ((id_str[n] >= 'a' && id_str[n] <= 'z') || (id_str[n] >= '0' && id_str[n] <= '9') || id_str[n] == '_' || id_str[n] == ':' || id_str[n] == '.' || id_str[n] == '-') { rslt += id_str[n]; } else if (id_str[n] == 0x20) { rslt += '_'; } else if (id_str[n] >= 'A' && id_str[n] <= 'Z') { rslt += static_cast<char>(id_str[n] + 0x20); } } return rslt; } //--------------------------------------------------------------------------- std::string html_reporter::s_page_link(const std::string& id_str, const std::string& name_str) { // Make "id_str" a link to an anchor. // Example: s_link("suite", "UCD_TESTS"); // returns: <a href=\"#anchor_suite">UCD_TESTS</a> return "<a href=\"#anchor_" + s_clean_id(id_str) + "\">" + name_str + "</a>"; } //--------------------------------------------------------------------------- std::string html_reporter::s_page_anchor(const std::string& id_str) { // Make "cat_str" an (empty) anchor. // Example: s_anchor("suite"); // returns: <span id=\"anchor_suite" /> return "<p id=\"anchor_" + s_clean_id(id_str) + "\"></p>"; } //--------------------------------------------------------------------------- std::string html_reporter::s_rslt_str(const basic_test* tc) { // Overral result of test switch(tc->state()) { case BTS_NOT_RUN: return BTS_NOT_RUN_STR; case BTS_SKIPPED: return BTS_SKIPPED_STR; case BTS_PASSED: return BTS_PASSED_STR; case BTS_FAILED: return std::string(BTS_FAILED_STR) + " (" + int_to_str(tc->fail_cnt()) + ")"; case BTS_TEST_ERROR: return BTS_ERROR_STR; default: return ""; } } //--------------------------------------------------------------------------- std::string html_reporter::s_th_str(const std::string& content, const std::string& width) { // Make table header cell if (!width.empty()) { return "<th style=\"width:" + width + "\">" + content + "</th>"; } else { return "<th>" + content + "</th>"; } } //--------------------------------------------------------------------------- std::string html_reporter::s_td_str(const std::string& content, bool bold, const std::string& class_id) { // Make table data cell std::string rslt = "<td"; if (!class_id.empty()) rslt += " class=\"" + class_id + "\""; rslt += ">"; if (bold) rslt += "<strong>" + content + "</strong>"; else rslt += content; return rslt + "</td>"; } //--------------------------------------------------------------------------- std::string html_reporter::s_cond_classid(bool passed) { // Condition color if (passed) return "pass-cell-col"; else return "fail-cell-col"; } //--------------------------------------------------------------------------- void html_reporter::m_build_trace(std::ostream& os, const std::vector<std::string>& trace_vec, const std::string& title_elem) { // During test case generation, trace output if buffered to a vector // array for adding to the report later. In this call, we take the vector // an build the trace sections of the report. Each test case is stored as // two items in the array. The first is the test name, and section is the // text formatted trace. Therefore, even numbered array indexes always // hold the test name for the trace that follows in the next item. // Start local indent - we expect 2 steps instead <html> & <body> tags std::size_t sz = trace_vec.size(); if (sz > 0 && sz % 2 == 0) { std::string t_name, t_cont; for(std::size_t n = 0; n < sz; n += 2) { // Extract test name and trace contents t_name = trace_vec[n]; t_cont = trace_vec[n+1]; if (t_cont.empty()) t_cont = NONE_STR; if (!t_name.empty()) { // Write title anchor os << m_indent() << s_page_anchor(t_name) + "\n"; // Make title, i.e. "....<h3>Suite::TestName</h3>" os << m_indent() << "<" << title_elem << ">"; os << TEST_LEADER << t_name << "</" + title_elem << ">\n"; // Stream <ul> start os << m_indent() + "<ul>\n"; m_indent_cnt += m_indent_step; // Steam trace content, replacing newlines with <li> pairs os << m_indent() + "<li>"; os << str_replace(t_cont, "\n", "</li>\n" + m_indent() + "<li>"); os << "</li>\n"; // Stream <ul> end m_indent_cnt -= m_indent_step; os << m_indent() + "</ul>\n"; } } } else { // No tests os << m_indent() << "<p>" << NONE_STR << "</p>\n"; } } //--------------------------------------------------------------------------- // CLASS html_reporter : PUBLIC MEMBERS //--------------------------------------------------------------------------- html_reporter::html_reporter(const runner* owner, html_reporter::style_t rs) : basic_reporter(owner) { // Constructor m_style = rs; m_indent_step = 2; m_html_report_author_col = true; // Create internal text reporter for test details // NB. We disable the test name leader as each output // block will have the test name as the heading. m_text_reporter_ptr = new text_reporter(m_runner_ptr, true); m_text_reporter_ptr->set_testname_leader(false); m_text_reporter_ptr->set_suite_breaks(false); // Zero clear(); } //--------------------------------------------------------------------------- html_reporter::~html_reporter() { try { // Destructor delete m_text_reporter_ptr; } catch(...) { } } //--------------------------------------------------------------------------- html_reporter::style_t html_reporter::style() const { // Accessor return m_style; } //--------------------------------------------------------------------------- void html_reporter::set_style(html_reporter::style_t s) { // Mutator m_style = s; } //--------------------------------------------------------------------------- int html_reporter::indent_step() const { // Accessor return m_indent_step; } //--------------------------------------------------------------------------- void html_reporter::set_indent_step(int is) { // Mutator if (is < 0) is = 0; m_indent_step = is; } //--------------------------------------------------------------------------- bool html_reporter::report_loc() const { // Accessor return m_text_reporter_ptr->report_loc(); } //--------------------------------------------------------------------------- void html_reporter::set_report_loc(bool rl) { // Mutator m_text_reporter_ptr->set_report_loc(rl); } //--------------------------------------------------------------------------- bool html_reporter::html_report_author_col() const { // Returns whether the HTML reports have an "author" column in // the result tables. return m_html_report_author_col; } //--------------------------------------------------------------------------- void html_reporter::set_html_report_author_col(bool a) { // Sets whether the HTML reports have an "author" column in // the result tables. m_html_report_author_col = a; } //--------------------------------------------------------------------------- void html_reporter::clear() { // Clear internal data m_suite_added = false; m_current_suite.clear(); m_indent_cnt = 0; m_text_reporter_ptr->clear(); m_pass_trace.clear(); m_fail_trace.clear(); m_error_trace.clear(); m_skipped_tests.clear(); } //--------------------------------------------------------------------------- std::ostream& html_reporter::gen_start(std::ostream& os) { // Write header to stream clear(); // DOCTYPE os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" "; os << "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n"; // HTML element os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"; m_indent_cnt += m_indent_step; // Head os << m_indent() << "<head>\n"; m_indent_cnt += m_indent_step; // Content-Type std::string temp_str = m_runner_ptr->report_charset(); os << m_indent() << "<meta http-equiv=\"Content-Type\" "; os << "content=\"text/html;"; if (!temp_str.empty()) os << " charset=" << temp_str; os << "\" />\n"; // Title temp_str = xml_esc(m_runner_ptr->project_name()); os << m_indent() << "<title>" << BASIC_TITLE; if (!temp_str.empty()) os << " | " << temp_str; os << "</title>\n"; // Stylesheet m_generate_css(os); // Head closure m_indent_cnt -= m_indent_step; os << m_indent() << "</head>\n"; // Body os << m_indent() << "<body>\n"; m_indent_cnt += m_indent_step; // Content - Title os << m_indent() << "<h1>" << BASIC_TITLE << "</h1>\n"; // Project information os << m_indent() << "<p>\n"; m_indent_cnt += m_indent_step; temp_str = xml_esc(m_runner_ptr->project_name()); if (!temp_str.empty()) { os << m_indent() << "<strong>" << PROJECT_NAME_LEADER << "</strong>"; os << temp_str << "<br/>\n"; } // Project version temp_str = xml_esc(m_runner_ptr->project_version()); if (!temp_str.empty()) { os << m_indent() << "<strong>" << PROJECT_VERSION_LEADER << "</strong>"; os << temp_str << "<br/>\n"; } // Test count os << m_indent() << "<strong>" << REG_COUNT_LEADER << "</strong>"; os << m_runner_ptr->registered_count() << "<br/>\n"; // Run scope os << m_indent() << "<strong>" << SCOPE_LEADER << "</strong>"; switch(m_runner_ptr->run_scope()) { case RUN_NONE: os << RUN_NONE_STR << "<br/>\n"; break; case RUN_ALL: os << RUN_ALL_STR << "<br/>\n"; break; case RUN_SUITE: os << RUN_SUITE_STR << "<br/>\n"; break; case RUN_TEST: os << RUN_TEST_STR << "<br/>\n"; break; default: os << "<br/>\n"; break; } // Start time os << m_indent() << "<strong>" << START_TIME_LEADER << "</strong>"; os << iso_time(m_runner_ptr->start_time()) << "<br/>\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</p>\n"; // Content - Title os << m_indent() << "<h2>" << REPORT_CONTENTS << "</h2>\n"; // Build navigation list if (m_runner_ptr->contains_suites()) { // Suite navigation // List os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<li>"; os << s_page_link("main", "<strong>" + std::string(TEST_RESULTS) + "</strong>"); os << "</li>\n"; // Get suite names std::vector<std::string> suite_array; m_runner_ptr->enum_suite_names(suite_array); std::size_t sz = suite_array.size(); for(std::size_t n = 0; n < sz; ++n) { if (suite_array[n].empty()) { // Sub default name suite_array[n] = DEF_SUITE_NAME; } // Escape suite_array[n] = xml_esc(suite_array[n]); os << m_indent() << "<li>"; os << s_page_link("suite_" + suite_array[n], suite_array[n]) << "</li>\n"; } // List closure m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; } else { // List os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<li>"; os << s_page_link("main", "<strong>" + std::string(TEST_RESULTS) + "</strong>"); os << "</li>\n"; // List closure m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; } // Additional info // List os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<li>"; os << s_page_link("test_stats", "<strong>" + std::string(TEST_STATS) + "</strong>"); os << "</li>\n"; if (m_style != HTML_SUMMARY) { // Additional content os << m_indent() << "<li>"; os << s_page_link("fail_details", FAIL_DETAILS); os << "</li>\n"; os << m_indent() << "<li>"; os << s_page_link("error_details", ERROR_DETAILS); os << "</li>\n"; if (m_style == HTML_VERBOSE) { // Verbose only content os << m_indent() << "<li>"; os << s_page_link("pass_details", PASS_DETAILS); os << "</li>\n"; os << m_indent() << "<li>"; os << s_page_link("disabled_tests", DISABLED_TESTS); os << "</li>\n"; } } // List closure m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; // Main section os << m_indent() << s_page_anchor("main") << "\n"; os << m_indent() << "<h2>" << TEST_RESULTS << "</h2>\n"; return os; } //--------------------------------------------------------------------------- std::ostream& html_reporter::gen_test(std::ostream& os, const basic_test* tc) { // Write test case to stream. tc cannot be null. if (tc->state() == BTS_SKIPPED) { if (m_style == HTML_VERBOSE) { // Record to skipped list m_skipped_tests.push_back(tc->full_name()); } } else if (tc->state() != BTS_NOT_RUN) { // Set temp_str to be suite name std::string s_name = xml_esc(tc->suite_name()); if (s_name != m_current_suite || !m_suite_added) { // New test suite if (m_suite_added) { // Close old suite m_indent_cnt -= m_indent_step; os << m_indent() << "</table>\n"; } // Add new suite m_suite_added = true; m_current_suite = s_name; // Apply default name if (m_runner_ptr->contains_suites()) { // Add suite header if (s_name.empty()) s_name = DEF_SUITE_NAME; os << m_indent() << s_page_anchor("suite_" + s_name) << "\n"; os << m_indent() << "<h3>" << SUITE_LEADER << s_name << "</h3>\n"; } // Open table (defines width properties) os << m_indent() << "<table style=\"width:75%; max-width:100em\">\n"; m_indent_cnt += m_indent_step; // Header row os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_th_str(TAB_TEST_NAME) << "\n"; if (m_html_report_author_col) { os << m_indent() << s_th_str(TAB_AUTHOR, "15%") << "\n"; } os << m_indent() << s_th_str(TAB_START_TIME, "20%") << "\n"; os << m_indent() << s_th_str(TAB_DURATION, "15%") << "\n"; os << m_indent() << s_th_str(TAB_RESULT, "15%") << "\n"; // Close row m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; } // Data row os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; // Set temp_str to be full test name std::string t_name = xml_esc(tc->full_name()); if (m_style == HTML_VERBOSE || (m_style != HTML_SUMMARY && tc->state() != BTS_PASSED)) { // Add event to corresponding vector - these // will be appended to the report later. We append // the test name, followed by the trace text, so // that even number elements always content the // test name, and trace contents will follow. std::stringstream ss; m_text_reporter_ptr->gen_test(ss, tc); std::string t_cont = xml_esc(trim_str(ss.str())); switch(tc->state()) { // Append to applicable vector case BTS_PASSED: m_pass_trace.push_back(t_name); m_pass_trace.push_back(t_cont); break; case BTS_FAILED: m_fail_trace.push_back(t_name); m_fail_trace.push_back(t_cont); break; case BTS_TEST_ERROR: m_error_trace.push_back(t_name); m_error_trace.push_back(t_cont); break; default: break; } // Linked test name t_name = s_page_link(t_name, t_name); } os << m_indent() << s_td_str(t_name) << "\n"; if (m_html_report_author_col) { os << m_indent() << s_td_str(xml_esc(tc->author())) << "\n"; } os << m_indent() << s_td_str(iso_time(tc->start_time())) << "\n"; os << m_indent() << s_td_str(duration_str(tc->test_duration())) << "\n"; // Color pass/fail value bool pass_ok = (tc->state() == BTS_PASSED); os << m_indent() << s_td_str(s_rslt_str(tc), !pass_ok, s_cond_classid(pass_ok)) << "\n"; // Close row m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; } return os; } //--------------------------------------------------------------------------- std::ostream& html_reporter::gen_end(std::ostream& os) { // Write footer to stream if (m_suite_added) { // Close last table m_indent_cnt -= m_indent_step; os << m_indent() << "</table>\n"; } else if (m_runner_ptr->stat_result(ST_RAN) == 0) { os << m_indent() << "<p>" << NONE_STR << "</p>"; } // Statistics os << m_indent() << s_page_anchor("test_stats") << "\n"; os << m_indent() << "<h2>" << TEST_STATS << "</h2>\n"; // Define colors std::string pass_id, fail_id, err_id; if (m_runner_ptr->stat_result(ST_PASSED) == m_runner_ptr->stat_result(ST_RAN)) { pass_id = s_cond_classid(true); } if (m_runner_ptr->stat_result(ST_FAILED) > 0) { fail_id = s_cond_classid(false); } if (m_runner_ptr->stat_result(ST_ERRORS) > 0) { err_id = s_cond_classid(false); } // Open table os << m_indent() << "<table style=\"width:20em\">\n"; m_indent_cnt += m_indent_step; // Header row os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_th_str(STAT_TAB_METRIC) << "\n"; os << m_indent() << s_th_str(STAT_TAB_VALUE) << "\n"; // Close row m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_RAN, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_RAN))) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_SKIPPED, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_SKIPPED))) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_PASSED, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_PASSED))) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_FAILED, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_FAILED)), false, fail_id) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_ERRORS, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_ERRORS)), false, err_id) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; os << m_indent() << "<tr>\n"; m_indent_cnt += m_indent_step; os << m_indent() << s_td_str(STAT_TAB_PERC, true) << "\n"; os << m_indent() << s_td_str(int_to_str( m_runner_ptr->stat_result(ST_PASS_RATE)) + "%", false, pass_id) << "\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</tr>\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</table>\n"; // Test end time os << m_indent() << "<p>\n"; m_indent_cnt += m_indent_step; os << m_indent() << "<strong>" << END_TIME_LEADER << "</strong>"; os << iso_time(m_runner_ptr->end_time()) << "<br/>\n"; // Duration os << m_indent() << "<strong>" << DURATION_LEADER << "</strong>"; os << duration_str(m_runner_ptr->duration()) << " (approx.) <br/>\n"; m_indent_cnt -= m_indent_step; os << m_indent() << "</p>\n"; if (m_style != HTML_SUMMARY) { // Additional content os << m_indent() << s_page_anchor("fail_details") << "\n"; os << m_indent() << "<h2>" << FAIL_DETAILS << "</h2>\n"; m_build_trace(os, m_fail_trace, "h3"); os << m_indent() << s_page_anchor("error_details") << "\n"; os << m_indent() << "<h2>" << ERROR_DETAILS << "</h2>\n"; m_build_trace(os, m_error_trace, "h3"); if (m_style == HTML_VERBOSE) { // Verbose only content os << m_indent() << s_page_anchor("pass_details") << "\n"; os << m_indent() << "<h2>" << PASS_DETAILS << "</h2>\n"; m_build_trace(os, m_pass_trace, "h3"); // Disabled tests os << m_indent() << s_page_anchor("disabled_tests") << "\n"; os << m_indent() << "<h2>" << DISABLED_TESTS << "</h2>\n"; // Build list of disabled tests std::size_t sk_sz = m_skipped_tests.size(); if (sk_sz > 0) { os << m_indent() << "<p>" << DISABLED_NOTES << "</p>\n"; os << m_indent() << "<ul>\n"; m_indent_cnt += m_indent_step; for(std::size_t n = 0; n < sk_sz; ++n) { os << m_indent() << "<li>" << m_skipped_tests[n] << "</li>\n"; } m_indent_cnt -= m_indent_step; os << m_indent() << "</ul>\n"; } else { os << m_indent() << "<p>" << NONE_STR << "</p>\n"; } } } // Generator os << m_indent() << "<p>" << GENERATED_LEADER; os << LIB_NAME << " " << LIB_VERSION; os << "</p>\n"; // Close body m_indent_cnt -= m_indent_step; os << m_indent() << "</body>\n"; // Close html m_indent_cnt -= m_indent_step; os << m_indent() << "</html>\n"; return os; } //---------------------------------------------------------------------------
31.698974
81
0.523921
skarab
dac60771e185d510189f139a26d01a41a909b797
14,725
inl
C++
image/include/storm/image/Image.inl
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
image/include/storm/image/Image.inl
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
image/include/storm/image/Image.inl
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #pragma once #include "Image.hpp" namespace storm::image { ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::pixel(core::ArraySize index, core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); auto _data = data(layer, face, level); STORMKIT_EXPECTS(index < m_extent.width * m_extent.height * m_extent.depth); const auto block_size = m_channel_count * m_bytes_per_channel; return { std::data(_data) + index * block_size, block_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::pixel(core::ArraySize index, core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); auto _data = data(layer, face, level); const auto mip_extent = extent(level); STORMKIT_EXPECTS(index < mip_extent.width * mip_extent.height * mip_extent.depth); const auto block_size = m_channel_count * m_bytes_per_channel; return { std::data(_data) + index * block_size, block_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::pixel(core::Position3u position, core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { const auto mip_extent = extent(level); const auto id = position->x + (position->y * mip_extent.width) + (mip_extent.width * mip_extent.height * position->z); return pixel(id, layer, face, level); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::pixel(core::Position3u position, core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { const auto mip_extent = extent(level); const auto id = position->x + (position->y * mip_extent.width) + (mip_extent.width * mip_extent.height * position->z); return pixel(id, layer, face, level); } ///////////////////////////////////// ///////////////////////////////////// core::Extentu Image::extent(core::UInt32 level) const noexcept { STORMKIT_EXPECTS(m_mip_levels > level); return { std::max(1u, m_extent.width >> level), std::max(1u, m_extent.height >> level), std::max(1u, m_extent.depth >> level) }; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::channelCount() const noexcept { return m_channel_count; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::bytesPerChannel() const noexcept { return m_bytes_per_channel; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::layers() const noexcept { return m_layers; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::faces() const noexcept { return m_faces; } ///////////////////////////////////// ///////////////////////////////////// core::UInt32 Image::mipLevels() const noexcept { return m_mip_levels; } ///////////////////////////////////// ///////////////////////////////////// Image::Format Image::format() const noexcept { return m_format; } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size() const noexcept { return std::size(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); const auto mip_extent = extent(level); return mip_extent.width * mip_extent.height * mip_extent.depth * m_channel_count * m_bytes_per_channel; } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size(core::UInt32 layer, core::UInt32 face) const noexcept { auto _size = core::ArraySize { 0u }; for (auto i = 0u; i < m_mip_levels; ++i) _size += size(layer, face, i); return _size; } ///////////////////////////////////// ///////////////////////////////////// core::ArraySize Image::size(core::UInt32 layer) const noexcept { auto _size = core::ArraySize { 0u }; for (auto i = 0u; i < m_faces; ++i) _size += size(layer, i); return _size; } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::data() noexcept { return m_data; } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan Image::data(core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { const auto mip_size = size(layer, face, level); auto offset = 0u; for (auto i = 0u; i < layer; ++i) offset += size(i); for (auto j = 0u; j < face; ++j) offset += size(layer, j); for (auto k = 0u; k < level; ++k) offset += size(layer, face, k); return { std::data(m_data) + offset, mip_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::data() const noexcept { return m_data; } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan Image::data(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { const auto mip_size = size(layer, face, level); auto offset = 0u; for (auto i = 0u; i < layer; ++i) offset += size(i); for (auto j = 0u; j < face; ++j) offset += size(layer, j); for (auto k = 0u; k < level; ++k) offset += size(layer, face, k); return { std::data(m_data) + offset, mip_size }; } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::iterator Image::begin() noexcept { return std::begin(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan::iterator Image::begin(core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { STORMKIT_EXPECTS(m_mip_levels > level); STORMKIT_EXPECTS(m_faces > face); STORMKIT_EXPECTS(m_layers > layer); return std::begin(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::begin() const noexcept { return std::begin(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::begin(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::begin(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::cbegin() const noexcept { return std::cbegin(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::cbegin(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::cbegin(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::iterator Image::end() noexcept { return std::end(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteSpan::iterator Image::end(core::UInt32 layer, core::UInt32 face, core::UInt32 level) noexcept { return std::end(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::end() const noexcept { return std::end(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::end(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::end(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// core::ByteArray::const_iterator Image::cend() const noexcept { return std::cend(m_data); } ///////////////////////////////////// ///////////////////////////////////// core::ByteConstSpan::iterator Image::cend(core::UInt32 layer, core::UInt32 face, core::UInt32 level) const noexcept { return std::cend(data(layer, face, level)); } ///////////////////////////////////// ///////////////////////////////////// constexpr core::UInt8 getChannelCountFor(Image::Format format) noexcept { switch (format) { case Image::Format::R8_SNorm: case Image::Format::R8_UNorm: case Image::Format::R16_SNorm: case Image::Format::R16_UNorm: case Image::Format::R8I: case Image::Format::R8U: case Image::Format::R16I: case Image::Format::R16U: case Image::Format::R32I: case Image::Format::R32U: case Image::Format::R16F: case Image::Format::R32F: return 1; case Image::Format::RG8_SNorm: case Image::Format::RG8_UNorm: case Image::Format::RG16_SNorm: case Image::Format::RG16_UNorm: case Image::Format::RG8I: case Image::Format::RG8U: case Image::Format::RG16I: case Image::Format::RG16U: case Image::Format::RG32I: case Image::Format::RG32U: case Image::Format::RG16F: case Image::Format::RG32F: return 2; case Image::Format::RGB8_SNorm: case Image::Format::RGB8_UNorm: case Image::Format::RGB16_SNorm: case Image::Format::RGB16_UNorm: case Image::Format::BGR8_UNorm: case Image::Format::RGB8I: case Image::Format::RGB8U: case Image::Format::RGB16I: case Image::Format::RGB16U: case Image::Format::RGB32I: case Image::Format::RGB32U: case Image::Format::RGB16F: case Image::Format::RGB32F: case Image::Format::sRGB8: case Image::Format::sBGR8: return 3; case Image::Format::RGBA8_SNorm: case Image::Format::RGBA8_UNorm: case Image::Format::RGBA16_SNorm: case Image::Format::RGBA16_UNorm: case Image::Format::BGRA8_UNorm: case Image::Format::RGBA8I: case Image::Format::RGBA8U: case Image::Format::RGBA16I: case Image::Format::RGBA16U: case Image::Format::RGBA32I: case Image::Format::RGBA32U: case Image::Format::RGBA16F: case Image::Format::RGBA32F: case Image::Format::sRGBA8: case Image::Format::sBGRA8: return 4; default: return 0u; } return 0u; } ///////////////////////////////////// ///////////////////////////////////// constexpr core::UInt8 getArraySizeByChannelFor(Image::Format format) noexcept { switch (format) { case Image::Format::R8_SNorm: case Image::Format::R8_UNorm: case Image::Format::RG8_SNorm: case Image::Format::RG8_UNorm: case Image::Format::R8I: case Image::Format::R8U: case Image::Format::RG8I: case Image::Format::RG8U: case Image::Format::RGB8_SNorm: case Image::Format::RGB8_UNorm: case Image::Format::BGR8_UNorm: case Image::Format::RGB8I: case Image::Format::RGB8U: case Image::Format::RGBA8_SNorm: case Image::Format::RGBA8_UNorm: case Image::Format::RGBA16_SNorm: case Image::Format::BGRA8_UNorm: case Image::Format::sRGB8: case Image::Format::sBGR8: case Image::Format::sRGBA8: case Image::Format::sBGRA8: return 1u; case Image::Format::R16_SNorm: case Image::Format::R16_UNorm: case Image::Format::R16I: case Image::Format::R16U: case Image::Format::RG16_SNorm: case Image::Format::RG16_UNorm: case Image::Format::RG16I: case Image::Format::RG16U: case Image::Format::RG16F: case Image::Format::RGB16I: case Image::Format::RGB16U: case Image::Format::RGB16F: case Image::Format::RGBA16I: case Image::Format::RGBA16U: case Image::Format::RGBA16F: case Image::Format::R16F: return 2u; case Image::Format::R32I: case Image::Format::R32U: case Image::Format::R32F: case Image::Format::RG32I: case Image::Format::RG32U: case Image::Format::RG32F: case Image::Format::RGB16_SNorm: case Image::Format::RGB32I: case Image::Format::RGB32U: case Image::Format::RGB32F: case Image::Format::RGBA8I: case Image::Format::RGBA8U: case Image::Format::RGBA32I: case Image::Format::RGBA32U: case Image::Format::RGBA32F: return 4u; default: return 0u; } return 0u; } } // namespace storm::image
37.659847
100
0.469134
Arthapz
dad4144fd8a60c44e5f8ac9649ebbfc262a21ff1
5,970
cpp
C++
IRLib/Decoder.cpp
rizwanullah/IRLib
d06bea379e62f0db7276d3be3488b5af8ce8c369
[ "Apache-2.0" ]
null
null
null
IRLib/Decoder.cpp
rizwanullah/IRLib
d06bea379e62f0db7276d3be3488b5af8ce8c369
[ "Apache-2.0" ]
null
null
null
IRLib/Decoder.cpp
rizwanullah/IRLib
d06bea379e62f0db7276d3be3488b5af8ce8c369
[ "Apache-2.0" ]
null
null
null
#include "Decoder.h" #include "json.hpp" #include "Common.h" using json = nlohmann::json; Decoder::Decoder() {} std::string Decoder::decode(std::string encodedIrJsonStr) { json encodedIrJson; REMOTE_COMMON remoteCommon; std::string encodedIrData; //memset(&remoteCommon, 0, sizeof(remoteCommon)); try { encodedIrJson = json::parse(encodedIrJsonStr); } catch (std::exception &e) { Common::logIrLib("Exception: %s", e.what()); return createResponseJson(CM_CODE_JSON_PARSE_ERROR, e.what(), "", ""); } try { remoteCommon.remoteId = encodedIrJson["remoteId"]; } catch (std::exception &e) { Common::logIrLib("Exception: %s", e.what()); return createResponseJson(CM_CODE_JSON_NO_KEY_ERROR, e.what(), "", ""); } try { encodedIrData = encodedIrJson["encodedIrData"]; } catch (std::exception &e) { Common::logIrLib("Exception: %s", e.what()); return createResponseJson(CM_CODE_JSON_NO_KEY_ERROR, e.what(), "", ""); } int32_t decodeErrorCode = DE_CODE_REMOTE_NOT_FOUND; if (remoteCommon.remoteId == 0) { // find remote if (decodeErrorCode != DE_CODE_SUCCESS) { RmtChigo1 *rmtChigo1 = new RmtChigo1(); decodeErrorCode = rmtChigo1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtChigo1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtAux1 *rmtAux1 = new RmtAux1(); decodeErrorCode = rmtAux1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtAux1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtTcl1 *rmtTcl1 = new RmtTcl1(); decodeErrorCode = rmtTcl1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtTcl1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtChigo2 *rmtChigo2 = new RmtChigo2(); decodeErrorCode = rmtChigo2->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtChigo2::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtLG1 *rmtLG1 = new RmtLG1(); decodeErrorCode = rmtLG1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtLG1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtMits1 *rmtMits1 = new RmtMits1(); decodeErrorCode = rmtMits1->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtMits1::remoteId; } if (decodeErrorCode != DE_CODE_SUCCESS) { RmtGreeAll *rmtGreeAll = new RmtGreeAll(); decodeErrorCode = rmtGreeAll->decodeRemote(encodedIrData, &remoteCommon); remoteCommon.remoteId = RmtGreeAll::remoteId; } } else if (remoteCommon.remoteId == RmtChigo1::remoteId) { RmtChigo1 *rmtChigo1 = new RmtChigo1(); decodeErrorCode = rmtChigo1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtAux1::remoteId) { RmtAux1 *rmtAux1 = new RmtAux1(); decodeErrorCode = rmtAux1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtTcl1::remoteId) { RmtTcl1 *rmtTcl1 = new RmtTcl1(); decodeErrorCode = rmtTcl1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtChigo2::remoteId) { RmtChigo2 *rmtChigo2 = new RmtChigo2(); decodeErrorCode = rmtChigo2->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtLG1::remoteId) { RmtLG1 *rmtLG1 = new RmtLG1(); decodeErrorCode = rmtLG1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtMits1::remoteId) { RmtMits1 *rmtMits1 = new RmtMits1(); decodeErrorCode = rmtMits1->decodeRemote(encodedIrData, &remoteCommon); } else if (remoteCommon.remoteId == RmtGreeAll::remoteId) { RmtGreeAll *rmtGreeAll = new RmtGreeAll(); decodeErrorCode = rmtGreeAll->decodeRemote(encodedIrData, &remoteCommon); } else { return createResponseJson(DE_CODE_REMOTE_NOT_FOUND, Common::getErrorString(DE_CODE_REMOTE_NOT_FOUND), "", ""); } json remoteJson; remoteJson["remoteId"] = remoteCommon.remoteId; remoteJson["remoteModel"] = remoteCommon.remoteModel; remoteJson["remoteBrand"] = remoteCommon.remoteBrand; remoteJson["powerOnOff"] = remoteCommon.powerOnOff; remoteJson["operationMode"] = remoteCommon.operationMode; remoteJson["setTemperature"] = remoteCommon.setTemperature; remoteJson["fanSpeed"] = remoteCommon.fanSpeed; remoteJson["swingVertical"] = remoteCommon.swingVertical; remoteJson["swingHorizontal"] = remoteCommon.swingHorizontal; remoteJson["turboOnOff"] = remoteCommon.turboOnOff; remoteJson["muteOnOff"] = remoteCommon.muteOnOff; remoteJson["autoEvapOnOff"] = remoteCommon.autoEvapOnOff; remoteJson["displayOnOff"] = remoteCommon.displayOnOff; if (decodeErrorCode == DE_CODE_SUCCESS) { json responseJson; responseJson["errorCode"] = DE_CODE_SUCCESS; responseJson["errorMessage"] = ""; responseJson["decodedIrPacket"] = remoteCommon.decodedPacket; responseJson["decodedIrJson"] = remoteJson; return responseJson.dump(); } else return createResponseJson(decodeErrorCode, Common::getErrorString(decodeErrorCode), "", ""); } std::string Decoder::createResponseJson(int32_t errorCode, std::string errorMessage, std::string decodedIrPacket, std::string decodedIrJsonStr) { json responseJson; responseJson["errorCode"] = errorCode; responseJson["errorMessage"] = errorMessage; responseJson["decodedIrPacket"] = decodedIrPacket; responseJson["decodedIrJson"] = decodedIrJsonStr; return responseJson.dump(); }
44.552239
145
0.672362
rizwanullah
dae53245f62fea7a54ed6926505324621f29f39b
1,056
cpp
C++
roman-to-integer.cpp
isanchez-aguilar/LeetCode-Solutions
094c15b672efa6ca2581f187579303c8b94390a3
[ "MIT" ]
null
null
null
roman-to-integer.cpp
isanchez-aguilar/LeetCode-Solutions
094c15b672efa6ca2581f187579303c8b94390a3
[ "MIT" ]
null
null
null
roman-to-integer.cpp
isanchez-aguilar/LeetCode-Solutions
094c15b672efa6ca2581f187579303c8b94390a3
[ "MIT" ]
null
null
null
class Solution { public: static int getValueOfChar(char c) { if (c == 'I') return 1; if (c == 'V') return 5; if (c == 'X') return 10; if (c == 'L') return 50; if (c == 'C') return 100; if (c == 'D') return 500; return 1000; } /* ** Time complexity: O(|s|) ** Space complexity: O(1) */ int romanToInt(string s) { int answer = 0; int currentSum = getValueOfChar(s[0]); int prevVal = currentSum; const int size = s.size(); for (int i = 1; i < size; ++i) { const int symbolValue = getValueOfChar(s[i]); if (symbolValue == prevVal) { currentSum += symbolValue; } if (symbolValue < prevVal) { answer += currentSum; currentSum = symbolValue; } if (prevVal < symbolValue) { answer += symbolValue - currentSum; currentSum = 0; } prevVal = symbolValue; } answer += currentSum; return answer; } };
17.311475
51
0.482008
isanchez-aguilar
daea7fa9d026ab64bc6657d418427ad9b130ff80
1,291
cpp
C++
src/modelFactory/FindSCMain.cpp
toebs88/SCAM
0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca
[ "MIT" ]
3
2018-08-31T21:35:27.000Z
2018-10-29T04:06:46.000Z
src/modelFactory/FindSCMain.cpp
toebs88/SCAM
0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca
[ "MIT" ]
1
2018-04-20T12:38:22.000Z
2018-04-20T12:38:55.000Z
src/modelFactory/FindSCMain.cpp
toebs88/SCAM
0b5a8f1c57593da40e85d0b8ce6a6cf5616379ca
[ "MIT" ]
null
null
null
#include <iostream> #include "FindSCMain.h" namespace SCAM { FindSCMain::FindSCMain(clang::TranslationUnitDecl *tuDecl): pass(0), scMainFound(false), _scmainFunctionDecl(NULL){ assert (!(tuDecl == NULL)); //Find sc_main TraverseDecl(tuDecl); //Is found } bool FindSCMain::VisitFunctionDecl(clang::FunctionDecl *functionDecl) { /// Find sc_main. /// There are three conditions to satisfy this: /// 1. Must have sc_main in its name. /// 2. Must have a body /// 3. Must *not* be a first declaration. (This is becuase systemc.h includes a null definition of sc_main. if ((functionDecl->getNameInfo().getAsString() == "sc_main") && (functionDecl->hasBody())) { //Pass the null definition of main if(pass == 1){ _scmainFunctionDecl = functionDecl; scMainFound = true; return false; } pass = 1; } return true; } clang::FunctionDecl *FindSCMain::getSCMainFunctionDecl() { assert (!(_scmainFunctionDecl == NULL)); return _scmainFunctionDecl; } bool FindSCMain::isScMainFound() const { return scMainFound; } }
28.688889
115
0.570875
toebs88
daf3166dce0501452596e89e418449bde63c9607
5,965
cpp
C++
StartDialog.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
StartDialog.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
StartDialog.cpp
KaikiasVind/CellBadger
c21adf5feec7766decfd4d89a110364d4bdfbc46
[ "MIT" ]
null
null
null
#include "StartDialog.h" #include "ui_StartDialog.h" #include <QStringList> #include <QFileDialog> #include <QDir> #include <QDebug> #include <QPushButton> #include <QLabel> #include <QObject> #include <QAction> #include <QMouseEvent> #include "Utils/Helper.h" using Helper::chopFileName; using Helper::openFileDialog; /** * @brief StartDialog::StartDialog * @param parent */ StartDialog::StartDialog(QWidget *parent) : QDialog(parent), ui(new Ui::StartDialog) { ui->setupUi(this); this->setWindowFlags(Qt::FramelessWindowHint); ui->stackedWidget->setCurrentIndex(0); ui->buttonRun->setDisabled(true); } /** * @brief StartDialog::~StartDialog */ StartDialog::~StartDialog() { /*REMEMBER: What should be done here?*/ } /** * @brief StartDialog::createPushButton * @return */ QPushButton * StartDialog::createPushButton() { QPushButton * button = new QPushButton(); button->setText("+"); return button; } /** * @brief StartDialog::addDatasetToLayout * @param name */ void StartDialog::addDatasetToLayout(const QString filePath) { QString fileName = chopFileName(filePath); QListWidgetItem * item = new QListWidgetItem(fileName); ui->listDatasets->addItem(item); } /** * @brief StartDialog::enableRunButtonIfReady - If every requirement is set, enable the run button */ void StartDialog::enableRunButtonIfReady() { bool isUploadedDataset = !uploadedDatasets.isEmpty(); bool isUseDefaultSelected = ui->checkBoxUseDefault->isChecked(); bool isCustomMarkerFileUploaded = !uploadedMarkerFile.isNull(); if (isUploadedDataset && (isUseDefaultSelected || isCustomMarkerFileUploaded)) { ui->buttonRun->setEnabled(true); } } /** * @brief StartDialog::disableUseDefaultButton - Disables the default button (in case no valid default file was found) */ void StartDialog::disableUseDefaultButton() { this->ui->checkBoxUseDefault->setDisabled(true); } // ++++++++++++++++++++++++++++++++ SLOTS ++++++++++++++++++++++++++++++++ // STACKED WIDGET PAGE ONE /** * @brief StartDialog::on_buttonMenuBarExit_clicked */ __attribute__((noreturn)) void StartDialog::on_buttonMenuBarExit_clicked() { exit(0); } /** * @brief StartDialog::on_buttonExit_clicked */ __attribute__((noreturn)) void StartDialog::on_buttonExit_clicked() { exit(0); } /** * @brief StartDialog::on_buttonLoadProject_clicked */ void StartDialog::on_buttonLoadProject_clicked() { QStringList csvMimeTypes = { "text/plain" }; QStringList fileNames = openFileDialog(this, csvMimeTypes, false); if (fileNames.empty()) return; qDebug() << "Sent project file name."; } /** * @brief StartDialog::on_buttonNewProject_clicked */ void StartDialog::on_buttonNewProject_clicked() { ui->stackedWidget->setCurrentIndex(1); } // STACKED WIDGET PAGE TWO /** * @brief StartDialog::on_buttonMenuBarBack_clicked */ void StartDialog::on_buttonMenuBarBack_clicked() { ui->stackedWidget->setCurrentIndex(0); } /** * @brief StartDialog::on_checkBoxUseDefault_stateChanged * @param state */ void StartDialog::on_checkBoxUseDefault_stateChanged(int state) { if (state == Qt::CheckState::Checked) { ui->buttonLoadCustom->setDisabled(true); // REMEMBER: This should be done differently uploadedMarkerFile = "nAn"; enableRunButtonIfReady(); } else { ui->buttonLoadCustom->setDisabled(false); ui->buttonRun->setDisabled(true); } } /** * @brief StartDialog::on_buttonMenuBarExit_2_clicked */ __attribute__((noreturn)) void StartDialog::on_buttonMenuBarExit_2_clicked() { exit(0); } /** * @brief StartDialog::on_buttonLoadCustom_clicked */ void StartDialog::on_buttonLoadCustom_clicked() { QStringList csvMimeTypes = { "text/csv" }; QStringList fileNames = openFileDialog(this, csvMimeTypes, false); if (fileNames.empty()) return; uploadedMarkerFile = fileNames.first(); enableRunButtonIfReady(); qDebug() << "Uploaded" << fileNames[0]; } /** * @brief StartDialog::on_buttonAddDataset_clicked */ void StartDialog::on_buttonAddDataset_clicked() { QStringList csvMimeTypes = { "text/csv" }; QStringList filePaths = openFileDialog(this, csvMimeTypes, true); if (filePaths.empty()) return; for (int i = 0; i < filePaths.length(); i++) { QString filePath = filePaths[i]; QString fileName = chopFileName(filePath); // If file has already been uploaded, skip it if (uploadedDatasets.contains(fileName)) { continue; } uploadedDatasets.insert(fileName, filePath); addDatasetToLayout(fileName); qDebug() << "Uploaded" << fileName; } enableRunButtonIfReady(); } /** * @brief StartDialog::on_buttonRemoveDataset_clicked */ void StartDialog::on_buttonRemoveDataset_clicked() { qDebug() << uploadedDatasets; for (QListWidgetItem * item : ui->listDatasets->selectedItems()) { uploadedDatasets.remove(item->text()); delete ui->listDatasets->takeItem(ui->listDatasets->row(item)); } qDebug() << uploadedDatasets; } /** * @brief StartDialog::on_buttonRun_clicked */ void StartDialog::on_buttonRun_clicked() { emit runNewProject(uploadedMarkerFile, uploadedDatasets.values()); this->close(); //REMEMBER: How to delete this the right way? // this->deleteLater(); ?! // this->~StartDialog(); } // ++++++++++++++++++++++++++++++++ SLOTS ++++++++++++++++++++++++++++++++ // ++++++++++++++++++++++++++++++++ MOUSE ++++++++++++++++++++++++++++++++ void StartDialog::mousePressEvent(QMouseEvent * mousePressEvent) { this->mouseClickXCoordinate = mousePressEvent->x(); this->mouseClickYCoordinate = mousePressEvent->y(); } void StartDialog::mouseMoveEvent(QMouseEvent * mouseMoveEvent) { this->move(mouseMoveEvent->globalX() - this->mouseClickXCoordinate, mouseMoveEvent->globalY() - this->mouseClickYCoordinate); }
25.063025
125
0.677284
KaikiasVind
daff34c6e49f7ce10c7b45518a1edd7a3d66be09
5,256
cpp
C++
traj_visualization_plugin/src/trajectory_display.cpp
YanzhouWang/rsp_final_project
c58c3efbf507cdd54abf860f7519006bc077c9f0
[ "MIT" ]
null
null
null
traj_visualization_plugin/src/trajectory_display.cpp
YanzhouWang/rsp_final_project
c58c3efbf507cdd54abf860f7519006bc077c9f0
[ "MIT" ]
null
null
null
traj_visualization_plugin/src/trajectory_display.cpp
YanzhouWang/rsp_final_project
c58c3efbf507cdd54abf860f7519006bc077c9f0
[ "MIT" ]
null
null
null
#include <traj_visualization_plugin/trajectory_display.hpp> namespace trajectory_display_ns{ trajectory_display::trajectory_display(){ description_property_=new rviz::StringProperty("Robot Description","robot_description", "The name of the ROS parameter where the URDF for the robot is loaded", this, SLOT (updateRobotDescription())); target_property_=new rviz::StringProperty("Target link", " ", "Target link of the robot", this, SLOT (updateLinkChoice())); color_property_=new rviz::ColorProperty("Line color",QColor(204,51,204), "Color of the path", this, SLOT (updateLineColorandAlpha())); alpha_property_=new rviz::FloatProperty("Line alpha",1, "Line alpha, 1 is opaque, 0 is transparent", this, SLOT (updateLineColorandAlpha())); width_property_=new rviz::FloatProperty("Line width",0.003, "Line width", this, SLOT(updateLineWidth())); plugin_status_=new rviz::StatusProperty("Plugin status","plugin status",rviz::StatusProperty::Level(0) , this); plugin_status_->hide(); } trajectory_display::~trajectory_display(){ delete target_property_; delete description_property_; delete color_property_; delete alpha_property_; delete width_property_; delete plugin_status_; delete kdlfk_r2t_; } void trajectory_display::onInitialize(){ MFDClass::onInitialize(); std::string robot_description_string; ros::param::get(description_property_->getStdString(),robot_description_string); if(!kdl_parser::treeFromString(robot_description_string, tree_)){ ROS_ERROR("Cannot build tree."); setStatus(rviz::StatusProperty::Level(2),"Robot state","Cannot get robot model from parameter server."); plugin_status_->setLevel(rviz::StatusProperty::Level(2)); } else{ ROS_INFO("Retrieved tree from parameter server."); setStatus(rviz::StatusProperty::Level(0),"Robot state","OK"); plugin_status_->setLevel(rviz::StatusProperty::Level(0)); } path_line_=new rviz::BillboardLine(scene_manager_, scene_node_); } void trajectory_display::reset(){ MFDClass::reset(); updateLinkChoice(); path_line_->clear(); } void trajectory_display::updateLinkChoice(){ std::map<std::string, KDL::TreeElement>::const_iterator root; root=tree_.getRootSegment(); std::string root_link=root->first; std::string target_link=target_property_->getStdString(); //Setting up for chain from root to target link if(!tree_.getChain(root_link,target_link,chain_r2t_)){ ROS_ERROR("Cannot get chain from %s to %s.", root_link.c_str(),target_link.c_str()); setStatus(rviz::StatusProperty::Level(2),"Target link","Cannot get chain."); plugin_status_->setLevel(rviz::StatusProperty::Level(2)); } else { ROS_INFO("To-target chain updated from %s to %s.",root_link.c_str(),target_link.c_str()); kdlfk_r2t_=new KDL::ChainFkSolverPos_recursive(chain_r2t_); setStatus(rviz::StatusProperty::Level(0),"Target link","OK"); plugin_status_->setLevel(rviz::StatusProperty::Level(0)); } } void trajectory_display::updateRobotDescription(){ onInitialize(); } void trajectory_display::updateLineColorandAlpha(){ Ogre::ColourValue new_color=color_property_->getOgreColor(); new_color.a=alpha_property_->getFloat(); path_line_->setColor(new_color.r, new_color.g, new_color.b, new_color.a); context_->queueRender(); } void trajectory_display::updateLineWidth(){ float new_width=width_property_->getFloat(); path_line_->setLineWidth(new_width); context_->queueRender(); } void trajectory_display::processMessage(const display_trajectory_msgs::DisplayTrajectoryStamped::ConstPtr& msg){ path_line_->clear(); Ogre::Quaternion orientation; Ogre::Vector3 position; if( !context_->getFrameManager()->getTransform( msg->header.frame_id, msg->header.stamp, position, orientation )) { ROS_DEBUG( "Error transforming from frame '%s' to frame '%s'", msg->header.frame_id.c_str(), qPrintable( fixed_frame_ )); return; } path_line_->setPosition(position); path_line_->setOrientation(orientation); //Proceed only when status is OK if(plugin_status_->getLevel()==0){ int num_wayPoints=msg->moveit_display_trajectory.trajectory[0].joint_trajectory.points.size(); int num_joints_to_target=chain_r2t_.getNrOfJoints(); updateLineWidth(); updateLineColorandAlpha(); //Here is the tricky part and will need more work into this. KDL::JntArray q_in_target; q_in_target.resize(num_joints_to_target); for(size_t i=0; i<num_wayPoints; i++){ for(size_t k=0; k<num_joints_to_target; k++){ q_in_target(k)=msg->moveit_display_trajectory.trajectory[0].joint_trajectory.points[i].positions[k]; } KDL::Frame p_out_target; kdlfk_r2t_->JntToCart(q_in_target, p_out_target); KDL::Vector V=p_out_target.p; Ogre::Vector3 new_point{(double)V.x(), (double)V.y(), (double)V.z()}; path_line_->addPoint(new_point); } } } } #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(trajectory_display_ns::trajectory_display, rviz::Display)
38.364964
115
0.709285
YanzhouWang
9704beb9c7e8f67345dac4235bdce1d99220ae3a
173
hpp
C++
include/Game/Entities/Treats/MultiballTreat.hpp
FoxelCode/Barkanoid
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
[ "Unlicense" ]
null
null
null
include/Game/Entities/Treats/MultiballTreat.hpp
FoxelCode/Barkanoid
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
[ "Unlicense" ]
null
null
null
include/Game/Entities/Treats/MultiballTreat.hpp
FoxelCode/Barkanoid
3e582cbfb4bf13aa522d344489c8b0bac77fa8c5
[ "Unlicense" ]
null
null
null
#pragma once #include "Treat.hpp" class MultiballTreat : public Treat { public: MultiballTreat(sf::Vector2f pos, float launchAngle); void AddAward(PlayState* state); };
15.727273
53
0.751445
FoxelCode
9704e258106af9ac50f95c6e1251955b8cb30194
544
hpp
C++
include/executor_exam/throw_message_node.hpp
hsgwa/executer_exam
083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24
[ "Apache-2.0" ]
null
null
null
include/executor_exam/throw_message_node.hpp
hsgwa/executer_exam
083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24
[ "Apache-2.0" ]
null
null
null
include/executor_exam/throw_message_node.hpp
hsgwa/executer_exam
083d246a1bfaa4b87f0df0d9d73b9bb9ebaf8e24
[ "Apache-2.0" ]
1
2021-11-11T12:35:09.000Z
2021-11-11T12:35:09.000Z
#ifndef __THROW_MESSAGE_NODE_HPP__ #define __THROW_MESSAGE_NODE_HPP__ #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/string.hpp> namespace executor_test { class ThrowMessageNode : public rclcpp::Node { public: explicit ThrowMessageNode(const rclcpp::NodeOptions &options); private: rclcpp::TimerBase::SharedPtr timer_; rclcpp::Publisher<std_msgs::msg::String>::SharedPtr msg_pub_; uint64_t publish_count_; void cyclic_send_message(); }; } #endif
22.666667
74
0.674632
hsgwa
8ccbe8b685149a575057a1fe2341f07029c38dec
4,255
cpp
C++
src/shared/ai/RandomIA.cpp
StevenEnsea/plt
f36edc064c375b58b4add9de1caa56ee3fc41fce
[ "Apache-2.0" ]
null
null
null
src/shared/ai/RandomIA.cpp
StevenEnsea/plt
f36edc064c375b58b4add9de1caa56ee3fc41fce
[ "Apache-2.0" ]
null
null
null
src/shared/ai/RandomIA.cpp
StevenEnsea/plt
f36edc064c375b58b4add9de1caa56ee3fc41fce
[ "Apache-2.0" ]
null
null
null
#include "ai.h" #include "engine.h" #include "state.h" #include <iostream> #include <stdlib.h> #include <unistd.h> using namespace ai; using namespace engine; using namespace state; using namespace std; int RandomIA::run (engine::Engine& engine){ // L'IA effectue ces actions uniquement si c'est son tour //sleep(5); State state = engine.getState(); if(state.getPlaying()->getIa()==true){ int randomAction; std::pair<int,int> randomPosition; int randomAttaque; bool premierEssai = true; bool actionPossible=true; bool attaquePossible=true; Player* bot =state.getPlaying(); int randomDirection; int X, Y, range; std::vector<int> attaquesValides; srand(time(NULL)); while ((bot->getHp() > 0) && actionPossible){ clock_t start_time = clock(); while(clock()<start_time+100000); //sleep(1); if(premierEssai == true){ cout<< "\t [Controle par le CPU] " << endl; premierEssai = false; } /* * randomAction: 0 = deplacemnt * 1 = attaque * 2 = fin de tour * */ //to do augementer proba d'action en fct des pm pa restant if (bot->getMovement()==0 && (bot->getSkillCount()==0 || !attaquePossible)){ randomAction = 2; } else if (bot->getMovement()==0 && bot->getSkillCount()>0 && attaquePossible){ randomAction = rand()%2+1 ; } else if (bot->getMovement()>0 && (bot->getSkillCount()==0 || !attaquePossible)){ randomAction = rand()%2; if(randomAction == 1){ randomAction = 2; } } else{randomAction = rand()%3;} //cout<<"Action selectionné :"; // 0 : Cas du deplacement if (randomAction == 0){ //cout<<" déplacement"<<endl; randomDirection=rand()%4; if(randomDirection==0){ randomPosition = {bot->getX(),bot->getY()-1}; }else if(randomDirection==1){ randomPosition = {bot->getX()+1,bot->getY()}; }else if(randomDirection==2){ randomPosition = {bot->getX(),bot->getY()+1}; }else if(randomDirection==3){ randomPosition = {bot->getX()-1,bot->getY()}; } Move* move = new Move(randomPosition); engine.executeCommand(move); } // 1 : Cas de l'attaque else if (randomAction == 1){ //cout<<" attaque"<<endl; std::vector<Skill*> listeAttaques = bot-> getSkills(); for(size_t a=0;a<listeAttaques.size();a++){ if(listeAttaques[a]->getCooldown()<=0){ attaquesValides.push_back(a); } } if (attaquesValides.size() !=0){ //cout<<"attaques valides"<<endl; //choix aléatoire de l'attaque parmi les attaques possibles randomAttaque = attaquesValides[rand()%attaquesValides.size()]; //cout<<"attaque selectionné :"<<listeAttaques[randomAttaque]->getName()<<endl; //choix de la direction aléatoire randomDirection=rand()%4; if(randomDirection==0){ X=0; Y=-1; //cout<<"Direction : Nord"<<endl; }else if(randomDirection==1){ X=1; Y=0; //cout<<"Direction : Est"<<endl; }else if(randomDirection==2){ X=0; Y=1; //cout<<"Direction : Sud"<<endl; }else if(randomDirection==3){ X=-1; Y=0; //cout<<"Direction : Ouest"<<endl; } //choix de la case attaqué (range) aléatoire range=rand()%(listeAttaques[randomAttaque]->getRange().second -listeAttaques[randomAttaque]->getRange().first+1)+listeAttaques[randomAttaque]->getRange().first; randomPosition={bot->getX()+X*range,bot->getY()+Y*range}; // Commande d'attaque Attack* attack = new Attack(randomPosition , randomAttaque); engine.executeCommand(attack); }else{ cout<<"Le CPU n'a pas d'attaque possible"<<endl; attaquePossible=false; } } // 2 : Cas de fin d'actions else if (randomAction == 2){ //cout<<" fin de tour"<<endl; EndActions* endactions = new EndActions(); engine.executeCommand(endactions); actionPossible=false; return 0; } engine.getState().notifyObservers(engine.getState()); } //test verification hors boucle if(actionPossible == false){ cout<< "\t\t-> Action impossible pour le CPU " << bot->getName() << " <-" << endl; } } return 0; }
26.93038
165
0.602115
StevenEnsea
8ccc20dd11a86c904eb27573405378b304d03922
1,915
cpp
C++
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "WorkingWithProjects/ImportingAndExporting/ReadProjectUIDsFromXMLFile.h" #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object.h> #include <system/collections/list.h> #include <PrimaveraXmlReader.h> #include <cstdint> #include "RunExamples.h" namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace WorkingWithProjects { namespace ImportingAndExporting { RTTI_INFO_IMPL_HASH(681918485u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::ImportingAndExporting::ReadProjectUIDsFromXMLFile, ThisTypeBaseTypesInfo); void ReadProjectUIDsFromXMLFile::Run() { // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:ReadProjectUIDsFromXMLFile System::SharedPtr<PrimaveraXmlReader> reader = System::MakeObject<PrimaveraXmlReader>(dataDir + u"Project.xml"); System::SharedPtr<System::Collections::Generic::List<int32_t>> listOpProjectUids = reader->GetProjectUids(); // ExEnd:ReadProjectUIDsFromXMLFile } } // namespace ImportingAndExporting } // namespace WorkingWithProjects } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
36.826923
164
0.784856
aspose-tasks
8ccd7e504d55323da82c84b9662b782c3e668742
2,526
hpp
C++
include/oglplus/object/bound.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
include/oglplus/object/bound.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
include/oglplus/object/bound.hpp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
/** * @file oglplus/object/bound.hpp * @brief Operations on currently bound objects * * @author Matus Chochlik * * Copyright 2010-2015 Matus Chochlik. 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) */ #pragma once #ifndef OGLPLUS_OBJECT_BOUND_1405011014_HPP #define OGLPLUS_OBJECT_BOUND_1405011014_HPP #include <oglplus/object/name.hpp> namespace oglplus { template <typename ObjTag> class BoundObjOps { public: BoundObjOps(void) OGLPLUS_NOEXCEPT(true) { } template <typename X> BoundObjOps(X) OGLPLUS_NOEXCEPT(true) { } }; template <typename ObjTag> class ObjectOps<tag::CurrentBound, ObjTag> : public ObjZeroOps<tag::CurrentBound, ObjTag> , public BoundObjOps<ObjTag> { protected: ObjectOps(ObjectName<ObjTag> name) OGLPLUS_NOEXCEPT(true) : ObjZeroOps<tag::CurrentBound, ObjTag>(name) { } public: typedef typename BoundObjOps<ObjTag>::Target Target; #if !OGLPLUS_NO_DEFAULTED_FUNCTIONS ObjectOps(ObjectOps&&) = default; ObjectOps(const ObjectOps&) = default; ObjectOps& operator = (ObjectOps&&) = default; ObjectOps& operator = (const ObjectOps&) = default; #else typedef ObjZeroOps<tag::CurrentBound, ObjTag> _base1; typedef BoundObjOps<ObjTag> _base2; ObjectOps(ObjectOps&& temp) OGLPLUS_NOEXCEPT(true) : _base1(static_cast<_base1&&>(temp)) , _base2(static_cast<_base2&&>(temp)) { } ObjectOps(const ObjectOps& that) OGLPLUS_NOEXCEPT(true) : _base1(static_cast<const _base1&>(that)) , _base2(static_cast<const _base2&>(that)) { } ObjectOps& operator = (ObjectOps&& temp) OGLPLUS_NOEXCEPT(true) { _base1::operator = (static_cast<_base1&&>(temp)); _base2::operator = (static_cast<_base2&&>(temp)); return *this; } ObjectOps& operator = (const ObjectOps& that) OGLPLUS_NOEXCEPT(true) { _base1::operator = (static_cast<const _base1&>(that)); _base2::operator = (static_cast<const _base2&>(that)); return *this; } #endif }; template <typename ObjTag> class Reference<ObjectOps<tag::CurrentBound, ObjTag>> : public ObjectOps<tag::CurrentBound, ObjTag> { private: typedef ObjectOps<tag::CurrentBound, ObjTag> Base; public: Reference(void) : ObjectOps<tag::CurrentBound, ObjTag>( ObjBindingOps<ObjTag>::Binding() ) { } Reference(typename Base::Target init_tgt) : ObjectOps<tag::CurrentBound, ObjTag>( ObjBindingOps<ObjTag>::Binding(init_tgt) ) { this->target = init_tgt; } }; } // namespace oglplus #endif // include guard
22.756757
68
0.732779
Extrunder
8ccdc0abe43785e2014d73e8172ed2189027dbe4
4,964
cpp
C++
brickstone/src/math/vec3.cpp
GenTexX/brickstone
b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b
[ "MIT" ]
1
2019-10-10T12:30:14.000Z
2019-10-10T12:30:14.000Z
brickstone/src/math/vec3.cpp
GenTexX/brickstone
b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b
[ "MIT" ]
null
null
null
brickstone/src/math/vec3.cpp
GenTexX/brickstone
b7dcd9860fee04aa38d7cc4dcb5fbbd52c528d9b
[ "MIT" ]
1
2019-10-10T12:52:08.000Z
2019-10-10T12:52:08.000Z
#include <bspch.h> #include "Vec3.h" namespace bs { const vec3 vec3::up(0.0f, 1.0f, 0.0f); const vec3 vec3::down(0.0f, -1.0f, 0.0f); const vec3 vec3::right(1.0f, 0.0f, 0.0f); const vec3 vec3::left(-1.0f, 0.0f, 0.0f); const vec3 vec3::back(0.0f, 0.0f, -1.0f); const vec3 vec3::forward(0.0f, 0.0f, 1.0f); const vec3 vec3::one(1.0f, 1.0f, 1.0f); const vec3 vec3::zero(0.0f, 0.0f, 0.0f); vec3::vec3(const float &x, const float &y, const float &z) : x(x), y(y), z(z) { } vec3::vec3() : x(0), y(0), z(0) { } vec3::~vec3() { } float vec3::magnitude() { return (float)sqrt(this->x * this->x + this->y * this->y + this->z * this->z); } float vec3::sqrMagnitude() { return (float) (this->x * this->x + this->y * this->y + this->z * this->z); } vec3 vec3::normalized() { return *this /= this->magnitude(); } bool vec3::equals(vec3& other) { return *this == other; } vec3& vec3::add(const vec3& other) { this->x += other.x; this->y += other.y; this->z += other.z; return *this; } vec3& vec3::sub(const vec3& other) { this->x -= other.x; this->y -= other.y; this->z -= other.z; return *this; } vec3& vec3::mult(const vec3& other) { this->x *= other.x; this->y *= other.y; this->z *= other.z; return *this; } vec3& vec3::div(const vec3& other) { this->x /= other.x; this->y /= other.y; this->z /= other.z; return *this; } vec3& vec3::add(const float& other) { this->x += other; this->y += other; this->z += other; return *this; } vec3& vec3::sub(const float& other) { this->x -= other; this->y -= other; this->z -= other; return *this; } vec3& vec3::mult(const float& other) { this->x *= other; this->y *= other; this->z *= other; return *this; } vec3& vec3::div(const float& other) { this->x /= other; this->y /= other; this->z /= other; return *this; } vec3& vec3::operator+=(const vec3& other) { return this->add(other); } vec3& vec3::operator-=(const vec3& other) { return this->sub(other); } vec3& vec3::operator*=(const vec3& other) { return this->mult(other); } vec3& vec3::operator/=(const vec3& other) { return this->div(other); } vec3& vec3::operator+=(const float& other) { return this->add(other); } vec3& vec3::operator-=(const float& other) { return this->sub(other); } vec3& vec3::operator*=(const float& other) { return this->mult(other); } vec3& vec3::operator/=(const float& other) { return this->div(other); } bool vec3::operator==(const vec3& other) { return (this->x == other.x && this->y == other.y && this->z == other.z); } bool vec3::operator!=(const vec3& other) { return !(this->x == other.x && this->y == other.y && this->z == other.z); } bool vec3::operator>(vec3& other) { return (this->sqrMagnitude() > other.sqrMagnitude()); } bool vec3::operator<(vec3& other) { return (this->sqrMagnitude() < other.sqrMagnitude()); } bool vec3::operator>=(vec3& other) { return (this->sqrMagnitude() >= other.sqrMagnitude()); } bool vec3::operator<=(vec3& other) { return (this->sqrMagnitude() <= other.sqrMagnitude()); } vec3 operator+(vec3 left, const vec3& right) { return left.add(right); } vec3 operator-(vec3 left, const vec3& right) { return left.sub(right); } vec3 operator*(vec3 left, const vec3& right) { return left.mult(right);; } vec3 operator/(vec3 left, const vec3& right) { return left.div(right);; } vec3 operator+(vec3 left, const float& right) { left.add(right); return left; } vec3 operator-(vec3 left, const float& right) { left.sub(right); return left; } vec3 operator*(vec3 left, const float& right) { left.mult(right); return left; } vec3 operator/(vec3 left, const float& right) { left.div(right); return left; } vec3 operator+(const float& left, vec3 right) { right.add(left); return right; } vec3 operator*(const float& left, vec3 right) { right.mult(left); return right; } std::ostream& operator<<(std::ostream& stream, vec3& vector) { stream << vector.toString(); return stream; } float vec3::dot(const vec3& left, const vec3& right) { return left.x * right.x + left.y * right.y + left.z * left.z; } vec3 vec3::cross(const vec3& left, const vec3& right) { return vec3(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x); } float vec3::distance(const vec3& left, const vec3& right) { return (left - right).magnitude(); } float vec3::sqrDistance(const vec3& left, const vec3& right) { return (left - right).sqrMagnitude(); } vec3 vec3::lerp(const vec3& left, const vec3& right, const float& t) { return ((right - left) * t) + left; } std::string vec3::toString() { return "(" + std::to_string(this->x) + " | " + std::to_string(this->y) + " | " + std::to_string(this->z) + ")"; } }
15.368421
125
0.595085
GenTexX
8ccfbe147c1ddb00c6b36131edb47a96d2caf253
16,631
cp
C++
Std/Mod/Stamps.cp
romiras/Blackbox-fw-playground
6de94dc65513e657a9b86c1772e2c07742b608a8
[ "BSD-2-Clause" ]
1
2016-03-17T08:27:05.000Z
2016-03-17T08:27:05.000Z
Std/Mod/Stamps.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
null
null
null
Std/Mod/Stamps.cps
Spirit-of-Oberon/LightBox
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
[ "BSD-2-Clause" ]
1
2018-03-14T17:53:27.000Z
2018-03-14T17:53:27.000Z
MODULE StdStamps; (** project = "BlackBox" organization = "www.oberon.ch" contributors = "Oberon microsystems" version = "System/Rsrc/About" copyright = "System/Rsrc/About" license = "Docu/BB-License" changes = "" issues = "" **) (* StdStamps are used to keep track of document changes, in particular program texts. StdStamps carry a sequence number and a fingerprint of the document with them. Each time the document (and therefore its fingerprint) is changed and stored, the sequence number is incremented. (When determining the fingerprint of the document, whitespace is ignored, except in string literals.) Each StdStamp also keeps track of the history of most recent changes. For the last maxHistoryEntries sequence numbers, the date and time, and an optional one-line comment is stored. To avoid too many entries in the history while working on a module, the most recent history entry is overwritten upon the generation of a new sequence number if the current date is the same as the date in the history entry. *) IMPORT SYSTEM, (* SYSTEM.ROT only, for fingerprint calculation *) Strings, Dates, StdCmds, Ports, Models, Stores, Containers, Properties, Views, Controllers, Fonts, TextModels, TextSetters, TextMappers, TextViews, TextRulers; CONST setCommentKey = "#Std:Set Comment"; maxHistoryEntries = 25; minVersion = 0; origStampVersion = 0; thisVersion = 2; TYPE History = ARRAY maxHistoryEntries OF RECORD fprint, snr: INTEGER; (* fingerprint, sequence number *) date: INTEGER; (* days since 1/1/1 *) time: INTEGER; (* min + 64 * hour *) comment: POINTER TO ARRAY OF CHAR; (* nil if no comment *) END; StdView = POINTER TO RECORD (Views.View) (*--snr: LONGINT;*) nentries: INTEGER; (* number of entries in history *) history: History; (* newest entry in history[0] *) cache: ARRAY 64 OF CHAR; END; SetCmtOp = POINTER TO RECORD (Stores.Operation) stamp: StdView; oldcomment: POINTER TO ARRAY OF CHAR; END; VAR comment*: RECORD s*: ARRAY 64 OF CHAR; END; PROCEDURE (op: SetCmtOp) Do; VAR temp: POINTER TO ARRAY OF CHAR; BEGIN temp := op.stamp.history[0].comment; op.stamp.history[0].comment := op.oldcomment; op.oldcomment := temp; END Do; PROCEDURE Format (v: StdView); VAR s: ARRAY 64 OF CHAR; d: Dates.Date; t: INTEGER; BEGIN t := v.history[0].time; Dates.DayToDate(v.history[0].date, d); Dates.DateToString(d, Dates.plainAbbreviated, s); v.cache := s$; Strings.IntToStringForm(v.history[0].snr, Strings.decimal, 4, "0", FALSE, s); v.cache := v.cache + " (" + s + ")" END Format; PROCEDURE FontContext (v: StdView): Fonts.Font; VAR c: Models.Context; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN RETURN c(TextModels.Context).Attr().font; ELSE RETURN Fonts.dir.Default() END; END FontContext; PROCEDURE CalcFP (t: TextModels.Model): INTEGER; CONST sglQuote = "'"; dblQuote = '"'; VAR fp: INTEGER; rd: TextModels.Reader; ch, quoteChar: CHAR; BEGIN quoteChar := 0X; fp := 0; rd := t.NewReader(NIL); rd.ReadChar(ch); WHILE ~rd.eot DO IF ch = quoteChar THEN quoteChar := 0X; ELSIF (quoteChar = 0X) & ((ch = dblQuote) OR (ch = sglQuote)) THEN quoteChar := ch; END; IF (quoteChar = 0X) & (21X <= ch) & (ch # 8BX) & (ch # 8FX) & (ch # 0A0X) (* not in string literal *) OR (quoteChar # 0X) & (20X <= ch) (* within string literal *) THEN fp := SYSTEM.ROT(fp, 1) + 13 * ORD(ch); END; rd.ReadChar(ch); END; RETURN fp; END CalcFP; PROCEDURE Update (v: StdView; forcenew: BOOLEAN); VAR fp: INTEGER; i: INTEGER; ndays: INTEGER; d: Dates.Date; t: Dates.Time; BEGIN IF (v.context # NIL) & (v.context IS TextModels.Context) THEN fp := CalcFP(v.context(TextModels.Context).ThisModel()); IF (fp # v.history[0].fprint) OR forcenew THEN Dates.GetDate(d); Dates.GetTime(t); ndays := Dates.Day(d); IF (ndays # v.history[0].date) OR forcenew THEN (* move down entries in history list *) i := maxHistoryEntries-1; WHILE i > 0 DO v.history[i] := v.history[i-1]; DEC(i); END; v.history[0].comment := NIL; END; IF v.nentries < maxHistoryEntries THEN INC(v.nentries) END; INC(v.history[0].snr); v.history[0].fprint := fp; v.history[0].date := ndays; v.history[0].time := t.minute + t.hour*64; Format(v); Views.Update(v, Views.keepFrames); END; END; END Update; PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer); VAR i, len: INTEGER; BEGIN Update(v, FALSE); v.Externalize^(wr); wr.WriteVersion(thisVersion); (*--wr.WriteLInt(v.snr);*) wr.WriteXInt(v.nentries); FOR i := 0 TO v.nentries-1 DO wr.WriteInt(v.history[i].fprint); wr.WriteInt(v.history[i].snr); wr.WriteInt(v.history[i].date); wr.WriteXInt(v.history[i].time); IF v.history[i].comment # NIL THEN len := LEN(v.history[i].comment$); wr.WriteXInt(len); wr.WriteXString(v.history[i].comment^); ELSE wr.WriteXInt(0); END END; END Externalize; PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader); VAR version: INTEGER; format: BYTE; i, len: INTEGER; d: Dates.Date; t: Dates.Time; BEGIN v.Internalize^(rd); IF ~rd.cancelled THEN rd.ReadVersion(minVersion, thisVersion, version); IF ~rd.cancelled THEN IF version = origStampVersion THEN (* deal with old StdStamp format *) (* would like to calculate fingerprint, but hosting model not available at this time *) v.history[0].fprint := 0; v.history[0].snr := 1; v.nentries := 1; rd.ReadXInt(d.year); rd.ReadXInt(d.month); rd.ReadXInt(d.day); rd.ReadXInt(t.hour); rd.ReadXInt(t.minute); rd.ReadXInt(t.second); rd.ReadByte(format); (* format not used anymore *) v.history[0].date := Dates.Day(d); v.history[0].time := t.minute + t.hour*64; ELSE IF version = 1 THEN rd.ReadInt(v.history[0].snr) END; (* red text: to be removed soon *) rd.ReadXInt(v.nentries); FOR i := 0 TO v.nentries-1 DO rd.ReadInt(v.history[i].fprint); IF version > 1 THEN rd.ReadInt(v.history[i].snr) ELSIF (* (version = 1) & *) i > 0 THEN v.history[i].snr := v.history[i-1].snr - 1; END; (* red text: to be removed soon *) rd.ReadInt(v.history[i].date); rd.ReadXInt(v.history[i].time); rd.ReadXInt(len); IF len > 0 THEN NEW(v.history[i].comment, len + 1); rd.ReadXString(v.history[i].comment^); ELSE v.history[i].comment := NIL; END END; END; Format(v); END END END Internalize; PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View); VAR i: INTEGER; BEGIN (* v.CopyFrom^(source); *) WITH source: StdView DO (*--v.snr := source.snr;*) v.nentries := source.nentries; v.history := source.history; v.cache := source.cache; FOR i := 0 TO v.nentries - 1 DO IF source.history[i].comment # NIL THEN NEW(v.history[i].comment, LEN(source.history[i].comment$) + 1); v.history[i].comment^ := source.history[i].comment^$; END END END END CopyFromSimpleView; PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER); VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font; asc, dsc, fw: INTEGER; BEGIN c := v.context; IF (c # NIL) & (c IS TextModels.Context) THEN a := v.context(TextModels.Context).Attr(); font := a.font; color := a.color; ELSE font := Fonts.dir.Default(); color := Ports.black; END; font.GetBounds(asc, dsc, fw); f.DrawLine(f.l, asc + f.dot, f.r, asc + f.dot, 1, Ports.grey25 ); f.DrawString(0, asc, color, v.cache, font); END Restore; PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref); VAR font: Fonts.Font; asc, dsc, w: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR; BEGIN font := FontContext(v); font.GetBounds(asc, dsc, w); d.day := 28; d.month := 1; d.year := 2222; p.w := 0; WHILE d.month <= 12 DO Dates.DateToString(d, Dates.plainAbbreviated, s); s := s + " (0000)"; w := font.StringWidth(s); IF w > p.w THEN p.w := w END; INC(d.month) END; p.h := asc + dsc; END SizePref; PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message); VAR font: Fonts.Font; asc, w: INTEGER; BEGIN WITH msg: Properties.Preference DO WITH msg: Properties.SizePref DO SizePref(v, msg) | msg: Properties.ResizePref DO msg.fixed := TRUE | msg: Properties.FocusPref DO msg.hotFocus := TRUE | msg: TextSetters.Pref DO font := FontContext(v); font.GetBounds(asc, msg.dsc, w); ELSE END ELSE END END HandlePropMsg; PROCEDURE NewRuler (): TextRulers.Ruler; CONST mm = Ports.mm; VAR r: TextRulers.Ruler; BEGIN r := TextRulers.dir.New(NIL); TextRulers.SetRight(r, 140 * mm); TextRulers.AddTab(r, 15 * mm); TextRulers.AddTab(r, 35 * mm); TextRulers.AddTab(r, 75 * mm); RETURN r END NewRuler; PROCEDURE ShowHistory (v: StdView); VAR text: TextModels.Model; f: TextMappers.Formatter; i: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR; tv: TextViews.View; attr: TextModels.Attributes; BEGIN text := TextModels.dir.New(); f.ConnectTo(text); attr := f.rider.attr; f.rider.SetAttr(TextModels.NewStyle(attr, {Fonts.italic})); f.WriteString("seq nr."); f.WriteTab; f.WriteString("fingerprint"); f.WriteTab; f.WriteString("date and time"); f.WriteTab; f.WriteString("comment"); f.WriteLn; f.rider.SetAttr(attr); f.WriteLn; (*--n := v.snr;*) FOR i := 0 TO v.nentries-1 DO f.WriteIntForm(v.history[i].snr, 10, 4, "0", FALSE); (*--DEC(n);*) f.WriteTab; f.WriteIntForm(v.history[i].fprint, TextMappers.hexadecimal, 8, "0", FALSE); f.WriteTab; Dates.DayToDate(v.history[i].date, d); Dates.DateToString(d, Dates.plainAbbreviated, s); f.WriteString(s); f.WriteString(" "); f.WriteIntForm(v.history[i].time DIV 64, 10, 2, "0", FALSE); f.WriteString(":"); f.WriteIntForm(v.history[i].time MOD 64, 10, 2, "0", FALSE); IF v.history[i].comment # NIL THEN f.WriteTab; f.WriteString( v.history[i].comment^); END; f.WriteLn; END; tv := TextViews.dir.New(text); tv.SetDefaults(NewRuler(), TextViews.dir.defAttr); tv.ThisController().SetOpts({Containers.noFocus, Containers.noCaret}); Views.OpenAux(tv, "History"); END ShowHistory; PROCEDURE Track (v: StdView; f: Views.Frame; x, y: INTEGER; buttons: SET); VAR c: Models.Context; w, h: INTEGER; isDown, in, in0: BOOLEAN; m: SET; BEGIN c := v.context; c.GetSize(w, h); in0 := FALSE; in := TRUE; REPEAT IF in # in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); in0 := in END; f.Input(x, y, m, isDown); in := (0 <= x) & (x < w) & (0 <= y) & (y < h) UNTIL ~isDown; IF in0 THEN f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide); IF Controllers.modify IN m THEN IF v.history[0].comment # NIL THEN comment.s := v.history[0].comment^$; ELSE comment.s := ""; END; StdCmds.OpenToolDialog("Std/Rsrc/Stamps", "Comment"); ELSE ShowHistory(v); END END END Track; PROCEDURE (v: StdView) HandleCtrlMsg ( f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View); BEGIN WITH msg: Controllers.TrackMsg DO Track(v, f, msg.x, msg.y, msg.modifiers) | msg: Controllers.PollCursorMsg DO msg.cursor := Ports.refCursor ELSE END END HandleCtrlMsg; (* ------------ programming interface: ---------------------- *) PROCEDURE GetFirstInText* (t: TextModels.Model): Views.View; VAR r: TextModels.Reader; v: Views.View; BEGIN IF t # NIL THEN r := t.NewReader(NIL); REPEAT r.ReadView(v) UNTIL (v = NIL) OR (v IS StdView); RETURN v; ELSE RETURN NIL; END; END GetFirstInText; PROCEDURE IsStamp* (v: Views.View): BOOLEAN; BEGIN RETURN v IS StdView; END IsStamp; PROCEDURE GetInfo* (v: Views.View; VAR snr, historylen: INTEGER); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO snr := v.history[0].snr; historylen := v.nentries; END END GetInfo; PROCEDURE GetData* (v: Views.View; entryno: INTEGER; VAR fprint: INTEGER; VAR date: Dates.Date; VAR time: Dates.Time); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO IF entryno <= v.nentries THEN fprint := v.history[entryno].fprint; Dates.DayToDate(v.history[entryno].date, date); time.minute := v.history[entryno].time MOD 64; time.minute := v.history[entryno].time DIV 64; time.second := 0; END END END GetData; (** Insert new history entry with comment in v. *) PROCEDURE Stamp* (v: Views.View; comment: ARRAY OF CHAR); BEGIN ASSERT(v IS StdView, 20); WITH v: StdView DO Update(v, TRUE); NEW(v.history[0].comment, LEN(comment$) + 1); v.history[0].comment^ := comment$; END END Stamp; PROCEDURE New* (): Views.View; VAR v: StdView; d: Dates.Date; t: Dates.Time; BEGIN NEW(v); v.history[0].snr := 0; v.nentries := 0; v.history[0].fprint := 0; Dates.GetDate(d); Dates.GetTime(t); v.history[0].date := Dates.Day(d); v.history[0].time := t.minute + t.hour*64; Format(v); RETURN v; END New; PROCEDURE SetComment*; VAR v: Views.View; op: SetCmtOp; BEGIN v := GetFirstInText(TextViews.FocusText()); IF v # NIL THEN WITH v: StdView DO NEW(op); op.stamp := v; NEW(op.oldcomment, LEN(comment.s$) + 1); op.oldcomment^ := comment.s$; Views.Do(v, setCommentKey, op); END END END SetComment; PROCEDURE Deposit*; BEGIN Views.Deposit(New()) END Deposit; END StdStamps.
37.373034
113
0.52793
romiras
8cd4fd710f3c18a8622b605dc0e595f513b4ca51
354
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlAttributeAttribute.Namespace Example/CPP/source.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
#using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; using namespace System::Xml::Serialization; // <Snippet1> public ref class Car { public: [XmlAttributeAttribute(Namespace="Make")] String^ MakerName; [XmlAttributeAttribute(Namespace="Model")] String^ ModelName; }; // </Snippet1>
15.391304
45
0.723164
BaruaSourav
8cd69161a48a2981e3173a0b39c7f7fce5fbda19
28
cpp
C++
FootCommander.cpp
amit1021/wargame-a
d46702bf56aff054469eae864fbb59cb87728065
[ "MIT" ]
null
null
null
FootCommander.cpp
amit1021/wargame-a
d46702bf56aff054469eae864fbb59cb87728065
[ "MIT" ]
null
null
null
FootCommander.cpp
amit1021/wargame-a
d46702bf56aff054469eae864fbb59cb87728065
[ "MIT" ]
null
null
null
#include "FootCommander.hpp"
28
28
0.821429
amit1021
8cda95fd83e580f2cd1abf917f21598d4332a6a2
1,589
hpp
C++
src/config.hpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
null
null
null
src/config.hpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
1
2019-05-20T16:47:28.000Z
2019-05-20T16:47:28.000Z
src/config.hpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
null
null
null
#ifndef CONFIG_HPP #define CONFIG_HPP #include <QSettings> #include <QMap> #define CONFIG_SLEEP_STR "watcher_sleep_ms" #define CONFIG_START_MIN_STR "start_minimized" #define CONFIG_ENABLED_STR "enabled" #define CONFIG_AUTOHIDE_STR "autohide" #define CONFIG_TRAY_INFO_SHOWN "tray_icon_warning_shown" #define CONFIG_DEFAULT_PROFILE_STR "default" using DVC_map = QMap<int,int>; class Config : public QSettings { public: Config() noexcept; QVariant getValue(const QString &key, const QVariant &defaultValue = QVariant()) const noexcept; void setValue(const QString &key, const QVariant &value) noexcept; QStringList queryProfiles() noexcept; bool get_bool(const QString &attribute) { return getValue(attribute).toBool(); } bool set_bool(const QString &attribute, bool val) { setValue(attribute, val); return val; } bool toggle_bool(const QString &attribute) { return set_bool(attribute, !get_bool(attribute)); } QString queryIconPath(const QString &profile_name) noexcept; void setIconPath(const QString &profile_name, const QString &path) noexcept; DVC_map queryDVC(const QString &profile_name) noexcept; void setDVC(const QString &profile_name, DVC_map &map) noexcept; unsigned querySleepTime_ms(void) noexcept; void setSleepTime_ms(unsigned ms) noexcept; void removeProfile(const QString &key) noexcept; }; #endif // CONFIG_HPP
29.425926
104
0.674638
tpruzina
8cdb79234c0934d62035d0a852b2e11fc2917b3e
3,019
hpp
C++
include/message.hpp
astuff/can_dbc_loader
ce97f5cf7b002e5faca367c50f33fff2dcde2c43
[ "MIT" ]
9
2019-10-23T15:00:06.000Z
2021-04-02T01:45:26.000Z
include/message.hpp
astuff/can_dbc_loader
ce97f5cf7b002e5faca367c50f33fff2dcde2c43
[ "MIT" ]
null
null
null
include/message.hpp
astuff/can_dbc_loader
ce97f5cf7b002e5faca367c50f33fff2dcde2c43
[ "MIT" ]
5
2020-04-30T03:45:13.000Z
2021-11-25T05:28:16.000Z
// Copyright (c) 2019 AutonomouStuff, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef MESSAGE_HPP_ #define MESSAGE_HPP_ #include "common_defs.hpp" #include "bus_node.hpp" #include "comment.hpp" #include "signal.hpp" #include <memory> #include <string> #include <unordered_map> #include <vector> namespace AS { namespace CAN { namespace DbcLoader { class Message : public DbcObj, public AttrObj { public: Message(std::string && dbc_text); Message( unsigned int id, std::string && name, unsigned char dlc, BusNode && transmitting_node, std::vector<Signal> && signals); ~Message() = default; Message(const Message & other); Message(Message && other) = default; Message & operator=(const Message & other); Message & operator=(Message && other) = default; unsigned int getId() const; std::string getName() const; unsigned char getDlc() const; unsigned char getLength() const; BusNode getTransmittingNode() const; std::unordered_map<std::string, const Signal *> getSignals() const; const std::string * getComment() const; static unsigned char dlcToLength(const unsigned char & dlc); friend class Database; friend class MessageTranscoder; private: unsigned int id_; std::string name_; unsigned char dlc_; BusNode transmitting_node_; std::unordered_map<std::string, Signal> signals_; std::unique_ptr<std::string> comment_; void generateText() override; void parse() override; }; class MessageTranscoder { public: MessageTranscoder(Message * dbc_msg); const Message * getMessageDef(); void decode(std::vector<uint8_t> && raw_data, TranscodeError * err = nullptr); std::vector<uint8_t> encode(TranscodeError * err = nullptr); private: void decodeRawData(TranscodeError * err); Message * msg_def_; std::vector<uint8_t> data_; std::unordered_map<std::string, SignalTranscoder> signal_xcoders_; }; } // namespace DbcLoader } // namespace CAN } // namespace AS #endif // MESSAGE_HPP_
28.752381
80
0.735012
astuff
8ce13ff806babb1ef5d71e52db54a76d89500c3b
1,373
cpp
C++
matrix/module/DropoutLayer.cpp
xiaohuihuichao/matrix
1500b398fe96ee308990dd14590df2b76aba3dad
[ "ICU" ]
6
2019-02-11T09:50:45.000Z
2021-07-31T03:27:11.000Z
matrix/module/DropoutLayer.cpp
xiaohuihuichao/matrix
1500b398fe96ee308990dd14590df2b76aba3dad
[ "ICU" ]
null
null
null
matrix/module/DropoutLayer.cpp
xiaohuihuichao/matrix
1500b398fe96ee308990dd14590df2b76aba3dad
[ "ICU" ]
1
2021-04-25T12:31:03.000Z
2021-04-25T12:31:03.000Z
#include "DropoutLayer.hpp" namespace mario { DropoutLayer::DropoutLayer(const int &_lastNeuronNum, const double &_p) { m_p = _p; m_in = matrix(1, _lastNeuronNum, 0); m_mul = matrix(1, _lastNeuronNum, 0); m_out = matrix(1, _lastNeuronNum, 0); m_dx = matrix(1, _lastNeuronNum, 0); } const matrix& DropoutLayer::forward(const matrix &_lastOut) { if (_lastOut.cols() != m_in.cols()) { throw "Error in DropoutLayer::forward(): _lastOut.cols() != m_in.cols()."; } m_in.release(); m_in = _lastOut; #if 1==TRAIN matrix deleteMul(1, m_in.cols(), 0); for (int c = 0; c < deleteMul.cols(); ++c) { if (isDelete()) { deleteMul.set(0, c, 0); } else { deleteMul.set(0, c, 1); } } #endif // 1==TRAIN #if 0==TRAIN matrix deleteMul(1, m_in.cols(), 1); #endif // 0==TRAIN m_mul.release(); m_mul = copyRow(deleteMul, _lastOut.rows()); m_out.release(); m_out = m_mul.mul(_lastOut); return m_out; } const matrix& DropoutLayer::backward(const matrix &_nextDerr) { if (m_dx.cols() != _nextDerr.cols()) { throw "Error in DropoutLayer::backward(): m_dx.cols() != _nextDerr.cols().\n"; } m_dx.release(); m_dx = m_mul.mul(_nextDerr); return m_dx; } bool DropoutLayer::isDelete() { double p = rand() / double(RAND_MAX); if (p < m_p) { return true; } return false; } }
16.152941
81
0.612527
xiaohuihuichao
8ce85cbe115c3eaf335aec9520d6771c5923f882
2,306
cpp
C++
examples/Scrolling/Scrolling.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
examples/Scrolling/Scrolling.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
examples/Scrolling/Scrolling.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2009 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #include <vaca/vaca.h> #include "../resource.h" using namespace vaca; ////////////////////////////////////////////////////////////////////// class ScrollableTest : public ScrollableWidget { // true if we have to wait some milliseconds after update the // invalidated area bool m_sleep; public: ScrollableTest(Widget* parent) : ScrollableWidget(parent) , m_sleep(false) { setFullSize(Size(2000, 1500)); // the red color will be used to erase the background of // invalidated area, but in onPaint the red will be re-erased with // a white brush setBgColor(Color::Red); } void setSleep(bool sleep) { m_sleep = sleep; } protected: virtual void onPaint(PaintEvent& ev) { Graphics& g = ev.getGraphics(); // this sleep have the purpose to show the invalidated areas 100 // milliseconds (the background filled by default with the // getBgColor, that in this case is Color::Red) if (m_sleep) CurrentThread::sleep(100); // draw the (white) background Brush brush(Color::White); g.fillRect(brush, getClientBounds()); // draw the shapes (ellipses and round-rectangles) Pen pen(Color::Blue); Point offset = -getScrollPoint(); for (int r=0; r<10; ++r) { Rect rc(offset, getFullSize()); rc.shrink(50 * r); g.drawEllipse(pen, rc); g.drawRoundRect(pen, rc, Size(32, 32)); } } }; ////////////////////////////////////////////////////////////////////// void updateSleep(ScrollableTest* s, CheckBox* cb) { s->setSleep(cb->isSelected()); } int VACA_MAIN() { Application app; Frame frm(L"Scrolling"); ScrollableTest wgt(&frm); CheckBox sleep(L"Show invalidated areas for some milliseconds", &frm); sleep.Click.connect(Bind<void>(&updateSleep, &wgt, &sleep)); wgt.setConstraint(new BoxConstraint(true)); frm.setLayout(new BoxLayout(Orientation::Vertical, false)); frm.setIcon(ResourceId(IDI_VACA)); frm.setVisible(true); app.run(); return 0; }
24.531915
73
0.606678
picrap
8ce922f71f5ddd81ed293609b080050c360b16e3
708
cpp
C++
1100/90/1196a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1100/90/1196a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1100/90/1196a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <algorithm> #include <array> #include <iostream> using integer = long long; template <typename T, size_t N> std::istream& operator >>(std::istream& input, std::array<T, N>& v) { for (T& a : v) input >> a; return input; } void answer(integer v) { std::cout << v << '\n'; } void solve(std::array<integer, 3>& v) { std::sort(v.begin(), v.end()); const integer d = std::min(v[1] - v[0], v[2]); v[0] += d; v[2] -= d; answer(v[0] < v[1] ? v[0] : v[0] + v[2] / 2); } void test_case() { std::array<integer, 3> v; std::cin >> v; solve(v); } int main() { size_t t; std::cin >> t; while (t-- > 0) test_case(); return 0; }
14.16
67
0.507062
actium
8ce9b13579ba3a267f73417c070ea22855259089
19,164
cpp
C++
plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
5
2016-04-18T23:12:51.000Z
2022-03-06T05:12:07.000Z
plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
2
2015-10-09T19:13:25.000Z
2018-12-25T17:16:54.000Z
plugins/VFS/vfspluginVP/src/vfspluginVP_CVPArchive.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
15
2015-02-23T16:35:28.000Z
2022-03-25T13:40:33.000Z
/* * vfspluginVP: Generic GUCEF VFS plugin for "Violation Pack" archives * Copyright (C) 2002 - 2008. Dinand Vanvelzen * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #include <string.h> #ifndef GUCEF_CORE_DVMD5UTILS_H #include "dvmd5utils.h" #define GUCEF_CORE_DVMD5UTILS_H #endif /* GUCEF_CORE_DVMD5UTILS_H ? */ #ifndef GUCEF_CORE_CDYNAMICBUFFER_H #include "CDynamicBuffer.h" #define GUCEF_CORE_CDYNAMICBUFFER_H #endif /* GUCEF_CORE_CDYNAMICBUFFER_H ? */ #ifndef GUCEF_CORE_CDYNAMICBUFFERACCESS_H #include "CDynamicBufferAccess.h" #define GUCEF_CORE_CDYNAMICBUFFERACCESS_H #endif /* GUCEF_CORE_CDYNAMICBUFFERACCESS_H ? */ #ifndef GUCEF_CORE_CSUBFILEACCESS_H #include "gucefCORE_CSubFileAccess.h" #define GUCEF_CORE_CSUBFILEACCESS_H #endif /* GUCEF_CORE_CSUBFILEACCESS_H ? */ #ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H #include "dvcppstringutils.h" #define GUCEF_CORE_DVCPPSTRINGUTILS_H #endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */ #include "vfspluginVP_CVPArchive.h" /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace VFSPLUGIN { namespace VP { /*-------------------------------------------------------------------------// // // // TYPES // // // //-------------------------------------------------------------------------*/ struct SVPFileIndexEntry { VFS::UInt32 offset; VFS::UInt32 size; char filename[ 32 ]; VFS::Int32 timestamp; }; typedef struct SVPFileIndexEntry TVPFileIndexEntry; /*-------------------------------------------------------------------------// // // // CONSTANTS // // // //-------------------------------------------------------------------------*/ #define VP_HEADER_SIZE 16 #define VP_INDEX_ENTRY_SIZE 44 /*-------------------------------------------------------------------------// // // // GLOBAL VARS // // // //-------------------------------------------------------------------------*/ const VFS::CString CVPArchive::VPArchiveTypeName = "vp"; /*-------------------------------------------------------------------------// // // // UTILITIES // // // //-------------------------------------------------------------------------*/ CVPArchive::CVPArchive( void ) : CArchive() , m_header() , m_index() , m_archiveName() , m_archivePath() {GUCEF_TRACE; } /*-------------------------------------------------------------------------*/ CVPArchive::~CVPArchive() {GUCEF_TRACE; UnloadArchive(); } /*-------------------------------------------------------------------------*/ VFS::CArchive::CVFSHandlePtr CVPArchive::GetFile( const VFS::CString& file , const char* mode , const VFS::UInt32 memLoadSize , const bool overwrite ) {GUCEF_TRACE; GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: request to get file: " + file ); // We only support read only modes if ( *mode != 'r' ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: Unable to support requested file access mode for file: " + file ); return CVFSHandlePtr(); } // load the file CORE::CIOAccess* fileAccess = LoadFile( file, memLoadSize ); if ( NULL != fileAccess ) { // create a handle for the file VFS::CString filePath = m_archivePath; CORE::AppendToPath( filePath, file ); VFS::CVFSHandle* fileHandle = new VFS::CVFSHandle( fileAccess , file , filePath ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: providing access to file: " + file ); return CVFSHandlePtr( fileHandle, this ); } GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: Unable to provide access to file: " + file ); return CVFSHandlePtr(); } /*-------------------------------------------------------------------------*/ bool CVPArchive::DeleteFile( const VFS::CString& filePath ) {GUCEF_TRACE; // Not implemented / supported at this time return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::StoreAsFile( const CORE::CString& filepath , const CORE::CDynamicBuffer& data , const CORE::UInt64 offset , const bool overwrite ) {GUCEF_TRACE; // Not implemented / supported at this time return false; } /*-------------------------------------------------------------------------*/ void CVPArchive::GetList( TStringSet& outputList , const VFS::CString& mountLocation , const VFS::CString& archiveLocation , bool recursive , bool includePathInFilename , const VFS::CString& filter , bool addFiles , bool addDirs ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.begin(); while ( i != m_index.end() ) { // Check if the starting path matches const VFS::CString& filePath = (*i).first; if ( filePath == archiveLocation ) { // Don't add the location itself to the list ++i; continue; } if ( 0 == filePath.HasSubstr( archiveLocation, true ) ) { const TVPIndexEntry& indexEntry = (*i).second; // Check if the entry is a directory if ( indexEntry.size == 0 || indexEntry.offset == 0 ) { if ( !addDirs ) { // Skip this item ++i; continue; } } else { if ( !addFiles ) { // Skip this item ++i; continue; } } if ( !recursive ) { // Check if we have multiple subdirs beyond the "location" to get to // the archive. If so then we cannot add this archive because recursive // searching is not allowed. if ( !CORE::IsFileInDir( archiveLocation, filePath ) ) { // The directory seperator was not the last character so we have multiple // sub-dirs which is not allowed, we cannot add this item ++i; continue; } } VFS::CString filename = CORE::ExtractFilename( filePath ); if ( filename != ".." ) { if ( includePathInFilename ) { outputList.insert( filePath ); } else { outputList.insert( filename ); } } } ++i; } } /*-------------------------------------------------------------------------*/ bool CVPArchive::FileExists( const VFS::CString& filePath ) const {GUCEF_TRACE; GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "CVPArchive: request to check if file exists: " + filePath ); return m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ) != m_index.end(); } /*-------------------------------------------------------------------------*/ VFS::UInt32 CVPArchive::GetFileSize( const VFS::CString& filePath ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ); if ( i != m_index.end() ) { return (*i).second.size; } return 0; } /*-------------------------------------------------------------------------*/ CORE::CIOAccess* CVPArchive::LoadFile( const VFS::CString& file , const VFS::UInt32 memLoadSize ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.find( file.Lowercase().ReplaceChar( '/', '\\' ) ); if ( i != m_index.end() ) { const TVPIndexEntry& entry = (*i).second; if ( memLoadSize >= entry.size ) { FILE* fptr = fopen( m_archivePath.C_String(), "rb" ); if ( NULL == fptr ) return NULL; if ( 0 == fseek( fptr, entry.offset, SEEK_CUR ) ) { // prepare a memory buffer for the file CORE::CDynamicBuffer* fileBuffer = new CORE::CDynamicBuffer(); fileBuffer->SetDataSize( entry.size ); if ( 1 == fread( fileBuffer->GetBufferPtr(), entry.size, 1, fptr ) ) { // Successfully read file into memory fclose( fptr ); return new CORE::CDynamicBufferAccess( fileBuffer, true ); } // unable to read entire file delete fileBuffer; } fclose( fptr ); } else { CORE::CSubFileAccess* fileAccess = new CORE::CSubFileAccess(); if ( fileAccess->Load( m_archivePath , entry.offset , entry.size ) ) { return fileAccess; } delete fileAccess; } } return NULL; } /*-------------------------------------------------------------------------*/ VFS::CString CVPArchive::GetFileHash( const VFS::CString& file ) const {GUCEF_TRACE; CORE::CIOAccess* fileAccess = LoadFile( file.Lowercase().ReplaceChar( '/', '\\' ), 102400 ); if ( NULL != fileAccess ) { VFS::UInt8 digest[ 16 ]; if ( 0 != CORE::md5fromfile( fileAccess->CStyleAccess() , digest ) ) { delete fileAccess; char md5_str[ 48 ]; CORE::md5tostring( digest, md5_str ); VFS::CString md5Str; md5Str.Set( md5_str, 48 ); return md5Str; } delete fileAccess; } return VFS::CString(); } /*-------------------------------------------------------------------------*/ CORE::CDateTime CVPArchive::GetFileModificationTime( const VFS::CString& filePath ) const {GUCEF_TRACE; TFileIndexMap::const_iterator i = m_index.find( filePath.Lowercase().ReplaceChar( '/', '\\' ) ); if ( i != m_index.end() ) { return CORE::CDateTime( (time_t) (*i).second.timestamp, true ); } return CORE::CDateTime(); } /*-------------------------------------------------------------------------*/ const VFS::CString& CVPArchive::GetArchiveName( void ) const {GUCEF_TRACE; return m_archiveName; } /*-------------------------------------------------------------------------*/ bool CVPArchive::IsWriteable( void ) const {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::LoadArchive( const VFS::CArchiveSettings& settings ) {GUCEF_TRACE; // We do not support writable VP archives if ( settings.GetWriteableRequested() ) return false; FILE* fptr = fopen( settings.GetActualArchivePath().C_String(), "rb" ); if ( NULL == fptr ) return false; if ( fread( &m_header, VP_HEADER_SIZE, 1, fptr ) == 1 ) { if ( ( memcmp( m_header.sig, "VPVP", 4 ) == 0 ) && ( m_header.version == 2 ) ) { // Move to the index location at the end of the file if ( 0 != fseek( fptr, m_header.indexoffset, SEEK_SET ) ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: unable to archive header" ); fclose( fptr ); return false; } GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Successfully read the archive header" ); // read the index VFS::CString path; TVPFileIndexEntry fileEntry; for ( VFS::UInt32 i=0; i<m_header.idxentries; ++i ) { if ( fread( &fileEntry, VP_INDEX_ENTRY_SIZE, 1, fptr ) != 1 ) { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: unable to read index entry" ); m_header.idxentries = i; break; } if ( fileEntry.offset == 0 || fileEntry.size == 0 ) { // directory entry VFS::CString dirName; dirName.Scan( fileEntry.filename, 32 ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Found directory entry: " + dirName); if ( dirName == ".." ) { path = CORE::StripLastSubDir( path ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Going up to directory: " + path ); } else { CORE::AppendToPath( path, dirName ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Entering directory: " + dirName ); } // Add the entry for the directory to our index TVPIndexEntry entry; entry.offset = 0; entry.size = 0; entry.timestamp = 0; m_index[ path.Lowercase().ReplaceChar( '/', '\\' ) ] = entry; } else { // file entry TVPIndexEntry entry; entry.offset = fileEntry.offset; entry.size = fileEntry.size; entry.timestamp = fileEntry.timestamp; VFS::CString filenameBuffer; filenameBuffer.Scan( fileEntry.filename, 32 ); VFS::CString filename = path; CORE::AppendToPath( filename, filenameBuffer ); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Found file entry: " + filenameBuffer ); m_index[ filename.Lowercase().ReplaceChar( '/', '\\' ) ] = entry; } } fclose( fptr ); m_archiveName = settings.GetArchiveName(); m_archivePath = settings.GetArchivePath(); GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Successfully finished reading the index" ); return true; } else { GUCEF_DEBUG_LOG( CORE::LOGLEVEL_NORMAL, "VFSPLUGIN VP: Error: Archive header not recognized" ); fclose( fptr ); } } return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::LoadArchive( const VFS::CString& archiveName , CVFSHandlePtr vfsResource , const bool writeableRequest ) {GUCEF_TRACE; return false; } /*-------------------------------------------------------------------------*/ bool CVPArchive::UnloadArchive( void ) {GUCEF_TRACE; m_index.clear(); m_archiveName = NULL; m_archivePath = NULL; return true; } /*-------------------------------------------------------------------------*/ const VFS::CString& CVPArchive::GetType( void ) const {GUCEF_TRACE; return VPArchiveTypeName; } /*-------------------------------------------------------------------------*/ void CVPArchive::DestroyObject( VFS::CVFSHandle* objectToBeDestroyed ) {GUCEF_TRACE; delete objectToBeDestroyed; } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace VP */ }; /* namespace VFSPLUGIN */ }; /* namespace GUCEF */ /*-------------------------------------------------------------------------*/
34.717391
128
0.412283
amvb
8cecd67c9170c77a95ca5206dfc6beeb4ff50153
46,408
cpp
C++
Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp
danielholanda/Tactile-Glove
837b5868afe1e567299e78b4c9cf7b5c93f126b5
[ "MIT" ]
14
2016-11-08T19:06:52.000Z
2022-03-15T13:20:50.000Z
Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp
danielholanda/Tactile-Glove
837b5868afe1e567299e78b4c9cf7b5c93f126b5
[ "MIT" ]
null
null
null
Galileo/DMP_for_Intel_Edison/MPU6050_6Axis_MotionApps20_4Edison.cpp
danielholanda/Tactile-Glove
837b5868afe1e567299e78b4c9cf7b5c93f126b5
[ "MIT" ]
null
null
null
/* * MPU6050_Axis_MotionApps20.cpp * * Created on: 2016年1月10日 * Author: qq95538 */ // I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation // Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00) // 6/18/2012 by Jeff Rowberg <[email protected]> // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib // // Changelog: // ... - ongoing debug release /* ============================================ I2Cdev device library code is placed under the MIT license Copyright (c) 2012 Jeff Rowberg 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 <iostream> #include <typeinfo> #include <math.h> #include <sys/time.h> #include "helper_3dmath4Edison.hpp" #include "MPU6050_4Edison.hpp" /* Source is from the InvenSense MotionApps v2 demo code. Original source is * unavailable, unless you happen to be amazing as decompiling binary by * hand (in which case, please contact me, and I'm totally serious). * * Also, I'd like to offer many, many thanks to Noah Zerkin for all of the * DMP reverse-engineering he did to help make this bit of wizardry * possible. */ #define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[] #define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[] #define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[] /* ================================================================================================ * | Default MotionApps v2.0 42-byte FIFO packet structure: | | | | [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] | | 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | | | | [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] | | 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | * ================================================================================================ */ #define prog_uchar uint8_t #define PROGMEM /** * Instance DMP variables */ bool dmpDebug = true; bool dmpReady = false; // set true if DMP init was successful uint8_t dmpIntStatus = false; // holds actual interrupt status byte from MPU uint8_t dmpStatus; // return status after each device operation (0 = success, !0 = error) uint16_t dmpPacketSize; // expected DMP packet size (default is 42 bytes) uint16_t dmpFifoCount; // count of all bytes currently in FIFO uint8_t dmpFifoBuffer[64]; // FIFO storage buffer // orientation/motion vars Quaternion dmpQuat; // [w, x, y, z] quaternion container VectorInt16 dmpAccel; // [x, y, z] accel sensor measurements VectorInt16 dmpAccelReal; // [x, y, z] gravity-free accel sensor measurements VectorInt16 dmpAccelWorld; // [x, y, z] world-frame accel sensor measurements VectorFloat dmpGravity; // [x, y, z] gravity vector float dmpEuler[3]; // [psi, theta, phi] Euler angle container float dmpYawPitchRoll[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector //#define OUTPUT_READABLE_QUATERNION #define OUTPUT_READABLE_EULER #define OUTPUT_READABLE_YAWPITCHROLL //#define OUTPUT_READABLE_REALACCEL #define OUTPUT_READABLE_WORLDACCEL //#define OUTPUT_TEAPOT uint8_t dmpTeapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' }; // this block of memory gets written to the MPU on start-up, and it seems // to be volatile memory, so it has to be done each time (it only takes ~1 // second though) const prog_uchar dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = { // bank 0, 256 bytes 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82, 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC, 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4, 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10, // bank 1, 256 bytes 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8, 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C, 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0, // bank 2, 256 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bank 3, 256 bytes 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F, 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2, 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF, 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C, 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1, 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01, 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80, 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80, 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E, 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9, 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0, 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86, 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1, 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86, // bank 4, 256 bytes 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA, 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C, 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8, 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3, 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84, 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5, 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3, 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1, 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5, 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A, 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8, 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87, // bank 5, 256 bytes 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8, 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68, 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D, 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94, 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56, 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA, 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A, 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60, 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97, 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04, 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78, 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79, 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68, 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68, // bank 6, 256 bytes 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04, 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66, 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31, 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60, 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76, 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56, 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD, 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91, 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE, 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9, 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD, 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E, 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8, 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89, 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79, // bank 7, 138 bytes (remainder) 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA, 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB, 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3, 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3, 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC, 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF }; // DMP FIFO update rate: 0x09 drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz, // 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very // noisy data. DMP output frequency is calculated easily using this equation: // (200Hz / (1 + value)) // It is important to make sure the host processor can keep up with reading and // processing the FIFO output at the desired rate. Handling FIFO overflow // cleanly is also a good idea. thanks to Noah Zerkin for piecing this stuff // together! #ifndef DMP_FIFO_RATE #define DMP_FIFO_RATE 1 #endif const prog_uchar dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = { // BANK OFFSET LENGTH [DATA] 0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration 0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration 0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration 0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration 0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration 0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration 0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration 0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration 0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02 0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10 0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11 0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12 0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20 0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21 0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22 0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors 0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion 0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update 0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone // SPECIAL 0x01 = enable interrupts 0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION 0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt 0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion 0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer 0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro 0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo 0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo 0x02, 0x16, 0x02, 0x00, DMP_FIFO_RATE // D_0_22 inv_set_fifo_rate }; const prog_uchar dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = { 0x01, 0xB2, 0x02, 0xFF, 0xFF, 0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35, 0x01, 0x6A, 0x02, 0x06, 0x00, 0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00, 0x01, 0x62, 0x02, 0x00, 0x00, 0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00 }; long long timeLastCatch = 0; int timeAvg = 0; int timeAvgMax = 30; int timeCountTarget = 10; // Minimal measurement int timeCountCatch = 0; // Number of catching data double timeBalance = 0.9999; /** * Return the current time as milliseconds * @param print * @return */ long long MPU6050::getMilliTime(bool print) { timeval millitime; long long mtime, seconds, useconds; gettimeofday(&millitime, NULL); seconds = millitime.tv_sec; useconds = millitime.tv_usec; mtime = (seconds * 1000) + (useconds / 1000.0) + 0.5; if(print) printf("Seconds: %lld, Micro: %lld, Milli: %lld\n", seconds, useconds, mtime); return mtime; } /** * Check if is time to do a new request * @return */ long long MPU6050::timeCheck() { long long cur = getMilliTime(false); int interval = cur - timeLastCatch; if (interval >= timeAvg) { if(dmpDebug) printf("Interval\n"); return cur; }/* else if (timeCountCatch < timeCountTarget) { printf("Count\n"); return cur; }*/ else if(dmpDebug) printf("Pass %d >= %d and %d < %d - %lld\n", interval, timeAvg, timeCountCatch, timeCountTarget, cur); return 0; } /** * Recalculate average time with new time * @param time */ void MPU6050::timeCount(long long time) { // Balance use a range of tolerance to avoid fifo overflow and request overflow timeAvg = ((time - timeLastCatch + timeAvg) / 2) * timeBalance; if (timeAvg > timeAvgMax) timeAvg = timeAvgMax; timeLastCatch = time; timeCountCatch += 1; } /** * Reset average time measurement for interval of request data from MPU unit */ void MPU6050::timeReset() { timeAvg = 0; timeCountCatch = 0; timeLastCatch = getMilliTime(false); } /** * Start the device through address with offset's informed * @param address * @param xGyroOffset * @param yGyroOffset * @param zGyroOffset * @return boolean */ bool MPU6050::dmpStartDevice(uint8_t address, int xGyroOffset, int yGyroOffset, int zGyroOffset) { setAddress(address); initialize(); setXGyroOffset(xGyroOffset); setYGyroOffset(yGyroOffset); setZGyroOffset(zGyroOffset); if (testConnection()) { if(dmpDebug) printf("Connection OK\n"); // load and configure the DMP if (dmpInitialize() == 0) { if(dmpDebug) printf("DMP initialized\n"); // turn on the DMP, now that it's ready setDMPEnabled(true); dmpStatus = getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it dmpReady = true; // get expected DMP packet size for later comparison dmpPacketSize = dmpGetFIFOPacketSize(); timeReset(); resetFIFO(); return true; } } return false; } /** * Collect and process data from MPU unit, if this data is available * @return boolean */ bool MPU6050::dmpGetData() { long long time = timeCheck(); if(dmpDebug) printf("%lld ", time); if(dmpReady && time > 0) { if(dmpDebug) printf("\n %lld \n", time); // get current FIFO count dmpFifoCount = getFIFOCount(); if (dmpFifoCount == 1024) { // reset so we can continue cleanly resetFIFO(); timeReset(); if(dmpDebug) printf("FIFO overflow!\n"); // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (dmpFifoCount >= 42) { timeCount(time); // read a packet from FIFO getFIFOBytes(dmpFifoBuffer, dmpPacketSize); // display quaternion values in easy matrix form: w x y z dmpGetQuaternion(&dmpQuat, dmpFifoBuffer); if(dmpDebug) printf("quat %7.2f %7.2f %7.2f %7.2f ", dmpQuat.w,dmpQuat.x,dmpQuat.y,dmpQuat.z); #ifdef OUTPUT_READABLE_EULER // display Euler angles in degrees dmpGetEuler(dmpEuler, &dmpQuat); dmpEuler[0] = dmpEuler[0] * 180/M_PI; dmpEuler[1] = dmpEuler[1] * 180/M_PI; dmpEuler[2] = dmpEuler[2] * 180/M_PI; if(dmpDebug) printf("euler %7.2f %7.2f %7.2f ", dmpEuler[0], dmpEuler[1], dmpEuler[2]); #endif #ifdef OUTPUT_READABLE_YAWPITCHROLL // display Euler angles in degrees dmpGetGravity(&dmpGravity, &dmpQuat); dmpGetYawPitchRoll(dmpYawPitchRoll, &dmpQuat, &dmpGravity); dmpYawPitchRoll[0] = dmpYawPitchRoll[0] * 180/M_PI; dmpYawPitchRoll[1] = dmpYawPitchRoll[1] * 180/M_PI; dmpYawPitchRoll[2] = dmpYawPitchRoll[2] * 180/M_PI; if(dmpDebug) printf("ypr %7.2f %7.2f %7.2f ", dmpYawPitchRoll[0], dmpYawPitchRoll[1], dmpYawPitchRoll[2]); #endif #ifdef OUTPUT_READABLE_REALACCEL // display real acceleration, adjusted to remove gravity dmpGetAccel(&dmpAccel, dmpFifoBuffer); dmpGetGravity(&dmpGravity, &dmpQuat); dmpGetLinearAccel(&dmpAccelReal, &dmpAccel, &dmpGravity); if(dmpDebug) printf("areal %6d %6d %6d ", dmpAccelReal.x, dmpAccelReal.y, dmpAccelReal.z); #endif #ifdef OUTPUT_READABLE_WORLDACCEL // display initial world-frame acceleration, adjusted to remove gravity // and rotated based on known orientation from quaternion dmpGetAccel(&dmpAccel, dmpFifoBuffer); dmpGetGravity(&dmpGravity, &dmpQuat); dmpGetLinearAccelInWorld(&dmpAccelWorld, &dmpAccelReal, &dmpQuat); if(dmpDebug) printf("aworld %6d %6d %6d ", dmpAccelWorld.x, dmpAccelWorld.y, dmpAccelWorld.z); #endif #ifdef OUTPUT_TEAPOT // display quaternion values in InvenSense Teapot demo format: dmpTeapotPacket[2] = dmpFifoBuffer[0]; dmpTeapotPacket[3] = dmpFifoBuffer[1]; dmpTeapotPacket[4] = dmpFifoBuffer[4]; dmpTeapotPacket[5] = dmpFifoBuffer[5]; dmpTeapotPacket[6] = dmpFifoBuffer[8]; dmpTeapotPacket[7] = dmpFifoBuffer[9]; dmpTeapotPacket[8] = dmpFifoBuffer[12]; dmpTeapotPacket[9] = dmpFifoBuffer[13]; //Serial.write(dmpTeapotPacket, 14); dmpTeapotPacket[11]++; // packetCount, loops at 0xFF on purpose #endif printf("\n"); return true; } } return false; } /** * Quaternion * @return Quaternion[w, x, y, z] */ Quaternion getDmpQuaternion() { return dmpQuat; } /** * Accel Sensor Measurements * @return VectorInt16[x, y, z] */ VectorInt16 getDmpAccel() { return dmpAccel; } /** * Gravity-free Accel Sensor Measurements * @return VectorInt16[x, y, z] */ VectorInt16 getDmpAccelReal() { return dmpAccelReal; } /** * World-frame Accel Sensor Measurements * @return VectorInt16[x, y, z] */ VectorInt16 getDmpAccelWorld() { return dmpAccelWorld; } /** * Gravity Vector * @return VectorFloat[x, y, z] */ VectorFloat getDmpGravity() { return dmpGravity; } /** * Euler Angle Container * @return Float[psi, theta, phi] */ float* getDmpEuler() { return dmpEuler; } /** * Yaw/Pitch/Roll container and gravity vector * @return Float[yaw, pitch, roll] */ float* getDmpYawPitchRoll() { return dmpYawPitchRoll; } /** * Initialize DMP inside MPU6050 * @return boolean */ uint8_t MPU6050::dmpInitialize() { //Resetting MPU6050... reset(); usleep(30000); // wait after reset //Disabling sleep mode... setSleepEnabled(false); // get MPU hardware revision //Selecting user bank 16... setMemoryBank(0x10, true, true); //Selecting memory byte 6... setMemoryStartAddress(0x06); //Checking hardware revision... uint8_t hwRevision __attribute__((__unused__)) = readMemoryByte(); //Revision @ user[16][6] = //hwRevision, HEX); //Resetting memory bank selection to 0... setMemoryBank(0, false, false); // check OTP bank valid //Reading OTP bank valid flag... uint8_t otpValid __attribute__((__unused__)) = getOTPBankValid(); //OTP bank is //otpValid ? F("valid!") : F("invalid! // get X/Y/Z gyro offsets //Reading gyro offset values... /* int8_t xgOffset = getXGyroOffset(); int8_t ygOffset = getYGyroOffset(); int8_t zgOffset = getZGyroOffset(); sleep(5); for(int cnt = 0; cnt < 1000; cnt = cnt + 1) { std::cout << "X: " << typeid(xgOffset).name() << "Y: " << typeid(ygOffset).name() << "Z: " << typeid(zgOffset).name() << "\n"; sleep(1); //xgOffset = (getXGyroOffset() + xgOffset)/2; //ygOffset = (getYGyroOffset() + ygOffset)/2; //zgOffset = (getZGyroOffset() + zgOffset)/2; } */ //X gyro offset = //xgOffset); //Y gyro offset = //ygOffset); //Z gyro offset = //zgOffset); // setup weird slave stuff (?) //Setting slave 0 address to 0x7F... setSlaveAddress(0, 0x7F); //Disabling I2C Master mode... setI2CMasterModeEnabled(false); //Setting slave 0 address to 0x68 (self)... setSlaveAddress(0, 0x68); /* if (addr == 104) { std::cout << "Address: 104"; setSlaveAddress(0, 0x68); } else { std::cout << "Address: 105"; setSlaveAddress(0, 0x69); } * */ //Resetting I2C Master control... resetI2CMaster(); usleep(20000); // load DMP code into memory banks //Writing DMP code to MPU memory banks ( // bytes) if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) { printf("Success! DMP code written and verified.\n"); // write DMP configuration //Writing DMP configuration to MPU memory banks ( // bytes in config def) if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) { printf("Success! DMP configuration written and verified.\n"); //Setting clock source to Z Gyro... setClockSource(MPU6050_CLOCK_PLL_ZGYRO); //Setting DMP and FIFO_OFLOW interrupts enabled... setIntEnabled(0x12); //Setting sample rate to 200Hz... setRate(4); // 1khz / (1 + 4) = 200 Hz //Setting external frame sync to TEMP_OUT_L[0]... setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L); //Setting DLPF bandwidth to 42Hz... setDLPFMode(MPU6050_DLPF_BW_42); //Setting gyro sensitivity to +/- 2000 deg/sec... setFullScaleGyroRange(MPU6050_GYRO_FS_2000); //Setting DMP configuration bytes (function unknown)... setDMPConfig1(0x03); setDMPConfig2(0x00); //Clearing OTP Bank flag... setOTPBankValid(false); /* //Setting X/Y/Z gyro offsets to previous values... setXGyroOffset(xgOffset); setYGyroOffset(ygOffset); setZGyroOffset(zgOffset); //Setting X/Y/Z gyro user offsets to zero... setXGyroOffsetUser(0); setYGyroOffsetUser(0); setZGyroOffsetUser(0); */ //Writing final memory update 1/7 (function unknown)... uint8_t dmpUpdate[16], j; uint16_t pos = 0; for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Writing final memory update 2/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Resetting FIFO... resetFIFO(); //Reading FIFO count... uint8_t fifoCount = getFIFOCount(); uint8_t fifoBuffer[128]; printf("Current FIFO count=%d\n", fifoCount); //fifoCount); if (fifoCount > 0) getFIFOBytes(fifoBuffer, fifoCount); //Setting motion detection threshold to 2... setMotionDetectionThreshold(2); //Setting zero-motion detection threshold to 156... setZeroMotionDetectionThreshold(156); //Setting motion detection duration to 80... setMotionDetectionDuration(80); //Setting zero-motion detection duration to 0... setZeroMotionDetectionDuration(0); //Resetting FIFO... resetFIFO(); //Enabling FIFO... setFIFOEnabled(true); //Enabling DMP... setDMPEnabled(true); //Resetting DMP... resetDMP(); //Writing final memory update 3/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Writing final memory update 4/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Writing final memory update 5/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); printf("Waiting for FIFO count > 2...\n"); while ((fifoCount = getFIFOCount()) < 3); printf("Current FIFO count=%d",fifoCount); //Reading FIFO data... getFIFOBytes(fifoBuffer, fifoCount); //Reading interrupt status... uint8_t mpuIntStatus __attribute__((__unused__)) = getIntStatus(); //Current interrupt status= mpuIntStatus, HEX //Reading final memory update 6/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //Waiting for FIFO count > 2... while ((fifoCount = getFIFOCount()) < 3); //Current FIFO count= //fifoCount); //Reading FIFO data... getFIFOBytes(fifoBuffer, fifoCount); //Reading interrupt status... mpuIntStatus = getIntStatus(); //Current interrupt status= //mpuIntStatus, HEX //Writing final memory update 7/7 (function unknown)... for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]); writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]); //DMP is good to go! Finally. //Disabling DMP (you turn it on later)... setDMPEnabled(false); //Setting up internal 42-byte (default) DMP packet buffer... dmpPacketSize = 42; /*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) { return 3; // TODO: proper error code for no memory }*/ //Resetting FIFO and clearing INT status one last time... resetFIFO(); getIntStatus(); } else { //ERROR! DMP configuration verification failed. return 2; // configuration block loading failed } } else { //ERROR! DMP code verification failed. return 1; // main binary block loading failed } return 0; // success } bool MPU6050::dmpPacketAvailable() { return getFIFOCount() >= dmpGetFIFOPacketSize(); } // uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate); // uint8_t MPU6050::dmpGetFIFORate(); // uint8_t MPU6050::dmpGetSampleStepSizeMS(); // uint8_t MPU6050::dmpGetSampleFrequency(); // int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg); //uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority); //uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func); //uint8_t MPU6050::dmpRunFIFORateProcesses(); // uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy); // uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy); uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]); data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]); data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]); return 0; } uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = (packet[28] << 8) + packet[29]; data[1] = (packet[32] << 8) + packet[33]; data[2] = (packet[36] << 8) + packet[37]; return 0; } uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; v -> x = (packet[28] << 8) + packet[29]; v -> y = (packet[32] << 8) + packet[33]; v -> z = (packet[36] << 8) + packet[37]; return 0; } uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]); data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]); data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]); data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]); return 0; } uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[0] << 8) + packet[1]); data[1] = ((packet[4] << 8) + packet[5]); data[2] = ((packet[8] << 8) + packet[9]); data[3] = ((packet[12] << 8) + packet[13]); return 0; } uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) int16_t qI[4]; uint8_t status = dmpGetQuaternion(qI, packet); if (status == 0) { q -> w = (float)qI[0] / 16384.0f; q -> x = (float)qI[1] / 16384.0f; q -> y = (float)qI[2] / 16384.0f; q -> z = (float)qI[3] / 16384.0f; return 0; } return status; // int16 return value, indicates error if this line is reached } // uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]); data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]); data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]); return 0; } uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) { // TODO: accommodate different arrangements of sent data (ONLY default supported now) if (packet == 0) packet = dmpPacketBuffer; data[0] = (packet[16] << 8) + packet[17]; data[1] = (packet[20] << 8) + packet[21]; data[2] = (packet[24] << 8) + packet[25]; return 0; } // uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef); // uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) { // get rid of the gravity component (+1g = +4096 in standard DMP FIFO packet) v -> x = vRaw -> x - gravity -> x*4096; v -> y = vRaw -> y - gravity -> y*4096; v -> z = vRaw -> z - gravity -> z*4096; return 0; } // uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) { // rotate measured 3D acceleration vector into original state // frame of reference based on orientation quaternion memcpy(v, vReal, sizeof(VectorInt16)); v -> rotate(q); return 0; } // uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) { v -> x = 2 * (q -> x*q -> z - q -> w*q -> y); v -> y = 2 * (q -> w*q -> x + q -> y*q -> z); v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z; return 0; } // uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet); // uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet); uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) { data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi return 0; } uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) { // yaw: (about Z axis) data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // pitch: (nose up/down, about Y axis) data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z)); // roll: (tilt left/right, about X axis) data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z)); return 0; } // uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet); // uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet); uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) { /*for (uint8_t k = 0; k < dmpPacketSize; k++) { if (dmpData[k] < 0x10) Serial.print("0"); Serial.print(dmpData[k], HEX); Serial.print(" "); } Serial.print("\n");*/ //Serial.println((uint16_t)dmpPacketBuffer); return 0; } uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) { uint8_t status; uint8_t buf[dmpPacketSize]; for (uint8_t i = 0; i < numPackets; i++) { // read packet from FIFO getFIFOBytes(buf, dmpPacketSize); // process packet if ((status = dmpProcessFIFOPacket(buf)) > 0) return status; // increment external process count variable, if supplied if (processed != 0) (*processed)++; } return 0; } // uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void)); // uint8_t MPU6050::dmpInitFIFOParam(); // uint8_t MPU6050::dmpCloseFIFO(); // uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source); // uint8_t MPU6050::dmpDecodeQuantizedAccel(); // uint32_t MPU6050::dmpGetGyroSumOfSquare(); // uint32_t MPU6050::dmpGetAccelSumOfSquare(); // void MPU6050::dmpOverrideQuaternion(long *q); uint16_t MPU6050::dmpGetFIFOPacketSize() { return dmpPacketSize; }
45.453477
134
0.618471
danielholanda
8cf02ef30bf559dd11e9df2d3d58fb0a749eac70
6,428
hpp
C++
State/code/StateMachine.hpp
HONGYU-LEE/DesignPatterns
b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918
[ "MIT" ]
null
null
null
State/code/StateMachine.hpp
HONGYU-LEE/DesignPatterns
b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918
[ "MIT" ]
null
null
null
State/code/StateMachine.hpp
HONGYU-LEE/DesignPatterns
b725a4daa07e13f7eaf8b2cfe9f8da6ffb491918
[ "MIT" ]
null
null
null
#pragma once #include"State.hpp" class MarioStateMachine { public: MarioStateMachine() : _score(0) { //提前缓存各种状态 _normalMario = new NormalMario(this); _superMario = new SuperMario(this); _fireMario = new FireMario(this); _deadMario = new DeadMario(this); _state = _normalMario; } ~MarioStateMachine() { delete _normalMario, _superMario, _fireMario, _deadMario; } void getRevive(); //复活 void getMushroom(); //获得蘑菇 void getSunFlower(); //获得太阳花 void getHurt(); //受到伤害 int getScore() const; //获取当前分数 MarioState* getState() const; //获取当前状态 void setScore(int score); //获取当前分数 void setState(MarioState* state); //获取当前状态 MarioState* getNormalMario(); //获取缓存的状态 MarioState* getSuperMario(); MarioState* getFireMario(); MarioState* getDeadMario(); private: int _score; //当前分数 MarioState* _state; //当前状态 MarioState* _superMario; //缓存所有的状态 MarioState* _normalMario; MarioState* _fireMario; MarioState* _deadMario; private: class NormalMario : public MarioState { public: NormalMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl; } void getMushroom() override { _stateMachine->setScore(_stateMachine->getScore() + 100); _stateMachine->setState(_stateMachine->getSuperMario()); std::cout << "获得蘑菇,由普通马里奥变为超级马里奥,增加一百分" << std::endl; } void getSunFlower() override { _stateMachine->setScore(_stateMachine->getScore() + 200); _stateMachine->setState(_stateMachine->getFireMario()); std::cout << "获得太阳花,由普通马里奥变为火焰马里奥,增加两百分" << std::endl; } void getHurt() override { _stateMachine->setScore(0); _stateMachine->setState(_stateMachine->getDeadMario()); std::cout << "受到伤害,马里奥死亡,分数清空" << std::endl; } std::string getStateName() override { return "普通马里奥"; } private: MarioStateMachine* _stateMachine; //状态机 }; class SuperMario : public MarioState { public: SuperMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl; } void getMushroom() override { _stateMachine->setScore(_stateMachine->getScore() + 100); std::cout << "获得蘑菇,增加一百分" << std::endl; } void getSunFlower() override { _stateMachine->setScore(_stateMachine->getScore() + 200); _stateMachine->setState(_stateMachine->getFireMario()); std::cout << "获得太阳花,由超级马里奥变为火焰马里奥,增加两百分" << std::endl; } void getHurt() override { _stateMachine->setScore(_stateMachine->getScore() - 100); _stateMachine->setState(_stateMachine->getNormalMario()); std::cout << "受到伤害,由超级马里奥变为普通马里奥,扣一百分" << std::endl; } std::string getStateName() override { return "超级马里奥"; } private: MarioStateMachine* _stateMachine; //状态机 }; class FireMario : public MarioState { public: FireMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { std::cout << "当前未死亡,不能复活。不存在该逻辑" << std::endl; } void getMushroom() override { _stateMachine->setScore(_stateMachine->getScore() + 100); std::cout << "获得蘑菇,增加一百分" << std::endl; } void getSunFlower() override { _stateMachine->setScore(_stateMachine->getScore() + 200); std::cout << "获得太阳花,增加两百分" << std::endl; } void getHurt() override { _stateMachine->setScore(_stateMachine->getScore() - 100); _stateMachine->setState(_stateMachine->getSuperMario()); std::cout << "受到伤害,由火焰马里奥变为超级马里奥,扣一百分" << std::endl; } std::string getStateName() override { return "火焰马里奥"; } private: MarioStateMachine* _stateMachine; //状态机 }; class DeadMario : public MarioState { public: DeadMario(MarioStateMachine* stateMachine) : _stateMachine(stateMachine) {} void getRevive() override { _stateMachine->setScore(0); _stateMachine->setState(_stateMachine->getNormalMario()); std::cout << "复活马里奥,会到普通状态,分数重新计算" << std::endl; } void getMushroom() override { std::cout << "死亡后不能获取道具,不存在该逻辑" << std::endl; } void getSunFlower() override { std::cout << "死亡后不能获取道具,不存在该逻辑" << std::endl; } void getHurt() override { std::cout << "死亡后不能受到伤害,不存在该逻辑" << std::endl; } std::string getStateName() override { return "死亡"; } private: MarioStateMachine* _stateMachine; //状态机 }; }; void MarioStateMachine::getRevive() { _state->getRevive(); } void MarioStateMachine::getMushroom() { _state->getMushroom(); } void MarioStateMachine::getSunFlower() { _state->getSunFlower(); } void MarioStateMachine::getHurt() { _state->getHurt(); } int MarioStateMachine::getScore() const { return _score; } MarioState* MarioStateMachine::getState() const { return _state; } void MarioStateMachine::setScore(int score) { _score = score; } void MarioStateMachine::setState(MarioState* state) { _state = state; } MarioState* MarioStateMachine::getNormalMario() { return _normalMario; } MarioState* MarioStateMachine::getSuperMario() { return _superMario; } MarioState* MarioStateMachine::getFireMario() { return _fireMario; } MarioState* MarioStateMachine::getDeadMario() { return _deadMario; }
23.807407
71
0.558027
HONGYU-LEE
8cf1cca6709f496c90b1ffcf3cbaa568ef803876
3,128
cpp
C++
301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
301-400/309-Best_Time_to_Buy_and_Sell_Stock_with_Cooldown-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Say you have an array for which the ith element is the price of a given stock // on day i. // Design an algorithm to find the maximum profit. You may complete as many // transactions as you like (ie, buy one and sell one share of the stock // multiple times) with the following restrictions: // You may not engage in multiple transactions at the same time (ie, you // must sell the stock before you buy again). After you sell your stock, you // cannot buy stock on next day. (ie, cooldown 1 day) // Example: // prices = [1, 2, 3, 0, 2] // maxProfit = 3 // transactions = [buy, sell, cooldown, buy, sell] // correct thinking direction // finite state machine // ref: // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking) // 3 states (indicate net money we have, start at 0): // s0: can stay at s0, or buy and go to s1 // s1: can stay at s1, or sell and go to s2 (cooldown state, cannot buy) // s2: cannot stay at s2, after 1 day cooldown, go to s1 class Solution { public: int maxProfit(vector<int> &prices) { if (prices.size() < 2) return 0; int n = prices.size(); vector<int> s0(n), s1(n), s2(n); s0[0] = 0; s1[0] = -prices[0]; s2[0] = INT_MIN; // impossible to sell at first day for (int i = 1; i < n; ++i) { s0[i] = max(s0[i - 1], s2[i - 1]); s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); s2[i] = s1[i - 1] + prices[i]; } return max(s0[n - 1], s2[n - 1]); } }; // further optimized to O(1) space class Solution { public: int maxProfit(vector<int> &prices) { int s0 = 0, s1 = INT_MIN, s2 = 0; for (auto &&p : prices) { int pre_s2 = s2; s2 = s1 + p; s1 = max(s1, s0 - p); s0 = max(s0, pre_s2); } return max(s0, s2); } }; // my own analysis, seems to be wrong way // analysis // vector input, return a int // conditions // => dp // let dp[n] represents the max profit after the end of day n // not day n price is price[n-1] // if day n-1 must be selling transaction // i.e. dp[n-1] != dp[n-2] // dp[n] = max(dp[n-1], dp[n-1] + price[n-1] - price[n-2]) // if day n-1 can be a non-selling transaction // if day n-1 can be cooldown window // i.e. dp[n-1] == dp[n-2] // dp[n] = dp[n-1] // if day n-1 is not cooldown (n-2 is not selling) // i.e. dp[n-2] == dp[n-3] // dp[n] = dp[n-2] + max(0, price[n-1] - price[n-2]) // beginning cases: // dp[0] = 0, dp[1] = 0, dp[2] = max(0, price[1] - price[0]) // // code: // int n = prices.size(); // vector<int> dp(n + 1); // all 0s // dp[2] = max(0, prices[1] - prices[0]); // for (int i = 3; i <= n; ++i) { // if (dp[i - 1] != dp[i - 2]) // dp[i] = dp[i - 1] + max(0, prices[i - 1] - prices[i - 2]); // else { // // n-1 is cooldown // dp[i] = dp[i - 1]; // if (dp[i - 2] == dp[i - 3]) // dp[i] += max(0, prices[i - 1] - prices[i - 2]); // } // } // return dp[n];
31.59596
141
0.538683
ysmiles
8cf76e3a2f55f04ec658adbbce9fe0ea6b6b9d73
1,412
cpp
C++
resources.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
null
null
null
resources.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
1
2018-01-26T00:06:19.000Z
2018-01-26T00:06:54.000Z
resources.cpp
5cript/minide
0964ae51512eb7ba1ee44d828d27e5b73da32245
[ "MIT" ]
null
null
null
#include "resources.hpp" #include <boost/dll/runtime_symbol_info.hpp> #include <fstream> #include <sstream> namespace MinIDE { //##################################################################################################################### path getResourcesDirectory() { auto program_path = boost::dll::program_location(); program_path = program_path.parent_path(); // for dev: auto fname = program_path.filename().string(); if (fname == "Debug" || fname == "Release") program_path = program_path.parent_path(); auto res = program_path.parent_path() / "resources"; return res; } //--------------------------------------------------------------------------------------------------------------------- path resource(path const& file) { return getResourcesDirectory() / file; } //--------------------------------------------------------------------------------------------------------------------- std::string loadResource(path const& file) { auto res = resource(file); std::ifstream reader{res, std::ios_base::binary}; std::stringstream buffer; buffer << reader.rdbuf(); return buffer.str(); } //##################################################################################################################### }
33.619048
120
0.386686
5cript
8cf8c764d68f0576d49cf9bbb33bd30b7e6a0e51
1,927
cc
C++
fibonacci_sum/fibonacci_sum.cc
ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014
c3351a8e1e62d01dad072c21f57654c102efc114
[ "MIT" ]
null
null
null
fibonacci_sum/fibonacci_sum.cc
ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014
c3351a8e1e62d01dad072c21f57654c102efc114
[ "MIT" ]
null
null
null
fibonacci_sum/fibonacci_sum.cc
ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014
c3351a8e1e62d01dad072c21f57654c102efc114
[ "MIT" ]
2
2020-12-02T13:04:29.000Z
2020-12-07T00:17:01.000Z
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @author F. de Sande * @date 7.nov.2020 * @brief Cada nuevo término de la serie de Fibonacci se genera sumando los dos anteriores. * Comenzando con 0 y 1, los primeros 10 términos serán: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 * Desarrolle en C++ un programa que calcule la suma de todos los términos de valor par * de la serie que sean menores que 1000. * @see https://docs.google.com/document/d/1-3hTIVf8tPrbn9u0vs0Cm2IGyX1XBgv8hReVU0KOSUQ/edit?usp=sharing * @see stoi http://www.cplusplus.com/reference/string/stoi/ * An Object Oriented Version of the program: * @see https://stackoverflow.com/questions/21360694/sum-of-even-fibonacci-numbers-under-1000 * */ #include <iostream> #include <cstdlib> // exit #include "fibonacci_sum.h" // Usage: the program requires a single numeric parameter void Usage(int argc, char *argv[]) { if (argc != 2) { std::cout << argv[0] << ": Falta un número natural como parámetro" << std::endl; std::cout << "Pruebe " << argv[0] << " --help para más información" << std::endl; exit(EXIT_SUCCESS); } std::string parameter{argv[1]}; if (parameter == "--help") { std::cout << kHelpText << std::endl; exit(EXIT_SUCCESS); } } size_t fibonacci_sum(const size_t kLimit) { size_t second_to_last{0}, // Second to last term last{1}, // Last term generated new_term; // New term of the serie size_t long sum{0}; // Accumulated sum of the terms do { new_term = last + second_to_last; if (new_term % 2 == 0) { sum += new_term; } // Uncomment for debug: print each new term // std::cout << "Term: " << new_term << std::endl; second_to_last = last; last = new_term; } while (new_term < kLimit); return sum; }
33.807018
104
0.646082
ULL-ESIT-IB-2020-2021
8cf90e7707c1f12d35fcd1633760e24ff715f571
3,984
cpp
C++
src/GameClient/MapView/ResourcesBar.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T13:44:49.000Z
2021-01-19T10:39:48.000Z
src/GameClient/MapView/ResourcesBar.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
null
null
null
src/GameClient/MapView/ResourcesBar.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T16:03:20.000Z
2020-02-15T09:14:30.000Z
// ResourcesBar.cpp: implementation of the CResourcesBar class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ResourcesBar.h" #include "..\GameClientGlobal.h" #include "..\DataObjects\CMap.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define RESOURCEBAR_ITEM_WIDTH 55 #define RESOURCEBAR_LINE_HEIGHT 18 #define RESOURCEBAR_TEXT_COLOR RGB32(255, 255, 255) ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNAMIC(CResourcesBar, CWindow) BEGIN_OBSERVER_MAP(CResourcesBar, CWindow) case -1: break; END_OBSERVER_MAP(CResourcesBar, CWindow) CResourcesBar::CResourcesBar() { m_pFont = NULL; memset(m_aResources, 0, sizeof(int) * RESOURCE_COUNT); } CResourcesBar::~CResourcesBar() { ASSERT(m_pFont == NULL); } #ifdef _DEBUG void CResourcesBar::AssertValid() const { CWindow::AssertValid(); ASSERT(m_pFont != NULL); } void CResourcesBar::Dump(CDumpContext &dc) const { CWindow::Dump(dc); } #endif void CResourcesBar::Create(CWindow *pParent, CFontObject *pFont) { ASSERT(pParent != NULL); ASSERT(pFont != NULL); m_pFont = pFont; // First determine count of used resources DWORD dwCount = 0, i; for(i = 0; i < RESOURCE_COUNT; i++){ if(!g_pMap->GetResource(i)->GetName().IsEmpty()){ dwCount ++; } } // Compute the positioning CRect rcParent; rcParent = pParent->GetWindowPosition(); int nStartPosition, nRowCount = 1; while((int)((dwCount / nRowCount) * RESOURCEBAR_ITEM_WIDTH) > rcParent.Width()) nRowCount++; nStartPosition = rcParent.Width() - ((dwCount + (nRowCount / 2)) / nRowCount) * RESOURCEBAR_ITEM_WIDTH; int nPos = nStartPosition, nRow = 0; for(i = 0; i < RESOURCE_COUNT; i++){ if(g_pMap->GetResource(i)->GetName().IsEmpty()){ m_aPositions[i].x = -1; } else{ m_aPositions[i].x = nPos - nStartPosition; m_aPositions[i].y = nRow * RESOURCEBAR_LINE_HEIGHT; nPos += RESOURCEBAR_ITEM_WIDTH; if(nPos >= rcParent.Width()){ nPos = nStartPosition; nRow++; } } } // Comptute the position of the window CRect rcWnd; rcWnd.left = nStartPosition; rcWnd.right = rcParent.Width(); rcWnd.top = 0; rcWnd.bottom = nRowCount * RESOURCEBAR_LINE_HEIGHT; m_bTransparent = TRUE; CWindow::Create(&rcWnd, pParent); } void CResourcesBar::Delete() { CWindow::Delete(); m_pFont = NULL; } void CResourcesBar::SetResource(DWORD dwIndex, int nNewValue) { ASSERT(dwIndex < RESOURCE_COUNT); m_aResources[dwIndex] = nNewValue; CRect rc; rc.left = m_aPositions[dwIndex].x; if(rc.left == -1) return; rc.top = m_aPositions[dwIndex].y; rc.right = rc.left + RESOURCEBAR_ITEM_WIDTH; rc.bottom = rc.top + RESOURCEBAR_LINE_HEIGHT; UpdateRect(&rc); } void CResourcesBar::Draw(CDDrawSurface *pSurface, CRect *pRect) { DWORD i; CString str; int nVal; for(i = 0; i < RESOURCE_COUNT; i++){ if(m_aPositions[i].x == -1) continue; pSurface->Paste(m_aPositions[i], g_pMap->GetResource(i)->GetIcon()); nVal = m_aResources[i]; if(abs(nVal) > 99999){ // nVal / 1000 k if(abs(nVal) > 9999999){ // nVal / 1000000 M if(abs(nVal) > 9999999999){ // nVal / 1000000000 G str.Format("%dG", nVal / 1000000000); } else{ str.Format("%dM", nVal / 1000000); } } else{ str.Format("%dk", nVal / 1000); } } else{ str.Format("%d", nVal); } m_pFont->PaintText(m_aPositions[i].x + 17, m_aPositions[i].y + (RESOURCEBAR_LINE_HEIGHT - m_pFont->GetCharSize('A').cy) / 2, str, pSurface, RESOURCEBAR_TEXT_COLOR); } } // Returns the window from givven screen point // works only on subtree of windows CWindow * CResourcesBar::WindowFromPoint(CPoint &pt) { return NULL; }
23.298246
128
0.626255
vitek-karas
8cf9baba50c162a61a817c1d88bfc08028f7fe46
417
cpp
C++
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise_3.7_SUM.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
// // Created by rahul on 21/7/19. // #include <iostream> #include <cmath> #define ACCURACY 0.001 int main() { int n; float sum,n1,m; n=1;sum=0; for(int i=1;;i++) { n1 = float(1) / n; m = pow(n1, i); std::cout<<m<<'\n'; sum +=m; std::cout<<"sum"<<sum<<'\n'; if (m <= ACCURACY) break; n++; } std::cout<<sum<<"\n"; return 0; }
16.68
36
0.434053
jattramesh
8cfcd4b41e0a05d8a7421905aaa8d3713f9c4f17
1,151
hpp
C++
Project/RSA_Input.hpp
elie-wanko/RSA-in-Optical-Networks
a23e4525b865826aca8e2d5b6ce55d7b3fc20528
[ "MIT" ]
null
null
null
Project/RSA_Input.hpp
elie-wanko/RSA-in-Optical-Networks
a23e4525b865826aca8e2d5b6ce55d7b3fc20528
[ "MIT" ]
null
null
null
Project/RSA_Input.hpp
elie-wanko/RSA-in-Optical-Networks
a23e4525b865826aca8e2d5b6ce55d7b3fc20528
[ "MIT" ]
null
null
null
#ifndef RSA_INPUT_HPP #define RSA_INPUT_HPP #include <vector> #include <string> //Forward declaration class Demand; class Vertex; class Edge; class RSA_Input { private: std::string file_Outputplacement_; std::vector<Demand *> requests_; std::vector<Vertex *> nodes_; std::vector<Edge *> edges_; public: //Constructors RSA_Input() {} //Getters const std::vector<Demand *> &getRequests() const { return requests_; } const std::vector<Vertex *> &getNodes() const { return nodes_; } const std::vector<Edge *> &getEdges() const { return edges_; } std::vector<Demand *> &getRequests() { return requests_; } std::vector<Vertex *> &getNodes() { return nodes_; } std::vector<Edge *> &getEdges() { return edges_; } //Functions void data_load_demand(const std::string filename); void data_load_edge(const std::string filename); void data_load_node(const std::string filename); //Shows void showRequests() const; //Destructors ~RSA_Input() {} }; #endif // RSA_INPUT_HPP
22.134615
78
0.612511
elie-wanko
ea09432aabad0fc4950466ce982930d98fb37c09
5,518
cpp
C++
HedgeLib/src/io/hl_stream.cpp
Radfordhound/HedgeLib
e59f875bb7feba37bc5a373a50ae5af8874cd1e2
[ "BSD-2-Clause" ]
56
2017-02-14T13:19:52.000Z
2022-03-26T03:59:07.000Z
HedgeLib/src/io/hl_stream.cpp
Radfordhound/HedgeLib
e59f875bb7feba37bc5a373a50ae5af8874cd1e2
[ "BSD-2-Clause" ]
66
2017-04-22T01:02:04.000Z
2021-08-18T00:41:04.000Z
HedgeLib/src/io/hl_stream.cpp
Radfordhound/HedgeLib
e59f875bb7feba37bc5a373a50ae5af8874cd1e2
[ "BSD-2-Clause" ]
30
2017-02-16T09:07:31.000Z
2022-01-20T23:48:22.000Z
#include "hedgelib/io/hl_stream.h" #include <memory> namespace hl { stream::~stream() {} void stream::read_all(std::size_t size, void* buf) { const std::size_t readByteCount = read(size, buf); if (readByteCount != size) { // TODO: Throw a better error? HL_ERROR(error_type::unknown); } } void stream::write_all(std::size_t size, const void* buf) { const std::size_t writtenByteCount = write(size, buf); if (writtenByteCount != size) { // TODO: Throw a better error? HL_ERROR(error_type::unknown); } } static const u8 in_stream_nulls_static_buffer[1024] = { 0 }; void stream::write_nulls(std::size_t amount) { if (amount > sizeof(in_stream_nulls_static_buffer)) { // Allocate a buffer large enough to hold all of the nulls we want to write. std::unique_ptr<u8[]> nulls(new u8[amount]()); // Write the nulls to the stream. write_arr(amount, nulls.get()); } else { // Write the given amount of nulls to the stream using our static nulls buffer. write_arr(amount, in_stream_nulls_static_buffer); } } void stream::write_off32(std::size_t basePos, std::size_t offVal, bool doSwap, off_table& offTable) { // Compute offset. u32 off = static_cast<u32>(offVal - basePos); // Swap offset if necessary. if (doSwap) endian_swap(off); // Add offset position to offset table. offTable.push_back(tell()); // Write offset to stream. write_obj(off); } void stream::write_off64(std::size_t basePos, std::size_t offVal, bool doSwap, off_table& offTable) { // Compute offset. u64 off = static_cast<u64>(offVal - basePos); // Swap offset if necessary. if (doSwap) endian_swap(off); // Add offset position to offset table. offTable.push_back(tell()); // Write offset to stream. write_obj(off); } void stream::fix_off32(std::size_t basePos, std::size_t offPos, bool doSwap, off_table& offTable) { // Get end of stream position. const std::size_t endPos = tell(); // Jump to the given offset position. jump_to(offPos); // Fix the offset. write_off32(basePos, endPos, doSwap, offTable); // Jump back to end of stream. jump_to(endPos); } void stream::fix_off64(std::size_t basePos, std::size_t offPos, bool doSwap, off_table& offTable) { // Get end of stream position. const std::size_t endPos = tell(); // Jump to the given offset position. jump_to(offPos); // Fix the offset. write_off64(basePos, endPos, doSwap, offTable); // Jump back to end of stream. jump_to(endPos); } bool stream::read_str(std::size_t bufSize, char* buf) { constexpr std::size_t tmpBufSize = 20; char tmpBuf[tmpBufSize]; // Return early if bufSize == 0 if (!bufSize) return true; // Read string into buffer. while (true) { const std::size_t readByteCount = read(tmpBufSize, tmpBuf); const std::size_t safeWriteCount = std::min(readByteCount, bufSize); // Append a null terminator and return failure // if we've reached the end of the stream. if (readByteCount == 0) { *(buf++) = '\0'; return false; } // Otherwise, append all of the bytes we just read into the temporary buffer. for (std::size_t i = 0; i < safeWriteCount; ++i) { *(buf++) = tmpBuf[i]; // Jump to end of string and return success if we read a null terminator. if (tmpBuf[i] == '\0') { jump_behind(static_cast<long>(readByteCount - (i + 1))); return true; } } // Decrease writable buffer size. bufSize -= safeWriteCount; // Raise an error if we've exceeded the buffer size. if (!bufSize) { HL_ERROR(error_type::out_of_range); } } } std::string stream::read_str() { constexpr std::size_t tmpBufSize = 20; std::string str; char tmpBuf[tmpBufSize]; while (true) { const std::size_t readByteCount = read(tmpBufSize, tmpBuf); // Return if we've reached the end of the stream. if (readByteCount == 0) return str; // Otherwise, append all of the bytes we just read into the temporary buffer. for (std::size_t i = 0; i < readByteCount; ++i) { // Jump to end of string and return if we read a null terminator. if (tmpBuf[i] == '\0') { jump_behind(static_cast<long>(readByteCount - (i + 1))); return str; } // Append characters. str += tmpBuf[i]; } } } void stream::align(std::size_t stride) { std::size_t pos; // If stride is < 2, we don't need to align. if (stride-- < 2) return; /* Get the current stream position. */ pos = tell(); // Compute the closest position in the stream that's aligned // by the given stride, and jump to that position. jump_to(((pos + stride) & ~stride)); } void stream::pad(std::size_t stride) { std::size_t pos; // If stride is < 2, we don't need to pad. if (stride-- < 2) return; // Get the current stream position. pos = tell(); // Compute the amount of nulls we need to write to align the // stream with the given stride, and write that many nulls. write_nulls(((pos + stride) & ~stride) - pos); } } // hl
25.546296
87
0.600942
Radfordhound
ea0dfab3accb98ecb414c3727797d1580fc51380
1,529
cpp
C++
source/MaterialXTest/MaterialXFormat/XmlExport.cpp
jerrans/MaterialX
8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6
[ "BSD-3-Clause" ]
101
2017-08-08T12:08:01.000Z
2022-03-17T06:37:58.000Z
source/MaterialXTest/MaterialXFormat/XmlExport.cpp
jerrans/MaterialX
8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6
[ "BSD-3-Clause" ]
1,002
2018-01-09T10:33:07.000Z
2022-03-31T18:35:04.000Z
source/MaterialXTest/MaterialXFormat/XmlExport.cpp
jerrans/MaterialX
8f2b4dd34c3e936d180cc6f0ead52f26efc8a2c6
[ "BSD-3-Clause" ]
24
2018-01-05T20:16:36.000Z
2022-02-03T15:40:14.000Z
// // TM & (c) 2021 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXTest/Catch/catch.hpp> #include <MaterialXFormat/XmlExport.h> namespace mx = MaterialX; TEST_CASE("File Path Predicate", "[xmlexport]") { mx::FileSearchPath searchPath("libraries/stdlib"); mx::DocumentPtr doc = mx::createDocument(); mx::readFromXmlFile(doc, "resources/Materials/TestSuite/stdlib/export/export.mtlx", searchPath); mx::XmlExportOptions exportOptions; exportOptions.flattenFilenames = true; exportOptions.resolvedTexturePath = mx::FileSearchPath(mx::FilePath::getCurrentPath() / "resources" / "Materials" / "TestSuite" / "stdlib" / "export" ); mx::FileSearchPath textureSearchPath("resources"); exportOptions.skipFlattening = [textureSearchPath](const mx::FilePath& filePath) -> bool { return textureSearchPath.find(filePath) != filePath; }; std::stringstream ss; mx::exportToXmlStream(doc, ss, &exportOptions); mx::NodePtr node = doc->getNode("image_color3"); mx::NodePtr node2 = doc->getNode("image_color3_2"); REQUIRE(node); REQUIRE(node2); mx::InputPtr input = node->getInput("file"); mx::InputPtr input2 = node2->getInput("file"); REQUIRE(input->getValueString() == "Images/grid.png"); REQUIRE(mx::FileSearchPath(input2->getValueString()).asString() == exportOptions.resolvedTexturePath.find("black_image.png").asString()); }
36.404762
141
0.69261
jerrans
ea0f1967721cd8d30cf9086331dd8fd119eb2d3d
394
cpp
C++
solved/0-b/arrange-the-numbers/gen.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/0-b/arrange-the-numbers/gen.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/0-b/arrange-the-numbers/gen.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> #include <cstdlib> #include <ctime> #if 0 #define MAXT 1000 #define MAXN 1000 #endif #if 1 #define MAXT 20 #define MAXN 1000 #endif int T; void gen() { int N = rand() % MAXN + 1; int M = rand() % N + 1; int K = rand() % M + 1; printf("%d %d %d\n", N, M, K); --T; } int main() { srand(time(NULL)); T = MAXT; printf("%d\n", T); while (T) gen(); return 0; }
9.85
31
0.550761
abuasifkhan
ea1661eda603cd1b755ed6abeda67e0793b7072c
3,283
hpp
C++
third_party/xsimd/types/xsimd_common_math.hpp
jeanlaroche/pythran
6a2452e8588390bbb20575f580dba11b0037962b
[ "BSD-3-Clause" ]
1
2019-11-09T07:12:56.000Z
2019-11-09T07:12:56.000Z
third_party/xsimd/types/xsimd_common_math.hpp
jeanlaroche/pythran
6a2452e8588390bbb20575f580dba11b0037962b
[ "BSD-3-Clause" ]
1
2015-12-19T10:53:53.000Z
2015-12-19T17:58:20.000Z
third_party/xsimd/types/xsimd_common_math.hpp
jeanlaroche/pythran
6a2452e8588390bbb20575f580dba11b0037962b
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************** * Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and * * Martin Renou * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XSIMD_COMMON_MATH_HPP #define XSIMD_COMMON_MATH_HPP #include <limits> #include <type_traits> namespace xsimd { /********************************************* * Some utility math operations shared * * across scalar versio and fallback * * versions * *********************************************/ namespace detail { template <class T0, class T1> inline T0 ipow(const T0& t0, const T1& t1) { static_assert(std::is_integral<T1>::value, "second argument must be an integer"); T0 a = t0; T1 b = t1; bool const recip = b < 0; T0 r{static_cast<T0>(1)}; while (1) { if (b & 1) { r *= a; } b /= 2; if (b == 0) { break; } a *= a; } return recip ? 1 / r : r; } template<typename T, class = typename std::enable_if<std::is_scalar<T>::value>::type> T sadd(const T& lhs, const T& rhs) { if (std::numeric_limits<T>::is_signed) { if ((lhs > 0) && (rhs > std::numeric_limits<T>::max() - lhs)) { return std::numeric_limits<T>::max(); } else if ((lhs < 0) && (rhs < std::numeric_limits<T>::lowest() - lhs)) { return std::numeric_limits<T>::lowest(); } else { return lhs + rhs; } } else { if (rhs > std::numeric_limits<T>::max() - lhs) { return std::numeric_limits<T>::max(); } else { return lhs + rhs; } } } template<typename T, class = typename std::enable_if<std::is_scalar<T>::value>::type> T ssub(const T& lhs, const T& rhs) { if (std::numeric_limits<T>::is_signed) { return sadd(lhs, (T)-rhs); } else { if (lhs < rhs) { return std::numeric_limits<T>::lowest(); } else { return lhs - rhs; } } } } } #endif
31.266667
93
0.335364
jeanlaroche
ea1a1a4ad651a8413789e171ef860cd2d745c0e6
107
cpp
C++
LiberoEngine/src/Libero/Components/InputComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Components/InputComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
LiberoEngine/src/Libero/Components/InputComponent.cpp
Kair0z/LiberoEngine3D
84c5f75251f19330da9a490587bbf0911bdb681a
[ "MIT" ]
null
null
null
#include "Liber_pch.h" #include "InputComponent.h" void Libero::InputComponent::HandleEvent(IEvent& ) { }
15.285714
50
0.747664
Kair0z
ea1e97576f585169d98fd8f01f696db032199934
10,874
cpp
C++
src/plugins/vtyulc/vlcplayer.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/vtyulc/vlcplayer.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/vtyulc/vlcplayer.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2013 Vladislav Tyulbashev * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include <QVBoxLayout> #include <QPushButton> #include <QTime> #include <QMouseEvent> #include <QWidget> #include <QTime> #include <QTimer> #include <QSizePolicy> #include <QEventLoop> #include <QTimeLine> #include <QDir> #include <QDebug> #include "vlcplayer.h" namespace { QTime convertTime (libvlc_time_t t) { return QTime (t / 1000 / 60 / 60, t / 1000 / 60 % 60, t / 1000 % 60, t % 1000); } void sleep (int ms) { QEventLoop loop; QTimer::singleShot (ms, &loop, SLOT (quit ())); loop.exec (); } const int DVD_IS_MORE_THAN = 10 * 60 * 1000; // in ms const int MAX_TIMEOUT = 1000; // in ms } namespace LeechCraft { namespace vlc { VlcPlayer::VlcPlayer (QWidget *parent) : QObject (parent) , M_ (nullptr) , Parent_ (parent) , DVD_ (false) { VlcInstance_ = std::shared_ptr<libvlc_instance_t> (libvlc_new (0, nullptr), libvlc_release); Mp_ = std::shared_ptr<libvlc_media_player_t> (libvlc_media_player_new (VlcInstance_.get ()), libvlc_media_player_release); libvlc_media_player_set_xwindow (Mp_.get (), parent->winId ()); } VlcPlayer::~VlcPlayer() { libvlc_media_player_stop (Mp_.get ()); } void VlcPlayer::Init (QWidget *parent) { libvlc_media_player_set_xwindow (Mp_.get (), parent->winId ()); Parent_ = parent; } void VlcPlayer::setUrl (const QUrl& url) { Subtitles_.clear (); libvlc_media_player_stop (Mp_.get ()); DVD_ = url.scheme () == "dvd"; M_.reset (libvlc_media_new_location (VlcInstance_.get (), url.toEncoded ()), libvlc_media_release); libvlc_media_player_set_media (Mp_.get (), M_.get ()); libvlc_media_player_play (Mp_.get ()); } void VlcPlayer::addUrl (const QUrl& url) { const QUrl &lastMedia = QUrl::fromEncoded (libvlc_media_get_meta (libvlc_media_player_get_media (Mp_.get ()), libvlc_meta_URL)); Freeze (); M_.reset (libvlc_media_new_location (VlcInstance_.get (), lastMedia.toEncoded ()), libvlc_media_release); libvlc_media_add_option (M_.get (), ":input-slave=" + url.toEncoded ()); libvlc_media_player_set_media (Mp_.get (), M_.get ()); UnFreeze (); } bool VlcPlayer::NowPlaying () const { return libvlc_media_player_is_playing (Mp_.get ()); } double VlcPlayer::GetPosition () const { return libvlc_media_player_get_position (Mp_.get ()); } void VlcPlayer::togglePlay () { bool subtitlesRequired = false; if (libvlc_media_player_get_state (Mp_.get ()) == libvlc_Stopped || libvlc_media_player_get_state (Mp_.get ()) == libvlc_Ended) subtitlesRequired = true; if (NowPlaying ()) libvlc_media_player_pause (Mp_.get ()); else libvlc_media_player_play (Mp_.get ()); if (subtitlesRequired) ReloadSubtitles (); } void VlcPlayer::stop () { libvlc_media_player_stop (Mp_.get ()); } void VlcPlayer::pause () { libvlc_media_player_pause (Mp_.get ()); } void VlcPlayer::changePosition (double pos) { if (libvlc_media_player_get_media (Mp_.get ())) libvlc_media_player_set_position (Mp_.get (), pos); } QTime VlcPlayer::GetFullTime () const { if (libvlc_media_player_get_media (Mp_.get ())) return convertTime (libvlc_media_player_get_length (Mp_.get ())); else return convertTime (0); } QTime VlcPlayer::GetCurrentTime () const { if (libvlc_media_player_get_media (Mp_.get ())) return convertTime (libvlc_media_player_get_time (Mp_.get ())); else return convertTime (0); } void VlcPlayer::SetCurrentTime (libvlc_time_t time) { if (libvlc_media_player_is_playing (Mp_.get ())) libvlc_media_player_set_time (Mp_.get (), time); else { libvlc_media_player_play (Mp_.get ()); WaitForPlaying (); libvlc_media_player_set_time (Mp_.get (), time); libvlc_media_player_pause (Mp_.get ()); } } void VlcPlayer::Freeze () { emit unstable (); FreezePlayingMedia_ = libvlc_media_player_get_media (Mp_.get ()); if (FreezePlayingMedia_) { FreezeCur_ = libvlc_media_player_get_time (Mp_.get ()); FreezeAudio_ = GetCurrentAudioTrack (); FreezeSubtitle_ = GetCurrentSubtitle (); } FreezeIsPlaying_ = libvlc_media_player_is_playing (Mp_.get ()); FreezeDVD_ = DVD_ && libvlc_media_player_get_length (Mp_.get ()) > DVD_IS_MORE_THAN; libvlc_media_player_stop (Mp_.get ()); } void VlcPlayer::switchWidget (QWidget *widget) { Freeze (); libvlc_media_player_set_xwindow (Mp_.get (), widget->winId ()); UnFreeze (); } void VlcPlayer::UnFreeze () { libvlc_media_player_play (Mp_.get ()); WaitForPlaying (); if (FreezeDVD_) { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_activate); WaitForDVDPlaying (); } if (FreezePlayingMedia_ && (!DVD_ || FreezeDVD_)) { libvlc_media_player_set_time (Mp_.get (), FreezeCur_); setAudioTrack (FreezeAudio_); setSubtitle (FreezeSubtitle_); } if (!FreezeIsPlaying_) libvlc_media_player_pause (Mp_.get ()); ReloadSubtitles (); emit stable (); } void VlcPlayer::ReloadSubtitles () { for (int i = 0; i < Subtitles_.size (); i++) libvlc_video_set_subtitle_file (Mp_.get (), Subtitles_ [i].toUtf8 ()); } QWidget* VlcPlayer::GetParent () const { return Parent_; } std::shared_ptr<libvlc_media_player_t> VlcPlayer::GetPlayer () const { return Mp_; } int VlcPlayer::GetAudioTracksNumber () const { return libvlc_audio_get_track_count (Mp_.get ()); } int VlcPlayer::GetCurrentAudioTrack () const { return libvlc_audio_get_track (Mp_.get ()); } void VlcPlayer::setAudioTrack (int track) { libvlc_audio_set_track (Mp_.get (), track); } QString VlcPlayer::GetAudioTrackDescription (int track) const { libvlc_track_description_t *t = GetTrack (libvlc_audio_get_track_description (Mp_.get ()), track); return QString (t->psz_name); } int VlcPlayer::GetAudioTrackId(int track) const { libvlc_track_description_t *t = GetTrack (libvlc_audio_get_track_description (Mp_.get ()), track); return t->i_id; } int VlcPlayer::GetSubtitlesNumber () const { return libvlc_video_get_spu_count (Mp_.get ()); } void VlcPlayer::AddSubtitles (const QString& file) { libvlc_video_set_subtitle_file (Mp_.get (), file.toUtf8 ()); Subtitles_ << file; } int VlcPlayer::GetCurrentSubtitle () const { return libvlc_video_get_spu (Mp_.get ()); } QString VlcPlayer::GetSubtitleDescription (int track) const { libvlc_track_description_t *t = GetTrack (libvlc_video_get_spu_description (Mp_.get ()), track); return QString (t->psz_name); } int VlcPlayer::GetSubtitleId(int track) const { libvlc_track_description_t *t = GetTrack (libvlc_video_get_spu_description (Mp_.get ()), track); return t->i_id; } void VlcPlayer::setSubtitle (int track) { libvlc_video_set_spu (Mp_.get (), track); } libvlc_track_description_t* VlcPlayer::GetTrack(libvlc_track_description_t *t, int track) const { for (int i = 0; i < track; i++) t = t->p_next; return t; } void VlcPlayer::DVDNavigate (unsigned nav) { libvlc_media_player_navigate (Mp_.get (), nav); } void VlcPlayer::dvdNavigateDown () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_down); } void VlcPlayer::dvdNavigateUp () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_up); } void VlcPlayer::dvdNavigateRight () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_right); } void VlcPlayer::dvdNavigateLeft () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_left); } void VlcPlayer::dvdNavigateEnter () { libvlc_media_player_navigate (Mp_.get (), libvlc_navigate_activate); } void VlcPlayer::WaitForPlaying () const { QTimeLine line; line.start (); while (!NowPlaying ()) { sleep (5); if (line.currentTime () > MAX_TIMEOUT) { qWarning () << Q_FUNC_INFO << "timeout"; break; } } } void VlcPlayer::WaitForDVDPlaying () const { QTimeLine line; line.start (); while (libvlc_media_player_get_length (Mp_.get ()) < DVD_IS_MORE_THAN) { sleep (5); if (line.currentTime () > MAX_TIMEOUT) { qWarning () << Q_FUNC_INFO << "timeout"; break; } } WaitForPlaying (); } libvlc_instance_t* VlcPlayer::GetInstance () const { return VlcInstance_.get (); } void VlcPlayer::plus3percent () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) + libvlc_media_player_get_length (Mp_.get ()) * 0.03); } void VlcPlayer::minus3percent () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) - libvlc_media_player_get_length (Mp_.get ()) * 0.03); } void VlcPlayer::plus10seconds () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) + 10 * 1000); } void VlcPlayer::minus10seconds () { libvlc_media_player_set_time (Mp_.get (), libvlc_media_player_get_time (Mp_.get ()) - 10 * 1000); } void VlcPlayer::setAspectRatio (const QByteArray& ratio) { libvlc_video_set_aspect_ratio (Mp_.get (), ratio); } void VlcPlayer::setRealZoom (const QByteArray& zoom) { libvlc_video_set_crop_geometry (Mp_.get (), zoom.constData ()); } QString VlcPlayer::GetAspectRatio () const { return libvlc_video_get_aspect_ratio (Mp_.get ()); } } }
26.014354
140
0.697995
MellonQ
ea221a48a43ed4ee332d6f60ac6fd941bf9321f2
5,515
cpp
C++
server.cpp
Stykk-Gruppen/qTracker-Server
4abf1a6a583c9681481e7fd678aa31a467f8040f
[ "MIT" ]
null
null
null
server.cpp
Stykk-Gruppen/qTracker-Server
4abf1a6a583c9681481e7fd678aa31a467f8040f
[ "MIT" ]
2
2020-06-03T10:03:48.000Z
2020-08-24T13:58:34.000Z
server.cpp
Feqzz/qTracker-Server
4abf1a6a583c9681481e7fd678aa31a467f8040f
[ "MIT" ]
null
null
null
#include "server.h" #include <string> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <iostream> /** * Initializes the openssl library, creates SSL context, configures it * and creates a socket using the portnumber supplied * @param int port * @return Server object */ Server::Server(int port) { initOpenSSL(); ctx = createContext(); configureContect(ctx); sock = createSocket(port); } /** * Creates a Secure TCP socket server and starts listening. * It does not very if the certificate is valid only that is exists. * The function also creates a new thread for each incoming request. */ void Server::start() { /* Handle connections */ while(1) { struct sockaddr_in addr; uint len = sizeof(addr); SSL *ssl; int client = accept(sock, (struct sockaddr*)&addr, &len); if (client < 0) { perror("Unable to accept"); exit(EXIT_FAILURE); } pid=fork(); if(pid==0) { ssl = SSL_new(ctx); SSL_set_fd(ssl, client); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); } else { handleClient(ssl); /*const char reply[] = "1"; char readBuffer[10]; SSL_read(ssl,readBuffer,10); SSL_write(ssl, reply, strlen(reply));*/ signal(SIGCHLD,SIG_IGN); SSL_shutdown(ssl); SSL_free(ssl); exit(0); } } else { close(client); } } close(sock); SSL_CTX_free(ctx); cleanupSSL(); } /** * Read and parses the buffer from the socket connection and creates a Email object. * Depending on the email sending success, a 0 or 1 is returned back to the TCP connection. * @param ssl Secure Socket connection pointer */ void Server::handleClient(SSL* ssl) { //buffer size can be changed to whatever int bufferSize = 255; std::string reply = ""; char readBuffer[bufferSize]; SSL_read(ssl,readBuffer,bufferSize); std::vector<std::string> variables; variables = parseBuffer(readBuffer,bufferSize); Email email(variables); int emailSuccess = email.send(); //emailSuccess = -1 means the system call failed if(emailSuccess >= 0) { reply = "1"; } else { reply = "0"; } SSL_write(ssl,&reply[0],1); /*const char asd[] = "1"; int test = SSL_write(ssl, asd, strlen(asd)); std::cout << test << "\n";*/ } /** * Iterates through the buffer to build strings, if a '\n' char is found a variable is finished * and added to the return vector. * @param buffer * @param length * @return std::vector<std::string> parsed data from buffer */ std::vector<std::string> Server::parseBuffer(char* buffer,int length) { std::vector<std::string> stringVector; std::string tempString = ""; //0 is invite, 1 is forgotten password //int code = (int)buffer[0]-48; for(int i=0;i<length;i++) { char tempChar = buffer[i]; if(tempChar=='\n') { stringVector.push_back(tempString); tempString = ""; } else { tempString += tempChar; } } return stringVector; } /** * Creates a TCP socket with the port number 'port' * @param port * @return int socket */ int Server::createSocket(int port) { int s; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = htonl(INADDR_ANY); s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror("Unable to create socket"); exit(EXIT_FAILURE); } if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) { perror("Unable to bind"); exit(EXIT_FAILURE); } if (listen(s, 1) < 0) { perror("Unable to listen"); exit(EXIT_FAILURE); } return s; } /** * @brief Server::initOpenSSL */ void Server::initOpenSSL() { SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); } /** * @brief Server::cleanupSSL */ void Server::cleanupSSL() { EVP_cleanup(); } /** * @brief Server::createContext * @return SSL_CTX* */ SSL_CTX* Server::createContext() { const SSL_METHOD *method; SSL_CTX *ctx; method = SSLv23_server_method(); ctx = SSL_CTX_new(method); if (!ctx) { perror("Unable to create SSL context"); ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } return ctx; } /** * @brief Server::configureContect * @param SSL_CTX* */ void Server::configureContect(SSL_CTX *ctx) { SSL_CTX_set_ecdh_auto(ctx, 1); /* Set the key and cert */ if (SSL_CTX_use_certificate_file(ctx, "cert.pem", SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } }
22.789256
96
0.553218
Stykk-Gruppen
ea2948783dfe546548f7937329adac5262413e9c
550
cpp
C++
Sail/src/Sail/entities/components/RagdollComponent.cpp
BTH-StoraSpel-DXR/SPLASH
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
12
2019-09-11T15:52:31.000Z
2021-11-14T20:33:35.000Z
Sail/src/Sail/entities/components/RagdollComponent.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
227
2019-09-11T08:40:24.000Z
2020-06-26T14:12:07.000Z
Sail/src/Sail/entities/components/RagdollComponent.cpp
BTH-StoraSpel-DXR/Game
1bf4c9b96cbcce570ed3a97f30a556a992e1ad08
[ "MIT" ]
2
2020-10-26T02:35:18.000Z
2020-10-26T02:36:01.000Z
#include "pch.h" #include "RagdollComponent.h" RagdollComponent::RagdollComponent() { localCenterOfMass = {0.f, 0.f, 0.f}; wireframeModel = nullptr; } RagdollComponent::RagdollComponent(Model* wireframe) { localCenterOfMass = { 0.f, 0.f, 0.f }; wireframeModel = wireframe; } RagdollComponent::~RagdollComponent() { } void RagdollComponent::addContactPoint(glm::vec3 localOffset, glm::vec3 halfSize) { contactPoints.emplace_back(); contactPoints.back().boundingBox.setHalfSize(halfSize); contactPoints.back().localOffSet = localOffset; }
22.916667
83
0.752727
BTH-StoraSpel-DXR
ea2f9e99d5b76a029fb58104b9313e546e674578
576
hpp
C++
hw3/src/object/geometry.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
2
2017-10-11T13:48:30.000Z
2020-06-04T05:30:13.000Z
hw3/src/object/geometry.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
null
null
null
hw3/src/object/geometry.hpp
xupei0610/ComputerGraphics-HW
299416c0d75db17f6490bbab95a3561210a6277e
[ "MIT" ]
2
2018-10-05T15:37:29.000Z
2021-12-20T15:25:48.000Z
#ifndef PX_CG_OBJECT_GEOMETRY_HPP #define PX_CG_OBJECT_GEOMETRY_HPP #include "object/geometry/base_geometry.hpp" #include "object/geometry/box.hpp" #include "object/geometry/cone.hpp" #include "object/geometry/cylinder.hpp" #include "object/geometry/disk.hpp" #include "object/geometry/ellipsoid.hpp" #include "object/geometry/normal_triangle.hpp" #include "object/geometry/plane.hpp" #include "object/geometry/quadric.hpp" #include "object/geometry/ring.hpp" #include "object/geometry/sphere.hpp" #include "object/geometry/triangle.hpp" #endif // PX_CG_OBJECT_GEOMETRY_HPP
32
46
0.809028
xupei0610
ea317fbca3e28c10b4b0e577e351cf6a6bbd06c9
6,197
cpp
C++
src/Framework/Utility.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
src/Framework/Utility.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
src/Framework/Utility.cpp
Belfer/SFMLTemplate
7dcf4aa26239252597d681ca72888463cd4a54b0
[ "MIT" ]
null
null
null
#include "Utility.hpp" #define TINYOBJLOADER_IMPLEMENTATION #include <tiny_obj_loader.h> #include <SFML/Graphics.hpp> #include <iostream> #include <string> #include <fstream> #include <streambuf> #define ASSERT(expr) assert(expr) std::string Utility::LoadTextFile(const std::string& filepath) { std::ifstream t(filepath); return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); } bool LoadObj(const std::string& directory, const std::string& filename, tinyobj::attrib_t& attrib, std::vector<tinyobj::shape_t>& shapes, std::vector<tinyobj::material_t>& materials) { std::string warn; std::string err; std::string& filepath = directory.size() > 0 ? directory + "/" + filename : filename; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filepath.c_str(), directory.c_str()); if (!warn.empty()) std::cout << warn << std::endl; if (!err.empty()) std::cerr << err << std::endl; return ret; } void ParseVertex(VertexPNCT& vertex, const tinyobj::index_t& idx, const tinyobj::attrib_t& attrib) { // access to vertex vertex.position.x = attrib.vertices[(3 * idx.vertex_index) + 0]; vertex.position.y = attrib.vertices[(3 * idx.vertex_index) + 1]; vertex.position.z = attrib.vertices[(3 * idx.vertex_index) + 2]; vertex.normal.x = attrib.normals[(3 * idx.normal_index) + 0]; vertex.normal.y = attrib.normals[(3 * idx.normal_index) + 1]; vertex.normal.z = attrib.normals[(3 * idx.normal_index) + 2]; vertex.texcoord.x = attrib.texcoords[(2 * idx.texcoord_index) + 0]; vertex.texcoord.y = attrib.texcoords[(2 * idx.texcoord_index) + 1]; vertex.color.r = attrib.colors[3 * idx.vertex_index + 0]; vertex.color.g = attrib.colors[3 * idx.vertex_index + 1]; vertex.color.b = attrib.colors[3 * idx.vertex_index + 2]; vertex.color.a = 1.0f; } Model Utility::LoadModel(const std::string& directory, const std::string& filename) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if (!LoadObj(directory, filename, attrib, shapes, materials)) throw; Model model; if (materials.size() > 0) { Material& material = model.material; material.diffuse = glm::vec3(materials[0].diffuse[0], materials[0].diffuse[1], materials[0].diffuse[2]); sf::Image image; if (image.loadFromFile((directory + "/" + materials[0].diffuse_texname).c_str())) { sf::Vector2u imageSize = image.getSize(); material.albedo = Graphics::CreateTexture(TextureFormat::RBGA32, 1, imageSize.x, imageSize.y, image.getPixelsPtr(), true); Graphics::FilterTexture(material.albedo, TextureWrap::REPEAT, TextureWrap::REPEAT, TextureFilter::LINEAR_LINEAR, TextureFilter::LINEAR); } material.attributeFormat = VertexPNCT::format; } std::vector<VertexPNCT> meshData; // Loop over shapes for (size_t s = 0; s < shapes.size(); s++) { // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { int fv = shapes[s].mesh.num_face_vertices[f]; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { VertexPNCT vertex; tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; ParseVertex(vertex, idx, attrib); meshData.emplace_back(vertex); } index_offset += fv; } } Mesh& mesh = model.mesh; mesh.vBuffer = Graphics::CreateBuffer(1, meshData.size() * (sizeof(VertexPNCT) / sizeof(float)), &meshData[0], false, false); mesh.count = meshData.size(); return model; } std::vector<Model> Utility::LoadScene(const std::string& directory, const std::string& filename) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if (!LoadObj(directory, filename, attrib, shapes, materials)) throw; std::vector<Model> models(materials.size()); for (size_t i = 0; i < materials.size(); i++) { Material& material = models[i].material; material.diffuse = glm::vec3(materials[i].diffuse[0], materials[i].diffuse[1], materials[i].diffuse[2]); sf::Image image; if (image.loadFromFile((directory + "/" + materials[i].diffuse_texname).c_str())) { sf::Vector2u imageSize = image.getSize(); material.albedo = Graphics::CreateTexture(TextureFormat::RBGA32, 1, imageSize.x, imageSize.y, image.getPixelsPtr(), true); Graphics::FilterTexture(material.albedo, TextureWrap::REPEAT, TextureWrap::REPEAT, TextureFilter::LINEAR_LINEAR, TextureFilter::LINEAR); } material.attributeFormat = VertexPNCT::format; } std::vector<std::vector<VertexPNCT>> meshData(materials.size()); // Loop over shapes for (size_t s = 0; s < shapes.size(); s++) { // Loop over faces(polygon) size_t index_offset = 0; for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) { // per-face material int matId = shapes[s].mesh.material_ids[f]; std::vector<VertexPNCT>& data = meshData[matId]; int fv = shapes[s].mesh.num_face_vertices[f]; // Loop over vertices in the face. for (size_t v = 0; v < fv; v++) { VertexPNCT vertex; tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v]; ParseVertex(vertex, idx, attrib); data.emplace_back(vertex); } index_offset += fv; } } for (size_t i = 0; i < materials.size(); i++) { std::vector<VertexPNCT>& data = meshData[i]; Mesh& mesh = models[i].mesh; mesh.vBuffer = Graphics::CreateBuffer(1, data.size() * (sizeof(VertexPNCT) / sizeof(float)), &data[0], false, false); mesh.count = data.size(); } return models; }
35.210227
182
0.616589
Belfer
ea31ecc3290c6e3646cb56c0b0742d4a0f278456
83
hpp
C++
Safety/Inc/RSSI.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
15
2017-09-12T14:54:16.000Z
2021-09-21T23:28:57.000Z
Safety/Inc/RSSI.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
67
2017-10-31T02:04:44.000Z
2022-03-28T01:02:25.000Z
Safety/Inc/RSSI.hpp
YashrajN/ZeroPilot-SW
3418f7050443af86bc0e7cc8e58177a95adc40eb
[ "BSD-4-Clause" ]
48
2017-09-28T23:47:17.000Z
2022-01-08T18:30:40.000Z
#ifndef RSSI_HPP #define RSSI_HPP bool CommsFailed(); void RSSI_Check(); #endif
9.222222
19
0.746988
YashrajN
ea32bfeb3470f003807075e55be23f2238848833
2,542
cpp
C++
src/capi/impl/capi_initialization.cpp
meiwanlanjun/turicreate
acd1422e82e4dabd6da7a3f82771dbf2f0474b1b
[ "BSD-3-Clause" ]
null
null
null
src/capi/impl/capi_initialization.cpp
meiwanlanjun/turicreate
acd1422e82e4dabd6da7a3f82771dbf2f0474b1b
[ "BSD-3-Clause" ]
null
null
null
src/capi/impl/capi_initialization.cpp
meiwanlanjun/turicreate
acd1422e82e4dabd6da7a3f82771dbf2f0474b1b
[ "BSD-3-Clause" ]
null
null
null
/* Copyright © 2018 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <unity/server/unity_server_control.hpp> #include <unity/server/unity_server_options.hpp> #include <unity/server/unity_server.hpp> #include <capi/impl/capi_initialization.hpp> #include <capi/impl/capi_initialization_internal.hpp> #include <capi/impl/capi_error_handling.hpp> // All the functions related to the initialization of the server. namespace turi { // Create and return the server options. static unity_server_options& _get_server_options() { static std::unique_ptr<turi::unity_server_options> _server_options; if (_server_options == nullptr) { _server_options.reset(new unity_server_options); _server_options->log_file = "/var/log/"; _server_options->root_path = ""; _server_options->daemon = false; _server_options->log_rotation_interval = 0; _server_options->log_rotation_truncate = 0; } return *_server_options; } /////////////////////////////////////////////////////////////////////////////// // // The server is initialized on demand. bool capi_server_initialized = false; static std::mutex _capi_server_initializer_lock; EXPORT void _tc_initialize() { std::lock_guard<std::mutex> lg(_capi_server_initializer_lock); if (capi_server_initialized) { return; } turi::start_server(_get_server_options(), *capi_server_initializer()); capi_server_initialized = true; // Set up the progress logger to log progress to stdout. global_logger().add_observer(LOG_PROGRESS, [](int, const char* buf, size_t len) { for (; len != 0; --len) { std::cout << *buf; ++buf; } std::cout << std::flush; }); } } // namespace turi // The user facing components of the server initialization extern "C" { EXPORT void tc_setup_log_location(const char* log_file, tc_error** error) { ERROR_HANDLE_START(); std::lock_guard<std::mutex> lg(turi::_capi_server_initializer_lock); if (turi::capi_server_initialized) { set_error(error, "CAPI server is already initialized; call setup functions before all other functions."); return; } turi::_get_server_options().log_file = log_file; ERROR_HANDLE_END(error); } }
29.905882
109
0.651849
meiwanlanjun
ea3bf7111be855d397152194b602065d6a61b0b0
107
hpp
C++
tests/export.hpp
RealKC/Reiji
69a8b50c5e1e997fb90652d5b263c27f75e4e0ea
[ "BSL-1.0" ]
null
null
null
tests/export.hpp
RealKC/Reiji
69a8b50c5e1e997fb90652d5b263c27f75e4e0ea
[ "BSL-1.0" ]
4
2020-08-09T20:33:04.000Z
2021-02-07T04:02:39.000Z
tests/export.hpp
RealKC/Reiji
69a8b50c5e1e997fb90652d5b263c27f75e4e0ea
[ "BSL-1.0" ]
null
null
null
#pragma once #if defined(_WIN32) # define EXPORT __declspec(dllexport) #else # define EXPORT #endif
13.375
40
0.719626
RealKC
ea3edce689c621c537745fbce640c7806ef286c5
457
cc
C++
ast/location.cc
asilha/hilti
ebfffc7dad31059b43a02eb26abcf7a25f742eb8
[ "BSD-3-Clause" ]
46
2015-01-21T13:31:25.000Z
2020-10-27T10:18:03.000Z
ast/location.cc
jjchromik/hilti-104-total
0f9e0cb7114acc157211af24f8254e4b23bd78a5
[ "BSD-3-Clause" ]
29
2015-03-30T08:23:04.000Z
2019-05-03T13:11:35.000Z
ast/location.cc
jjchromik/hilti-104-total
0f9e0cb7114acc157211af24f8254e4b23bd78a5
[ "BSD-3-Clause" ]
20
2015-01-27T12:59:38.000Z
2020-10-28T21:40:47.000Z
#include <util/util.h> #include "location.h" using namespace ast; const Location Location::None("<no location>"); Location::operator string() const { if ( this == &None ) return "<no location>"; string s = _file.size() ? _file : "<no filename>"; s += ":"; if ( _from >= 0 ) { if ( _to >= 0 ) s += util::fmt("%d-%d", _from, _to); else s += util::fmt("%d", _from); } return s; }
16.925926
54
0.49453
asilha
ea3f18a9f2941f8de6e6ad85de09584ffa021e61
3,040
cpp
C++
Engine/Source/GEOGL/Rendering/SubTexture2D.cpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
Engine/Source/GEOGL/Rendering/SubTexture2D.cpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
Engine/Source/GEOGL/Rendering/SubTexture2D.cpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
/******************************************************************************* * Copyright (c) 2020 Matthew Krueger * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgment in the product documentation would * * be appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not * * be misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source * * distribution. * * * *******************************************************************************/ #include "SubTexture2D.hpp" namespace GEOGL{ SubTexture2D::SubTexture2D(const Ref <Texture2D> &textureAtlas, const glm::vec2 &minBound, const glm::vec2 &maxBound) : m_Texture(textureAtlas){ m_TextureCoords[0] = {minBound.x, minBound.y}; m_TextureCoords[1] = {maxBound.x, minBound.y}; m_TextureCoords[2] = {maxBound.x, maxBound.y}; m_TextureCoords[3] = {minBound.x, maxBound.y}; } Ref <SubTexture2D> SubTexture2D::createFromCoords(const Ref<Texture2D>& textureAtlas, const glm::vec2 &spritePosition, const glm::vec2& cellSize, const glm::vec2& spriteDimensions) { glm::vec2 minBounds = { (spritePosition.x * cellSize.x)/(float)textureAtlas->getWidth(), (spritePosition.y * cellSize.y)/(float)textureAtlas->getHeight()}; glm::vec2 maxBounds = { ((spritePosition.x + spriteDimensions.x) * cellSize.x) / (float)textureAtlas->getWidth(), ((spritePosition.y + spriteDimensions.y) * cellSize.y) / (float)textureAtlas->getHeight()}; return createRef<SubTexture2D>(textureAtlas, minBounds, maxBounds); } }
55.272727
186
0.471382
Matthew-Krueger
ea405f6f53b65abdb821e58f9bf4bb40b9deefa4
1,715
cpp
C++
src/Cameras/PerspectiveCamera.cpp
drobnik/raytracing-engine
ae4add6e59e2f80c794e13edc6f6fe65ea5615f6
[ "MIT" ]
1
2018-01-16T18:55:31.000Z
2018-01-16T18:55:31.000Z
src/Cameras/PerspectiveCamera.cpp
drobnik/raytracing-engine
ae4add6e59e2f80c794e13edc6f6fe65ea5615f6
[ "MIT" ]
null
null
null
src/Cameras/PerspectiveCamera.cpp
drobnik/raytracing-engine
ae4add6e59e2f80c794e13edc6f6fe65ea5615f6
[ "MIT" ]
null
null
null
#include "PerspectiveCamera.h" PerspectiveCamera::PerspectiveCamera(const Vector3& e, const Vector3& look, const Vector3& u, unsigned int height, unsigned int width, float pixSize, const std::shared_ptr<AdaptiveSampler>& sampler, float field) : Camera(e, look, u, height, width, pixSize, sampler) { fieldOfView = field; // if distance is default -> calculate from field(ofView) calculateViewDistance(); zoom = 4.0f; } EngineImage PerspectiveCamera::RenderScene(LightIntensity &background, std::unique_ptr<Tracer> const &tracer) { LightIntensity color; std::string name = tracer->sceneName(); EngineImage image = EngineImage(viewHeight, viewWidth, background, name); image.resetPixels(background); float x, y; float d; Ray ray; Vector3 vo; ray.setOrigin(eye); for(unsigned int r = 0; r < viewHeight; r++){ //up for(unsigned int c = 0; c < viewWidth; c++){ //horizontal x = pixelSize * (c - 0.5f *(viewWidth - 1.0f)); y = pixelSize * (r - 0.5f *(viewHeight - 1.0f)); vo = Vector3(x, y, viewDistance) - eye; d = vo.length(); ray.setDirection(Vector3(x, y, d)); color = sampler->AdaptiveSampling(ray, tracer, pixelSize, 0, false); image.setPixel((int)r, (int)c, color); } } return image; } PerspectiveCamera::PerspectiveCamera(const PerspectiveCamera& cam) : Camera(cam), fieldOfView(cam.fieldOfView){ } void PerspectiveCamera::calculateViewDistance(){ viewDistance = 400.0f;//viewWidth / (2.0f * tanf(Utility::degToRad(fieldOfView) * 0.5f)); }
36.489362
111
0.61516
drobnik
3569f3f4b1ed81bd76a4a9f74daff5d730c69b77
748
cpp
C++
December-25/day25_rohithmsr_trappingrainwater.cpp
rohith-bare-on/A-December-of-Algorithms-2020
aadc6fc59c9e2046a2803d42466991b7357e64dc
[ "MIT" ]
1
2020-12-09T06:12:43.000Z
2020-12-09T06:12:43.000Z
December-25/day25_rohithmsr_trappingrainwater.cpp
rohith-bare-on/A-December-of-Algorithms-2020
aadc6fc59c9e2046a2803d42466991b7357e64dc
[ "MIT" ]
null
null
null
December-25/day25_rohithmsr_trappingrainwater.cpp
rohith-bare-on/A-December-of-Algorithms-2020
aadc6fc59c9e2046a2803d42466991b7357e64dc
[ "MIT" ]
null
null
null
/* Runtime: 4 ms, faster than 98.81% of C++ online submissions for Trapping Rain Water. Memory Usage: 14.4 MB, less than 96.32% of C++ online submissions for Trapping Rain Water. */ class Solution { public: int trap(vector<int> &height) { int i = 0; int j = height.size() - 1; int vol = 0; int lmax = 0; int rmax = 0; while (i < j) { lmax = max(lmax, height[i]); rmax = max(rmax, height[j]); if (lmax < rmax) { vol += lmax - height[i]; i++; } else { vol += rmax - height[j]; j--; } } return vol; } };
20.777778
90
0.417112
rohith-bare-on
356e66a8717a03e14994d0f5362993c17eab363d
918
cpp
C++
Homeworks/1_MiniDraw/project/src/App/Curve.cpp
Chaphlagical/USTC_CG
9f8b0321e09e5a05afb1c93303e3c736f78503fa
[ "MIT" ]
13
2020-05-21T03:12:48.000Z
2022-01-20T01:25:02.000Z
Homeworks/1_MiniDraw/project/src/App/Curve.cpp
lyf7115/USTC_CG
9f8b0321e09e5a05afb1c93303e3c736f78503fa
[ "MIT" ]
null
null
null
Homeworks/1_MiniDraw/project/src/App/Curve.cpp
lyf7115/USTC_CG
9f8b0321e09e5a05afb1c93303e3c736f78503fa
[ "MIT" ]
4
2020-06-13T13:14:14.000Z
2021-12-15T07:36:05.000Z
#include "Curve.h" using namespace minidraw; Curve::Curve() { type_ = kCurve; finish = false; polygon.push_back(start); } Curve::~Curve() { } void Curve::update(int mode) { switch (mode) { case 0: finish = true; break; case 1: if (polygon.size() > 0) { polygon.back() = end; points.push_back(end); } polygon.push_back(polygon.back()); break; default: break; } } void Curve::Draw(QPainter& painter) { if (finish) { QPainterPath path(points[0]); for (int i = 0; i < points.size() - 1; i++) { QPoint sp = points[i]; QPoint ep = points[i + 1]; QPoint c1 = QPoint((sp.x() + ep.x()) / 2, sp.y()); QPoint c2 = QPoint((sp.x() + ep.x()) / 2, ep.y()); //QPoint c2 = QPoint(ep.x(), (sp.y() + ep.y()) / 2); path.cubicTo(c1, c2, ep); //path.quadTo(c1, ep); } painter.drawPath(path); } //painter.drawPolygon(polygon); else painter.drawPolyline(polygon); }
15.827586
55
0.58061
Chaphlagical
3576d34fd65a8bcf6ffb78c50761890d9945b668
10,370
cpp
C++
silkopter/rc/src/main.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
36
2015-03-09T16:47:14.000Z
2021-02-04T08:32:04.000Z
silkopter/rc/src/main.cpp
jeanlemotan/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
42
2017-02-11T11:15:51.000Z
2019-12-28T16:00:44.000Z
silkopter/rc/src/main.cpp
jeanleflambeur/silkopter
cdbc67ee2c85f5c95eb4f52e2e0ba24514962dd8
[ "BSD-3-Clause" ]
5
2015-10-15T05:46:48.000Z
2020-05-11T17:40:36.000Z
#include "Comms.h" #include "Video_Decoder.h" //#include "Menu_System.h" //#include "Splash_Menu_Page.h" //#include "Main_Menu_Page.h" #include "utils/Clock.h" #include "IHAL.h" #ifdef RASPBERRY_PI # include "PI_HAL.h" #else # include "GLFW_HAL.h" #endif #include "imgui.h" #include "HUD.h" namespace silk { int s_version_major = 1; int s_version_minor = 0; std::string s_program_path; std::unique_ptr<silk::IHAL> s_hal; } /////////////////////////////////////////////////////////////////////////////////////////////////// //This prints an "Assertion failed" message and aborts. void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function) { QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion); } /////////////////////////////////////////////////////////////////////////////////////////////////// void signal_callback_handler(int signum) { printf("Caught signal %d\n", signum); if (silk::s_hal) { silk::s_hal->shutdown(); } exit(signum); } /////////////////////////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger())); q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC)); // boost::shared_ptr<asio::io_service::work> work(new asio::io_service::work(s_async_io_service)); // std::thread_group worker_threads; // for(int x = 0; x < 4; ++x) // { // worker_threads.create_thread(boost::bind(&asio::io_service::run, &s_async_io_service)); // } signal(SIGHUP, signal_callback_handler); signal(SIGINT, signal_callback_handler); signal(SIGCONT, signal_callback_handler); signal(SIGTERM, signal_callback_handler); silk::s_program_path = argv[0]; size_t off = silk::s_program_path.find_last_of('/'); if (off != std::string::npos) { silk::s_program_path = silk::s_program_path.substr(0, off); } QLOGI("Program path: {}.", silk::s_program_path); #ifdef RASPBERRY_PI silk::s_hal.reset(new silk::PI_HAL()); #else silk::s_hal.reset(new silk::GLFW_HAL()); #endif silk::IHAL& hal = *silk::s_hal; ts::Result<void> result = hal.init(); if (result != ts::success) { QLOGE("Cannot init hal: {}.", result.error().what()); exit(1); } silk::HUD hud(hal); math::vec2u32 display_size = hal.get_display_size(); ImGuiStyle& style = ImGui::GetStyle(); style.ScrollbarSize = display_size.x / 80.f; style.TouchExtraPadding = ImVec2(style.ScrollbarSize * 2.f, style.ScrollbarSize * 2.f); //style.ItemSpacing = ImVec2(size.x / 200, size.x / 200); //style.ItemInnerSpacing = ImVec2(style.ItemSpacing.x / 2, style.ItemSpacing.y / 2); ImGuiIO& io = ImGui::GetIO(); io.FontGlobalScale = 2.f; Video_Decoder decoder; decoder.init(); Clock::time_point last_tp = Clock::now(); hal.get_comms().on_video_data_received = [&decoder](void const* data, size_t size, math::vec2u16 const& res) { decoder.decode_data(data, size, res); }; float temperature = 0.f; Clock::time_point last_comms_history_tp = Clock::now(); std::vector<float> tx_rssi_history; std::vector<float> rx_rssi_history; std::vector<float> packets_dropped_history; std::vector<float> packets_received_history; std::vector<float> packets_sent_history; float brightness = 80.f; float fan_speed = 100.f; hal.set_backlight(brightness / 100.f); hal.set_fan_speed(fan_speed / 100.f); bool single_phy = false; silk::stream::ICamera_Commands::Value camera_commands; while (hal.process()) { decoder.release_buffers(); Clock::time_point now = Clock::now(); Clock::duration dt = now - last_tp; last_tp = now; io.DeltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(dt).count(); ImGui::NewFrame(); ImGui::SetNextWindowPos(ImVec2(0, 0)); ImGui::SetNextWindowSize(ImVec2(display_size.x, display_size.y)); ImGui::SetNextWindowBgAlpha(0); ImGui::Begin("", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs); ImGui::Image((void*)(decoder.get_video_texture_id() | 0x80000000), ImVec2(display_size.x, display_size.y), ImVec2(0, 1), ImVec2(1, 0)); hud.draw(); ImGui::Begin("HAL"); { static int counter = 0; ImGui::Text("Hello, world!"); // Display some text (you can use a format string too) if (ImGui::SliderFloat("Brightness", &brightness, 10.f, 100.f, "%.0f%%")) { hal.set_backlight(brightness / 100.f); } if (ImGui::SliderFloat("Fan", &fan_speed, 10.f, 100.f, "%.0f%%")) { hal.set_fan_speed(fan_speed / 100.f); } temperature = hal.get_temperature(); ImGui::Text("Temperature = %.2f'C", temperature); if (now - last_comms_history_tp >= std::chrono::milliseconds(100)) { last_comms_history_tp = now; silk::Comms::Stats stats = hal.get_comms().get_stats(); tx_rssi_history.push_back(stats.tx_rssi); while (tx_rssi_history.size() > 10 * 5) { tx_rssi_history.erase(tx_rssi_history.begin()); } rx_rssi_history.push_back(stats.rx_rssi); while (rx_rssi_history.size() > 10 * 5) { rx_rssi_history.erase(rx_rssi_history.begin()); } packets_dropped_history.push_back(stats.packets_dropped_per_second); while (packets_dropped_history.size() > 10 * 5) { packets_dropped_history.erase(packets_dropped_history.begin()); } packets_received_history.push_back(stats.packets_received_per_second); while (packets_received_history.size() > 10 * 5) { packets_received_history.erase(packets_received_history.begin()); } packets_sent_history.push_back(stats.packets_sent_per_second); while (packets_sent_history.size() > 10 * 5) { packets_sent_history.erase(packets_sent_history.begin()); } } if (!tx_rssi_history.empty()) { ImGui::Text("TX = %ddBm", (int)tx_rssi_history.back()); ImGui::PlotLines("History", tx_rssi_history.data(), tx_rssi_history.size(), 0, NULL, -128.f, 128.f, ImVec2(0, display_size.y / 20)); } if (!rx_rssi_history.empty()) { ImGui::Text("RX = %ddBm", (int)rx_rssi_history.back()); ImGui::PlotLines("History", rx_rssi_history.data(), rx_rssi_history.size(), 0, NULL, -128.f, 128.f, ImVec2(0, display_size.y / 20)); } if (!packets_dropped_history.empty()) { ImGui::Text("Dropped = %.2f", packets_dropped_history.back()); auto minmax = std::minmax_element(packets_dropped_history.begin(), packets_dropped_history.end()); ImGui::PlotLines("History", packets_dropped_history.data(), packets_dropped_history.size(), 0, NULL, *minmax.first, *minmax.second, ImVec2(0, display_size.y / 20)); } if (!packets_received_history.empty()) { ImGui::Text("Received = %.2f", packets_received_history.back()); auto minmax = std::minmax_element(packets_received_history.begin(), packets_received_history.end()); ImGui::PlotLines("History", packets_received_history.data(), packets_received_history.size(), 0, NULL, *minmax.first, *minmax.second, ImVec2(0, display_size.y / 20)); } if (!packets_sent_history.empty()) { ImGui::Text("Sent = %.2f", packets_sent_history.back()); auto minmax = std::minmax_element(packets_sent_history.begin(), packets_sent_history.end()); ImGui::PlotLines("History", packets_sent_history.data(), packets_sent_history.size(), 0, NULL, *minmax.first, *minmax.second, ImVec2(0, display_size.y / 20)); } bool hq = camera_commands.quality == silk::stream::ICamera_Commands::Quality::HIGH; ImGui::Checkbox("HQ Video", &hq); camera_commands.quality = hq ? silk::stream::ICamera_Commands::Quality::HIGH : silk::stream::ICamera_Commands::Quality::LOW; ImGui::SameLine(); ImGui::Checkbox("Record Video", &camera_commands.recording); hal.get_comms().send_camera_commands_value(camera_commands); ImGui::Checkbox("Single Phy", &single_phy); hal.get_comms().set_single_phy(single_phy); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } ImGui::End(); ImGui::End(); //std::this_thread::sleep_for(std::chrono::microseconds(1)); ImGui::Render(); } hal.shutdown(); return 0; }
39.429658
155
0.542816
jeanleflambeur