hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
37c5a322be381b13ec2a502c4e1a2f5ca962a7a7
775
cpp
C++
src/gtp_lz_stub.cpp
wentaol/zero-problem
887e61826225137b5c7e40feea8ae932bdcf333b
[ "CC0-1.0" ]
5
2018-12-12T01:53:27.000Z
2022-03-17T00:58:12.000Z
src/gtp_lz_stub.cpp
wentaol/zero-problem
887e61826225137b5c7e40feea8ae932bdcf333b
[ "CC0-1.0" ]
null
null
null
src/gtp_lz_stub.cpp
wentaol/zero-problem
887e61826225137b5c7e40feea8ae932bdcf333b
[ "CC0-1.0" ]
1
2020-01-11T00:12:25.000Z
2020-01-11T00:12:25.000Z
#include "gtp_lz_stub.h" #include "log_file.h" GtpLzStub::GtpLzStub(const std::string& e) : ess(e) { } std::string GtpLzStub::getLine() { std::string line; if (ess && std::getline(ess, line)) { Log(line); return line; } return std::string(); } std::string GtpLzStub::getLine(const std::string& s) { std::string line; while (ess) { line = getLine(); if (s.empty()) { return line; } if (line.substr(0U, s.length()) == s) { return line; } } return std::string(); } std::string GtpLzStub::getResult() { Log("=\n"); return std::string("=\n"); } void GtpLzStub::send(const std::string& gtpCommand) { oss << gtpCommand << std::endl; } std::string GtpLzStub::str() const { return oss.str(); }
15.816327
53
0.576774
wentaol
37c9801635037205743d7450780d028b62468482
6,813
cpp
C++
3dbody/util/ConfigMap.cpp
GuangfuWang/threedbody
31c544c25e524cecf107a505c3b4438fc04cd766
[ "BSD-2-Clause" ]
null
null
null
3dbody/util/ConfigMap.cpp
GuangfuWang/threedbody
31c544c25e524cecf107a505c3b4438fc04cd766
[ "BSD-2-Clause" ]
null
null
null
3dbody/util/ConfigMap.cpp
GuangfuWang/threedbody
31c544c25e524cecf107a505c3b4438fc04cd766
[ "BSD-2-Clause" ]
null
null
null
#include "util/ConfigMap.h" #include "util/StringHelper.h" #include "util/Log.h" #include <fstream> namespace gf { BasicInfoMap *BasicInfoMap::instance = nullptr; ConfigMap *ConfigMap::instance = nullptr; BasicInfoMap::BasicInfoMap() { init(); } Ref_Unique<BasicInfoMap> BasicInfoMap::getInstance() { if (instance == nullptr) { instance = new BasicInfoMap(); } Ref_Unique<BasicInfoMap> ret(instance); return ret; } void BasicInfoMap::init() { std::ifstream ifs("./../config/config.ini"); if (ifs.is_open()) { if (ifs.bad()) { GF_CORE_ERROR("Error: cannot open config.ini file..."); GF_CORE_ERROR("Default basic info will be used"); softwareName = "3D Body"; softwareVersion = "2.1.0"; authors = "Guangfu Wang"; authorsEmail = "thuwgf@mail.com"; contributors = ""; facilities = "Bigdata-Department, Chine Mining Group"; introductionInfo = ""; officialSites = "https://www.place_holder.com"; wikiSites = "https://www.place_holder.com"; dateOfCreation = "2021-11-20"; versionMajor = 2; versionMinor = 1; versionPatch = 0; LTSVersion = true; openSource = true; return; } string temp; while (std::getline(ifs, temp)) { if (temp.size() < 1)continue; int hashIdx = temp.find_first_of('#'); temp = temp.substr(0, hashIdx); temp = trim(temp); if (temp.size() < 1)continue; if (temp[0] == '$') { int idx = temp.find(""); } } ifs.close(); } } ConfigMap::ConfigMap() : filterInputFormat(nullptr), filterOutputFormat(nullptr) { if (input_format_.empty()) { input_format_.reserve(55); input_format_.emplace_back(".fbx"); input_format_.emplace_back(".obj"); input_format_.emplace_back(".ply"); input_format_.emplace_back(".stl"); input_format_.emplace_back(".blend"); input_format_.emplace_back(".3d"); input_format_.emplace_back(".3ds"); input_format_.emplace_back(".3mf"); input_format_.emplace_back(".ac"); input_format_.emplace_back(".ac3d"); input_format_.emplace_back(".acc"); input_format_.emplace_back(".amj"); input_format_.emplace_back(".ase"); input_format_.emplace_back(".ask"); input_format_.emplace_back(".b3d"); input_format_.emplace_back(".bvh"); input_format_.emplace_back(".cms"); input_format_.emplace_back(".cob"); input_format_.emplace_back(".dae"); input_format_.emplace_back(".dxf"); input_format_.emplace_back(".enff"); input_format_.emplace_back(".hmb"); input_format_.emplace_back(".irr"); input_format_.emplace_back(".lwo"); input_format_.emplace_back(".lws"); input_format_.emplace_back(".lxo"); input_format_.emplace_back(".m3d"); input_format_.emplace_back(".md2"); input_format_.emplace_back(".md3"); input_format_.emplace_back(".md5"); input_format_.emplace_back(".mdc"); input_format_.emplace_back(".mdl"); input_format_.emplace_back(".VanillaMesh"); input_format_.emplace_back(".mot"); input_format_.emplace_back(".ms3d"); input_format_.emplace_back(".ndo"); input_format_.emplace_back(".nff"); input_format_.emplace_back(".off"); input_format_.emplace_back(".ogex"); input_format_.emplace_back(".pmx"); input_format_.emplace_back(".prj"); input_format_.emplace_back(".q3o"); input_format_.emplace_back(".q3s"); input_format_.emplace_back(".raw"); input_format_.emplace_back(".scn"); input_format_.emplace_back(".sib"); input_format_.emplace_back(".smd"); input_format_.emplace_back(".stp"); input_format_.emplace_back(".ter"); input_format_.emplace_back(".uc"); input_format_.emplace_back(".vta"); input_format_.emplace_back(".x"); input_format_.emplace_back(".x3d"); input_format_.emplace_back(".xgl"); input_format_.emplace_back(".zgl"); GF_CORE_INFO(input_format_[0]); } if (output_format_.empty()) { output_format_.reserve(9); output_format_.emplace_back(".dae"); output_format_.emplace_back(".stl"); output_format_.emplace_back(".obj"); output_format_.emplace_back(".ply"); output_format_.emplace_back(".x"); output_format_.emplace_back(".3ds"); output_format_.emplace_back(".json"); output_format_.emplace_back(".assbin"); output_format_.emplace_back(".step"); } if (filterInputFormat == nullptr) { unsigned int num = input_format_.size(); filterInputFormat = new nfdfilteritem_t[num]; int idx = 0; for (auto &each: input_format_) { filterInputFormat[idx++] = cvtFilter(each); } } if (filterOutputFormat == nullptr) { unsigned int num = output_format_.size(); filterOutputFormat = new nfdfilteritem_t[num]; int idx = 0; for (auto &each: output_format_) { filterOutputFormat[idx++] = cvtFilter(each); } } fs::path curr = getRootDir(); root_dir_ = curr.string(); curr /= "resources"; resource_dir_ = curr.string(); curr = curr.parent_path(); curr /= "scripts"; script_dir_ = curr.string(); curr = curr.parent_path(); curr /= "tests"; test_dir_ = curr.string(); curr = curr.parent_path(); curr /= "3dbody"; source_code_dir_ = curr.string(); } ConfigMap *ConfigMap::getInstance() { if (instance == nullptr) { instance = new ConfigMap(); } return instance; } void ConfigMap::loadFormat(std::ifstream &ifs) { } ConfigMap::~ConfigMap() { } }
35.857895
76
0.530016
GuangfuWang
37cb62a0450c24ec6ba7f0f2275726b800a2a5a7
3,699
hpp
C++
Sisyphe/interpreter/plugins/libpdbPlg/interpreter/src/IDiaSourceFilePtrInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/interpreter/plugins/libpdbPlg/interpreter/src/IDiaSourceFilePtrInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
Sisyphe/interpreter/plugins/libpdbPlg/interpreter/src/IDiaSourceFilePtrInterpreter.hpp
tedi21/SisypheReview
f7c05bad1ccc036f45870535149d9685e1120c2c
[ "Unlicense" ]
null
null
null
/* * IDiaSourceFilePtrInterpreter.hpp * * * @date 12-07-2020 * @author Teddy DIDE * @version 1.00 * Pdb Interpreter generated by gensources. */ #ifndef _IDIASOURCEFILEPTR_INTERPRETER_H_ #define _IDIASOURCEFILEPTR_INTERPRETER_H_ #include "config.hpp" #include "Macros.hpp" #include "Base.hpp" #include "Array.hpp" #include "DiaPtr.h" typedef CDiaPtr<IDiaSourceFile> IDiaSourceFilePtr; #define A(str) encode<EncodingT,ansi>(str) #define C(str) encode<ansi,EncodingT>(str) using namespace boost; NAMESPACE_BEGIN(interp) // Représente un fichier source. template <class EncodingT> class IDiaSourceFilePtrInterpreter : public Base<EncodingT> { private: IDiaSourceFilePtr m_object; void initValue(const IDiaSourceFilePtr& object); IDiaSourceFilePtr& refValue(); const IDiaSourceFilePtr& refValue() const; void tidyValue(); public: IDiaSourceFilePtrInterpreter(); IDiaSourceFilePtrInterpreter(const IDiaSourceFilePtr& object); const IDiaSourceFilePtr& value() const; void value(IDiaSourceFilePtr const& object); virtual typename EncodingT::string_t toString() const; virtual boost::shared_ptr< Base<EncodingT> > clone() const; virtual typename EncodingT::string_t getClassName() const; virtual boost::shared_ptr< Base<EncodingT> > invoke(const typename EncodingT::string_t& method, std::vector< boost::shared_ptr< Base<EncodingT> > >& params); // Récupère les octets de checksum. FACTORY_PROTOTYPE3(get_checksum, InOut< boost::shared_ptr< Base<EncodingT> > >, InOut< boost::shared_ptr< Base<EncodingT> > >, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > get_checksum(boost::shared_ptr< Base<EncodingT> >& cbData, boost::shared_ptr< Base<EncodingT> >& pcbData, boost::shared_ptr< Base<EncodingT> >& data); // Extrait le nom du fichier source. FACTORY_PROTOTYPE1(get_fileName, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > get_fileName(boost::shared_ptr< Base<EncodingT> >& pRetVal); // Récupère un énumérateur des compilands qui ont des numéros de ligne référençant ce fichier. FACTORY_PROTOTYPE1(get_compilands, InOut< boost::shared_ptr< Base<EncodingT> > >) boost::shared_ptr< Base<EncodingT> > get_compilands(boost::shared_ptr< Base<EncodingT> >& ppRetVal); FACTORY_BEGIN_REGISTER CLASS_KEY_REGISTER ( IDiaSourceFilePtrInterpreter, UCS("IDiaSourceFilePtr") ); METHOD_KEY_REGISTER3( IDiaSourceFilePtrInterpreter, boost::shared_ptr< Base<EncodingT> >, get_checksum, no_const_t, UCS("IDiaSourceFilePtr::Get_checksum") ); METHOD_KEY_REGISTER1( IDiaSourceFilePtrInterpreter, boost::shared_ptr< Base<EncodingT> >, get_fileName, no_const_t, UCS("IDiaSourceFilePtr::Get_fileName") ); METHOD_KEY_REGISTER1( IDiaSourceFilePtrInterpreter, boost::shared_ptr< Base<EncodingT> >, get_compilands, no_const_t, UCS("IDiaSourceFilePtr::Get_compilands") ); FACTORY_END_REGISTER FACTORY_BEGIN_UNREGISTER CLASS_KEY_UNREGISTER ( UCS("IDiaSourceFilePtr") ); METHOD_KEY_UNREGISTER3( UCS("IDiaSourceFilePtr::Get_checksum") ); METHOD_KEY_UNREGISTER1( UCS("IDiaSourceFilePtr::Get_fileName") ); METHOD_KEY_UNREGISTER1( UCS("IDiaSourceFilePtr::Get_compilands") ); FACTORY_END_UNREGISTER }; template <class EncodingT> bool check_IDiaSourceFilePtr(boost::shared_ptr< Base<EncodingT> > const& val, IDiaSourceFilePtr& a); template <class EncodingT> bool reset_IDiaSourceFilePtr(boost::shared_ptr< Base<EncodingT> >& val, IDiaSourceFilePtr const& a); NAMESPACE_END #undef A #undef C #include "IDiaSourceFilePtrInterpreter_impl.hpp" #endif
36.99
190
0.751825
tedi21
56d2efb9bdf40aae8eab3718799d648f20dd27dd
1,215
cpp
C++
Scheduling/FCFS/DiffArrivalTime/fcfs.cpp
Gurubalan-GIT/OS-Algorithms
0a5906b8e36343fe54e50094cf256dfea51422fd
[ "BSD-3-Clause" ]
null
null
null
Scheduling/FCFS/DiffArrivalTime/fcfs.cpp
Gurubalan-GIT/OS-Algorithms
0a5906b8e36343fe54e50094cf256dfea51422fd
[ "BSD-3-Clause" ]
null
null
null
Scheduling/FCFS/DiffArrivalTime/fcfs.cpp
Gurubalan-GIT/OS-Algorithms
0a5906b8e36343fe54e50094cf256dfea51422fd
[ "BSD-3-Clause" ]
null
null
null
/* * Created Date: Tuesday April 9th 2019 * Author: Gurubalan Harikrishnan * Email-ID: gurubalan.work@gmail.com * ----- * Copyright (c) 2019 Gurubalan Harikrishnan */ #include<iostream> using namespace std; int main(){ int n,twt,ttat,temp1,temp2=0; int bt[100],at[100],wt[100],tat[100],st[100]; cout<<"Enter number of processes -\n"; cin>>n; cout<<"Enter burst times -\n"; for(int i=0;i<n;i++){ cin>>bt[i]; } cout<<"Enter arrival time -\n"; for(int i=0;i<n;i++){ cin>>at[i]; } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(at[i]>at[j]){ temp1=at[i]; at[i]=at[j]; at[j]=temp1; temp2=bt[i]; bt[i]=bt[j]; bt[j]=temp2; } } } st[0]=0; wt[0]=0; for(int i=1;i<n;i++){ st[i]=st[i-1]+bt[i-1]; wt[i]=st[i]-at[i]; } for(int i=0;i<n;i++){ tat[i]=wt[i]+bt[i]; } cout<<"Burst time\t\t"<<"Arrival time\t\t"<<"Waiting time\t\t"<<"Turn Around time\n"; for(int i=0;i<n;i++){ cout<<bt[i]<<"\t\t\t\t"<<at[i]<<"\t\t\t"<<wt[i]<<"\t\t\t"<<tat[i]<<endl; } }
22.924528
89
0.451852
Gurubalan-GIT
56dad6d7b7c06f5cd24f25ba619ccbb13e08632f
629
cpp
C++
04_template_meta_programming/18_type_list_00_head_tail.cpp
cpptt-book/2nd
d710af6df9ed2561bc7432be7b0b0b93dafecb0a
[ "CC0-1.0" ]
17
2015-01-07T08:10:09.000Z
2021-06-21T13:07:25.000Z
04_template_meta_programming/18_type_list_00_head_tail.cpp
cpptt-book/2nd
d710af6df9ed2561bc7432be7b0b0b93dafecb0a
[ "CC0-1.0" ]
null
null
null
04_template_meta_programming/18_type_list_00_head_tail.cpp
cpptt-book/2nd
d710af6df9ed2561bc7432be7b0b0b93dafecb0a
[ "CC0-1.0" ]
5
2015-05-02T19:07:43.000Z
2021-11-14T21:21:32.000Z
// Copyright (c) 2014 // Akira Takahashi, Fumiki Fukuda. // Released under the CC0 1.0 Universal license. #include <tuple> #include <type_traits> template <class Head, class... Tail> struct g { typedef Head head; typedef std::tuple<Tail...> tail; }; template <class... List> struct f { typedef typename g<List...>::head head; typedef typename g<List...>::tail tail; }; typedef f<int, char, double> list; static_assert(std::is_same< list::head, int >::value, "head must be int"); static_assert(std::is_same< list::tail, std::tuple<char, double> >::value, "tail must be tuple<char, double>"); int main() {}
18.5
48
0.669316
cpptt-book
56e4377256c65cc3aa5aacec8896da81819d5f70
6,789
cpp
C++
library/L2_HAL/sensors/battery/test/ltc4150_test.cpp
diarkia124/SJSU-Dev2
3385f034690d281c2720e17b0a6bdbe51a65113c
[ "Apache-2.0" ]
1
2019-11-25T20:31:07.000Z
2019-11-25T20:31:07.000Z
library/L2_HAL/sensors/battery/test/ltc4150_test.cpp
diarkia124/SJSU-Dev2
3385f034690d281c2720e17b0a6bdbe51a65113c
[ "Apache-2.0" ]
null
null
null
library/L2_HAL/sensors/battery/test/ltc4150_test.cpp
diarkia124/SJSU-Dev2
3385f034690d281c2720e17b0a6bdbe51a65113c
[ "Apache-2.0" ]
null
null
null
#include "L2_HAL/sensors/battery/ltc4150.hpp" #include "L2_HAL/sensors/battery/coulomb_counter.hpp" #include "L4_Testing/testing_frameworks.hpp" #include "L1_Peripheral/interrupt.hpp" #include "L1_Peripheral/gpio.hpp" #include "utility/units.hpp" #include "utility/log.hpp" namespace sjsu { auto GetLambda(InterruptCallback & isr) { return [&isr](InterruptCallback callback, Gpio::Edge) { isr = callback; }; } TEST_CASE("Test LTC4150 Coulomb Counter/ Battery Gas Gauge", "[ltc4150]") { constexpr float kResolution = 0.001f; units::impedance::ohm_t resistance = 0.00050_Ohm; Mock<Gpio> mock_primary_pol_pin; Mock<Gpio> mock_backup_pol_pin; Mock<HardwareCounter> mock_primary_hardware_counter; Mock<HardwareCounter> mock_backup_hardware_counter; InterruptCallback primary_input_isr; InterruptCallback primary_pol_isr; InterruptCallback backup_input_isr; InterruptCallback backup_pol_isr; When(Method(mock_primary_pol_pin, AttachInterrupt)) .AlwaysDo(GetLambda(primary_pol_isr)); When(Method(mock_backup_pol_pin, AttachInterrupt)) .AlwaysDo(GetLambda(backup_pol_isr)); Fake(Method(mock_primary_hardware_counter, Initialize)); Fake(Method(mock_backup_hardware_counter, Initialize)); Fake(Method(mock_primary_hardware_counter, Enable)); Fake(Method(mock_backup_hardware_counter, Enable)); Fake(Method(mock_primary_hardware_counter, GetCount)); Fake(Method(mock_backup_hardware_counter, GetCount)); Fake(Method(mock_primary_hardware_counter, SetDirection)); Fake(Method(mock_backup_hardware_counter, SetDirection)); Fake(Method(mock_primary_pol_pin, SetDirection)); Fake(Method(mock_backup_pol_pin, SetDirection)); Fake(Method(mock_primary_pol_pin, DetachInterrupt)); Fake(Method(mock_backup_pol_pin, DetachInterrupt)); SECTION("LTC4150 Initialization") { Ltc4150 primary_counter = Ltc4150(mock_primary_hardware_counter.get(), mock_primary_pol_pin.get(), resistance); Ltc4150 backup_counter = Ltc4150(mock_backup_hardware_counter.get(), mock_backup_pol_pin.get(), resistance); When(Method(mock_primary_pol_pin, Read)).Return(true); When(Method(mock_backup_pol_pin, Read)).Return(false); primary_counter.Initialize(); backup_counter.Initialize(); Verify(Method(mock_primary_hardware_counter, Initialize)).Exactly(1); Verify(Method(mock_backup_hardware_counter, Initialize)).Exactly(1); Verify(Method(mock_primary_pol_pin, SetDirection) .Using(Gpio::Direction::kInput)); Verify(Method(mock_backup_pol_pin, SetDirection) .Using(Gpio::Direction::kInput)); Verify(Method(mock_primary_pol_pin, AttachInterrupt)).Exactly(1); Verify(Method(mock_backup_pol_pin, AttachInterrupt)).Exactly(1); Verify(Method(mock_primary_hardware_counter, Enable)).Exactly(1); Verify(Method(mock_backup_hardware_counter, Enable)).Exactly(1); } SECTION("Count Ticks and Calculate mAh") { constexpr float kPrimaryCharge = -0.068271f; constexpr float kBackupCharge = 0.102407f; Ltc4150 primary_counter = Ltc4150(mock_primary_hardware_counter.get(), mock_primary_pol_pin.get(), resistance); Ltc4150 backup_counter = Ltc4150(mock_backup_hardware_counter.get(), mock_backup_pol_pin.get(), resistance); When(Method(mock_primary_pol_pin, Read)).Return(false); When(Method(mock_backup_pol_pin, Read)).Return(true); When(Method(mock_primary_hardware_counter, GetCount)).Return(-4); When(Method(mock_backup_hardware_counter, GetCount)).Return(6); primary_counter.Initialize(); CHECK(primary_counter.GetCharge().to<float>() == Approx(kPrimaryCharge)); backup_counter.Initialize(); CHECK(backup_counter.GetCharge().to<float>() == Approx(kBackupCharge)); } SECTION("Direction of Counter changes with the Polarity Pin's State Change") { Ltc4150 primary_counter = Ltc4150(mock_primary_hardware_counter.get(), mock_primary_pol_pin.get(), resistance); Ltc4150 backup_counter = Ltc4150(mock_backup_hardware_counter.get(), mock_backup_pol_pin.get(), resistance); When(Method(mock_primary_pol_pin, Read)).Return(true, false); When(Method(mock_backup_pol_pin, Read)).Return(false, true); primary_counter.Initialize(); Verify(Method(mock_primary_hardware_counter, SetDirection) .Using(HardwareCounter::Direction::kUp)); primary_pol_isr(); Verify(Method(mock_primary_hardware_counter, SetDirection) .Using(HardwareCounter::Direction::kDown)); backup_counter.Initialize(); Verify(Method(mock_backup_hardware_counter, SetDirection) .Using(HardwareCounter::Direction::kDown)); backup_pol_isr(); Verify(Method(mock_backup_hardware_counter, SetDirection) .Using(HardwareCounter::Direction::kUp)); } SECTION("Charge Flips Sign with the Polarity Pin's State Change") { constexpr float kPositivePrimaryCharge = 0.08534f; constexpr float kNegativePrimaryCharge = -0.0512f; constexpr float kPositiveBackupCharge = 0.0512f; constexpr float kNegativeBackupCharge = -0.08534f; Ltc4150 primary_counter = Ltc4150(mock_primary_hardware_counter.get(), mock_primary_pol_pin.get(), resistance); Ltc4150 backup_counter = Ltc4150(mock_backup_hardware_counter.get(), mock_backup_pol_pin.get(), resistance); When(Method(mock_primary_pol_pin, Read)).Return(false, true); When(Method(mock_backup_pol_pin, Read)).Return(true, false); When(Method(mock_primary_hardware_counter, GetCount)).Return(-3, 5); When(Method(mock_backup_hardware_counter, GetCount)).Return(3, -5); primary_counter.Initialize(); CHECK(primary_counter.GetCharge().to<float>() == Approx(kNegativePrimaryCharge).epsilon(kResolution)); primary_pol_isr(); CHECK(primary_counter.GetCharge().to<float>() == Approx(kPositivePrimaryCharge).epsilon(kResolution)); backup_counter.Initialize(); CHECK(backup_counter.GetCharge().to<float>() == Approx(kPositiveBackupCharge).epsilon(kResolution)); backup_pol_isr(); CHECK(backup_counter.GetCharge().to<float>() == Approx(kNegativeBackupCharge).epsilon(kResolution)); } } } // namespace sjsu
43.242038
78
0.689498
diarkia124
56e8b254a097294d2995fcb3d9b47fac023e8cb5
1,101
hpp
C++
include/gbAudio/Exceptions.hpp
ComicSansMS/GhulbusAudio
895ed529d98f10cdbd68dcbcc5a5de655bb099d1
[ "MIT" ]
null
null
null
include/gbAudio/Exceptions.hpp
ComicSansMS/GhulbusAudio
895ed529d98f10cdbd68dcbcc5a5de655bb099d1
[ "MIT" ]
null
null
null
include/gbAudio/Exceptions.hpp
ComicSansMS/GhulbusAudio
895ed529d98f10cdbd68dcbcc5a5de655bb099d1
[ "MIT" ]
null
null
null
#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_AUDIO_EXCEPTIONS_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_AUDIO_EXCEPTIONS_HPP /** @file * * @brief Exceptions. * @author Andreas Weis (der_ghulbus@ghulbus-inc.de) */ #include <gbAudio/config.hpp> #include <gbBase/Exception.hpp> namespace GHULBUS_AUDIO_NAMESPACE { /** Exception decorators. */ namespace Exception_Info { using namespace GHULBUS_BASE_NAMESPACE::Exception_Info; /** Decorator Tags. * Tags are empty types used to uniquely identify a decoratory type. */ namespace Tags { struct GHULBUS_AUDIO_API invalid_enum_value { }; } /** Decorator record types. */ namespace Records { } /** @name Decorators * @{ */ /** An int representation of the invalid enum value. */ using invalid_enum_value = ::GHULBUS_BASE_NAMESPACE::ErrorInfo<Tags::invalid_enum_value, int>; /// @} } namespace Exceptions { using namespace GHULBUS_BASE_NAMESPACE::Exceptions; struct OpenALError : public GHULBUS_BASE_NAMESPACE::Exceptions::impl::ExceptionImpl {}; } } #endif
21.588235
98
0.703906
ComicSansMS
56e8f2b7b825adca7e275ce0b965086df5386b65
6,607
cpp
C++
c++/src/lac.cpp
LGDEMO/lac
49416fc738daa3d3e131b130242f2ab6eb84fb68
[ "Apache-2.0" ]
1
2021-08-05T12:12:57.000Z
2021-08-05T12:12:57.000Z
c++/src/lac.cpp
gokunwu/lac
407b5566f6c6aa6d9a43362871b71cf97d33a813
[ "Apache-2.0" ]
null
null
null
c++/src/lac.cpp
gokunwu/lac
407b5566f6c6aa6d9a43362871b71cf97d33a813
[ "Apache-2.0" ]
1
2021-08-09T12:37:39.000Z
2021-08-09T12:37:39.000Z
/* Copyright (c) 2020 Baidu, Inc. 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 "lac.h" #include "lac_util.h" #include "paddle_api.h" #include "lac_custom.h" /* LAC构造函数:初始化、装载模型和词典 */ LAC::LAC(const std::string& model_path, CODE_TYPE type) : _codetype(type), _lod(std::vector<std::vector<size_t> >(1)), _id2label_dict(new std::unordered_map<int64_t, std::string>), _q2b_dict(new std::unordered_map<std::string, std::string>), _word2id_dict(new std::unordered_map<std::string, int64_t>), custom(NULL) { // 装载词典 std::string word_dict_path = model_path + "/conf/word.dic"; load_word2id_dict(word_dict_path, *_word2id_dict); std::string q2b_dict_path = model_path + "/conf/q2b.dic"; load_q2b_dict(q2b_dict_path, *_q2b_dict); std::string label_dict_path = model_path + "/conf/tag.dic"; load_id2label_dict(label_dict_path, *_id2label_dict); // 使用AnalysisConfig装载模型,会进一步优化模型 this->_place = paddle::PaddlePlace::kCPU; paddle::AnalysisConfig config; // config.SwitchIrOptim(false); // 关闭优化 config.EnableMKLDNN(); config.SetModel(model_path + "/model"); config.DisableGpu(); config.SetCpuMathLibraryNumThreads(1); config.SwitchUseFeedFetchOps(false); this->_predictor = paddle::CreatePaddlePredictor<paddle::AnalysisConfig>(config); // 初始化输入输出变量 auto input_names = this->_predictor->GetInputNames(); this->_input_tensor = this->_predictor->GetInputTensor(input_names[0]); auto output_names = this->_predictor->GetOutputNames(); this->_output_tensor = this->_predictor->GetOutputTensor(output_names[0]); this->_oov_id = this->_word2id_dict->size() - 1; auto word_iter = this->_word2id_dict->find("OOV"); if (word_iter != this->_word2id_dict->end()) { this->_oov_id = word_iter->second; } } /* 拷贝构造函数,用于多线程重载 */ LAC::LAC(LAC &lac) : _codetype(lac._codetype), _lod(std::vector<std::vector<size_t> >(1)), _id2label_dict(lac._id2label_dict), _q2b_dict(lac._q2b_dict), _word2id_dict(lac._word2id_dict), _oov_id(lac._oov_id), _place(lac._place), _predictor(lac._predictor->Clone()), custom(lac.custom) { auto input_names = this->_predictor->GetInputNames(); this->_input_tensor = this->_predictor->GetInputTensor(input_names[0]); auto output_names = this->_predictor->GetOutputNames(); this->_output_tensor = this->_predictor->GetOutputTensor(output_names[0]); } /* 装载用户词典 */ int LAC::load_customization(const std::string& filename){ /* 多线程热加载时容易出问题,多个线程共享custom if (custom){ return custom->load_dict(filename); } */ custom = std::make_shared<Customization>(filename); return 0; } /* 将字符串输入转为Tensor */ int LAC::feed_data(const std::vector<std::string> &querys) { this->_seq_words_batch.clear(); this->_lod[0].clear(); this->_lod[0].push_back(0); int shape = 0; for (size_t i = 0; i < querys.size(); ++i) { split_words(querys[i], this->_codetype, this->_seq_words); this->_seq_words_batch.push_back(this->_seq_words); shape += this->_seq_words.size(); this->_lod[0].push_back(shape); } this->_input_tensor->SetLoD(this->_lod); this->_input_tensor->Reshape({shape, 1}); int64_t *input_d = this->_input_tensor->mutable_data<int64_t>(this->_place); int index = 0; for (size_t i = 0; i < this->_seq_words_batch.size(); ++i) { for (size_t j = 0; j < this->_seq_words_batch[i].size(); ++j) { // normalization std::string word = this->_seq_words_batch[i][j]; auto q2b_iter = this->_q2b_dict->find(word); if (q2b_iter != this->_q2b_dict->end()) { word = q2b_iter->second; } // get word_id int64_t word_id = this->_oov_id; auto word_iter = this->_word2id_dict->find(word); if (word_iter != this->_word2id_dict->end()) { word_id = word_iter->second; } input_d[index++] = word_id; } } return 0; } /* 对输出的标签进行解码转换为模型输出格式 */ int LAC::parse_targets( const std::vector<std::string> &tags, const std::vector<std::string> &words, std::vector<OutputItem> &result) { result.clear(); for (size_t i = 0; i < tags.size(); ++i) { // 若新词,则push_back一个新词,否则append到上一个词中 if (result.empty() || tags[i].rfind("B") == tags[i].length() - 1 || tags[i].rfind("S") == tags[i].length() - 1) { OutputItem output_item; output_item.word = words[i]; output_item.tag = tags[i].substr(0, tags[i].length() - 2); result.push_back(output_item); } else { result[result.size() - 1].word += words[i]; } } return 0; } std::vector<OutputItem> LAC::run(const std::string &query) { std::vector<std::string> query_vector = std::vector<std::string>({query}); auto result = run(query_vector); return result[0]; } std::vector<std::vector<OutputItem>> LAC::run(const std::vector<std::string> &querys) { this->feed_data(querys); this->_predictor->ZeroCopyRun(); // 对模型输出进行解码 int output_size = 0; int64_t *output_d = this->_output_tensor->data<int64_t>(&(this->_place), &output_size); this->_labels.clear(); this->_results_batch.clear(); for (size_t i = 0; i < this->_lod[0].size() - 1; ++i) { for (size_t j = 0; j < _lod[0][i + 1] - _lod[0][i]; ++j) { int64_t cur_label_id = output_d[_lod[0][i] + j]; auto it = this->_id2label_dict->find(cur_label_id); this->_labels.push_back(it->second); } // 装载了用户干预词典,先进行干预处理 if (custom){ custom->parse_customization(this->_seq_words_batch[i], this->_labels); } parse_targets(this->_labels, this->_seq_words_batch[i], this->_results); this->_labels.clear(); _results_batch.push_back(this->_results); } return this->_results_batch; }
32.870647
119
0.629938
LGDEMO
56eddb4248c2f08e2b86c3ec34cb5fcc8617340c
383
hpp
C++
2015/Day18/src/Light.hpp
Xav83/AdventOfCode
7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5
[ "MIT" ]
2
2019-11-14T18:11:02.000Z
2020-01-20T22:40:31.000Z
2015/Day18/src/Light.hpp
Xav83/AdventOfCode
7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5
[ "MIT" ]
null
null
null
2015/Day18/src/Light.hpp
Xav83/AdventOfCode
7e305b89abe0a497efdab0f1a3bfe2bfc24b36d5
[ "MIT" ]
null
null
null
#pragma once #include <vector> using LightState = bool; class Light { public: Light(LightState initialState); ~Light(); virtual bool isOn() const; virtual bool isOff() const; void prepareNextState(const std::vector<std::reference_wrapper<Light>> &neighbors); void nextState(); private: LightState currentState = false; LightState willChangeState = false; };
15.958333
80
0.720627
Xav83
56ee8abe8ec1f8f557be87b17f55f4c777e23c09
4,926
hpp
C++
src/lib/include/black/logic/lex.hpp
black-sat/black
80902240987312fb0e6f00227a06e9f9c9728a67
[ "MIT" ]
4
2020-09-30T15:16:22.000Z
2021-09-20T15:02:39.000Z
src/lib/include/black/logic/lex.hpp
teodorov/black
4de280ded5e99cc515141b4acc35137ba32c2469
[ "MIT" ]
42
2020-07-15T13:46:11.000Z
2022-03-10T09:42:43.000Z
src/lib/include/black/logic/lex.hpp
teodorov/black
4de280ded5e99cc515141b4acc35137ba32c2469
[ "MIT" ]
3
2020-03-30T14:39:17.000Z
2022-03-18T14:05:33.000Z
// // BLACK - Bounded Ltl sAtisfiability ChecKer // // (C) 2019 Nicola Gigante // // 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 BLACK_LEX_H_ #define BLACK_LEX_H_ #include <black/support/common.hpp> #include <black/logic/formula.hpp> #include <iostream> #include <cassert> #include <cctype> #include <optional> #include <variant> #include <vector> namespace black::internal { // Type representing tokens generated from the lexer. // WARNING: tokens must not outlive their originating lexer object. struct token { enum class type : uint8_t { boolean = 0, atom, unary_operator, binary_operator, punctuation }; // Type of non-logical tokens. Only parens, for now. enum class punctuation : uint8_t { // non-logical tokens left_paren, right_paren }; constexpr token(bool b) : _data{b} { } constexpr token(std::string_view s) : _data{s} { } constexpr token(unary::type t) : _data{t} { } constexpr token(binary::type t) : _data{t} { } constexpr token(punctuation s) : _data{s} { } template<typename T> constexpr bool is() const { return std::holds_alternative<T>(_data); } template<typename T> constexpr std::optional<T> data() const { if(auto p = std::get_if<T>(&_data); p) return {*p}; return std::nullopt; } type token_type() const { return static_cast<type>(_data.index()); } friend constexpr std::string_view to_string(token const &tok); private: // data related to recognized tokens std::variant< bool, // booleans std::string_view, // atoms unary::type, // unary operator binary::type, // binary operator punctuation // any non-logical token > _data; }; constexpr std::string_view to_string(unary::type const& t) { constexpr std::string_view toks[] = { "!", // negation "X", // tomorrow "wX", // weak tomorrow "Y", // yesterday "Z", // weak yesterday "G", // always "F", // eventually "O", // once "H", // historically }; return toks[to_underlying(t) - to_underlying(unary::type::negation)]; } constexpr std::string_view to_string(binary::type const& t) { constexpr std::string_view toks[] = { "&", // conjunction "|", // disjunction "->", // implication "<->", // iff "U", // until "R", // release "W", // weak until "M", // strong release "S", // since "T", // triggered }; return toks[to_underlying(t) - to_underlying(binary::type::conjunction)]; } constexpr std::string_view to_string(token const &tok) { using namespace std::literals; return std::visit( overloaded { [](bool b) { return b ? "true"sv : "false"sv; }, [](std::string_view s) { return s; }, [](unary::type t) { return to_string(t); }, [](binary::type t) { return to_string(t); }, [](token::punctuation s) { switch(s) { case token::punctuation::left_paren: return "("sv; case token::punctuation::right_paren: return ")"sv; } } }, tok._data); } class BLACK_EXPORT lexer { public: explicit lexer(std::istream &stream) : _stream(stream) {} std::optional<token> get() { return _token = _lex(); } std::optional<token> peek() const { return _token; } private: std::optional<token> _lex(); std::optional<token> _identifier(); bool _is_identifier_char(int c); bool _is_initial_identifier_char(int c); std::optional<token> _token = std::nullopt; std::istream &_stream; std::vector<std::string> _lexed_identifiers; }; std::ostream &operator<<(std::ostream &s, token const &t); } #endif // LEX_H_
29.147929
80
0.623427
black-sat
56f96c06b18d4aa54fbee65911eed499bd335632
735
cpp
C++
File Processing/sequentialFile.cpp
jc-andrade/cpp-exercises
8cb6234c29d4d0d5bb588bdd168d30517e60e185
[ "MIT" ]
null
null
null
File Processing/sequentialFile.cpp
jc-andrade/cpp-exercises
8cb6234c29d4d0d5bb588bdd168d30517e60e185
[ "MIT" ]
null
null
null
File Processing/sequentialFile.cpp
jc-andrade/cpp-exercises
8cb6234c29d4d0d5bb588bdd168d30517e60e185
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <fstream> // file stream #include <cstdlib> using namespace std; int main() { // ofsstream constructor opens file ofstream outClientFile("clients.txt", ios::out); // exit program if unable to create file if (!outClientFile) // overloaded ! operator { cerr << "File could not be opened" << endl; exit(1); }// end if cout << "Enter the account, name and balance." << endl << "Enter end-of-file to en input.\n? "; int account; string name; double balance; // read account, name and balance from cin, then place in file while (cin >> account >> name >> balance) { outClientFile << account << ' ' << name << ' ' << balance << endl; cout << "? "; }// end while }
21
68
0.642177
jc-andrade
56febbfe632bd6e647d854a40fdacbeee91131b0
2,052
cxx
C++
test/mpi/cxx/comm/commname2.cxx
OpenCMISS-Dependencies/mpich2
cc5f4d3fd0f8c9f2774d10deaebdced77985d839
[ "Unlicense" ]
7
2015-12-31T03:15:50.000Z
2020-08-15T00:54:47.000Z
test/mpi/cxx/comm/commname2.cxx
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
3
2015-12-30T22:28:15.000Z
2017-05-16T19:17:42.000Z
test/mpi/cxx/comm/commname2.cxx
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
3
2015-12-29T22:14:56.000Z
2019-06-13T07:23:35.000Z
/* -*- Mode: C++; c-basic-offset:4 ; -*- */ /* * * (C) 2003 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include "mpi.h" #include "mpitestconf.h" #ifdef HAVE_IOSTREAM // Not all C++ compilers have iostream instead of iostream.h #include <iostream> #ifdef HAVE_NAMESPACE_STD // Those that do often need the std namespace; otherwise, a bare "cout" // is likely to fail to compile using namespace std; #endif #else #include <iostream.h> #endif #include <string.h> #include <stdio.h> #include "mpitestcxx.h" int main( int argc, char **argv ) { int errs = 0; char name[MPI_MAX_OBJECT_NAME], tname[MPI_MAX_OBJECT_NAME]; int rlen; int i, n; MPI::Comm *(comm[10]); MTest_Init( ); // Test predefined names MPI::COMM_WORLD.Get_name( name, rlen ); if (strcmp( name, "MPI_COMM_WORLD" ) != 0) { errs ++; cout << "Name of COMM_WORLD was " << name << "\n"; } if (rlen != strlen(name)) { errs++; cout << "Resultlen for COMM_WORLD is incorrect: " << rlen << "\n"; } MPI::COMM_SELF.Get_name( name, rlen ); if (strcmp( name, "MPI_COMM_SELF" ) != 0) { errs ++; cout << "Name of COMM_SELF was " << name << "\n"; } if (rlen != strlen(name)) { errs++; cout << "Resultlen for COMM_SELF is incorrect: " << rlen << "\n"; } // Reset name of comm_world MPI::COMM_WORLD.Set_name( "FooBar !" ); MPI::COMM_WORLD.Get_name( name, rlen ); if (strcmp( name, "FooBar !" ) != 0) { errs ++; cout << "Changed name of COMM_WORLD was " << name << "\n"; } // Test a few other communicators n = 0; while (MTestGetComm( &comm[n], 1 ) && n < 4) { sprintf( name, "test%d", n ); comm[n]->Set_name( name ); n++; } for (i=0; i<n; i++) { sprintf( tname, "test%d", i ); comm[i]->Get_name( name, rlen ); if (strcmp( name, tname ) != 0) { errs++; cout << "comm[" << i << "] gave name " << name << "\n"; } MTestFreeComm ( *comm[i] ); } MTest_Finalize( errs ); MPI::Finalize(); return 0; }
24.428571
71
0.575049
OpenCMISS-Dependencies
56fee6d8c1122247e1eeced1fadf0074045897e6
57
cpp
C++
Tga3D/Source/tga2dcore/tga2d/math/CommonMath.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
1
2022-03-10T11:43:24.000Z
2022-03-10T11:43:24.000Z
Tga3D/Source/tga2dcore/tga2d/math/CommonMath.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
Tga3D/Source/tga2dcore/tga2d/math/CommonMath.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <tga2d/math/CommonMath.h>
19
35
0.719298
sarisman84
7102c1e66822922c85dd02983bbc02586b572c14
3,564
cpp
C++
Source/UnrealGT/Private/Streamers/GTThreadedTCPStreamer.cpp
charleshamesse/unrealgt
04f72c344b468a39337a2e6b2f12576f501bccfa
[ "MIT" ]
13
2020-04-19T22:30:54.000Z
2022-03-28T11:39:37.000Z
Source/UnrealGT/Private/Streamers/GTThreadedTCPStreamer.cpp
charleshamesse/unrealgt
04f72c344b468a39337a2e6b2f12576f501bccfa
[ "MIT" ]
9
2020-03-30T22:27:38.000Z
2022-03-24T16:49:37.000Z
Source/UnrealGT/Private/Streamers/GTThreadedTCPStreamer.cpp
charleshamesse/unrealgt
04f72c344b468a39337a2e6b2f12576f501bccfa
[ "MIT" ]
4
2020-05-10T18:41:16.000Z
2022-03-16T07:01:13.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "Streamers/GTThreadedTCPStreamer.h" #include <IPAddress.h> #include <SocketSubsystem.h> #include <Sockets.h> FGTThreadedTCPStreamer::FGTThreadedTCPStreamer(FString IPAddress, uint32 Port) : Socket(nullptr) , IPAddress(IPAddress) , Port(Port) , bIsSocketConnected(false) , bShouldStop(false) { Thread = FRunnableThread::Create(this, TEXT("TCPStreamerThread")); } FGTThreadedTCPStreamer::~FGTThreadedTCPStreamer() { if (Thread) { Thread->Kill(true); delete Thread; Thread = nullptr; } } void FGTThreadedTCPStreamer::SendMessage(const TArray<uint8>& MessagePayload) { // Dont accept requests if we dont have a connection if (!bIsSocketConnected) { return; } MessageRequests.Enqueue(MessagePayload); } bool FGTThreadedTCPStreamer::Init() { TryConnect(); return true; } uint32 FGTThreadedTCPStreamer::Run() { while (!bShouldStop) { // Important that tryconnect is called first before checking the queue if (TryConnect() && !MessageRequests.IsEmpty()) { TArray<uint8> Data; MessageRequests.Dequeue(Data); int32 ByteCount = Data.Num(); int32 TotalMessageLength = ByteCount + sizeof(ByteCount); // Little to Big Endian int32 ByteCountBigEndian = (ByteCount & 0x000000FFU) << 24 | (ByteCount & 0x0000FF00U) << 8 | (ByteCount & 0x00FF0000U) >> 8 | (ByteCount & 0xFF000000U) >> 24; uint8* Packet = (uint8*)FMemory::Malloc(TotalMessageLength); FMemory::Memcpy(Packet, &ByteCountBigEndian, sizeof(int32)); FMemory::Memcpy(Packet + sizeof(int32), Data.GetData(), Data.Num()); int32 BytesSend = 0; int32 TotalBytesSend = 0; while (TotalBytesSend != TotalMessageLength) { Socket->Send( Packet + TotalBytesSend, TotalMessageLength - TotalBytesSend, BytesSend); if (BytesSend == -1) { bIsSocketConnected = false; Socket->Close(); ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(Socket); break; } TotalBytesSend += BytesSend; } FMemory::Free(Packet); } // If we still dont have a connection sleep a bit longer if (!bIsSocketConnected) { FPlatformProcess::SleepNoStats(0.5f); } else { FPlatformProcess::SleepNoStats(1 / 120.f); } } return 0; } void FGTThreadedTCPStreamer::Stop() { bShouldStop = true; } void FGTThreadedTCPStreamer::Exit() { if (Socket) { ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(Socket); } } bool FGTThreadedTCPStreamer::TryConnect() { if (!bIsSocketConnected || !Socket) { Socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM) ->CreateSocket(NAME_Stream, TEXT("default"), false); TSharedRef<FInternetAddr> InternetAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr(); bool bIsIPValid; InternetAddr->SetIp(*IPAddress, bIsIPValid); InternetAddr->SetPort(Port); bIsSocketConnected = Socket->Connect(*InternetAddr); return bIsSocketConnected; } return true; }
28.741935
93
0.60578
charleshamesse
7105f4fbb57497a242234d787da69363763021c0
934
cc
C++
cpp/leetcode/151.reverse-words-in-a-string.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
3
2021-03-03T13:18:23.000Z
2022-02-09T07:49:24.000Z
cpp/leetcode/151.reverse-words-in-a-string.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
null
null
null
cpp/leetcode/151.reverse-words-in-a-string.cc
liubang/laboratory
747f239a123cd0c2e5eeba893b9a4d1536555b1e
[ "MIT" ]
1
2021-03-29T15:21:42.000Z
2021-03-29T15:21:42.000Z
#include <gtest/gtest.h> #include <string> namespace { class Solution { public: std::string reverseWords(const std::string& s) { int len = s.length(); if (len == 0 || len == 1) { return s; } std::string ret; int i = 0; while (s[i] == ' ' && i < len) { i++; } for (; i < len; ++i) { std::string tmp; while (s[i] != ' ' && i < len) { tmp.push_back(s[i++]); } if (!tmp.empty()) { tmp.push_back(' '); ret.insert(0, tmp); } } return ret.erase(ret.find_last_not_of(' ') + 1); } }; } // namespace TEST(Leetcode, reverse_words_in_a_string) { Solution s; { std::string input = " hello world! "; std::string exp = "world! hello"; EXPECT_EQ(exp, s.reverseWords(input)); } { std::string input = "a good example"; std::string exp = "example good a"; EXPECT_EQ(exp, s.reverseWords(input)); } }
19.87234
52
0.512848
liubang
710924e57ad5a3ef8fe8fe0b2e58fea9253663d7
760
hpp
C++
include/telnetpp/options/suppress_ga/server.hpp
KazDragon/telnetpp
c9b49588fca2c2186189421d2711c0e4febe13ed
[ "MIT" ]
49
2015-12-15T22:35:32.000Z
2022-03-30T16:08:10.000Z
include/telnetpp/options/suppress_ga/server.hpp
KazDragon/telnetpp
c9b49588fca2c2186189421d2711c0e4febe13ed
[ "MIT" ]
188
2015-10-02T16:07:30.000Z
2022-03-08T06:53:29.000Z
include/telnetpp/options/suppress_ga/server.hpp
KazDragon/telnetpp
c9b49588fca2c2186189421d2711c0e4febe13ed
[ "MIT" ]
15
2015-10-02T06:56:36.000Z
2021-05-21T18:59:26.000Z
#pragma once #include "telnetpp/core.hpp" #include "telnetpp/options/basic_server.hpp" #include "telnetpp/options/suppress_ga/detail/protocol.hpp" namespace telnetpp { namespace options { namespace suppress_ga { //* ========================================================================= /// \class telnetpp::options::suppress_ga::server /// \extends telnetpp::server_option /// \brief An implementation of the server side of the Telnet Suppress Go- /// Ahead option. /// \see https://tools.ietf.org/html/rfc858 //* ========================================================================= class TELNETPP_EXPORT server : public telnetpp::options::basic_server< telnetpp::options::suppress_ga::detail::option > { public: server() noexcept; }; }}}
30.4
77
0.594737
KazDragon
710cd7933ad09da9ec2884f6dd2d4cc0a6f6858b
12,596
cpp
C++
Source/Render/RenderData/RenderLight.cpp
PolyAH/RealTimeGI
372638568ff22a4dea9c1ff448cec42e3e25aaf2
[ "MIT" ]
6
2021-10-31T14:43:04.000Z
2022-03-12T12:56:27.000Z
Source/Render/RenderData/RenderLight.cpp
PolyAH/RealTimeGI
372638568ff22a4dea9c1ff448cec42e3e25aaf2
[ "MIT" ]
null
null
null
Source/Render/RenderData/RenderLight.cpp
PolyAH/RealTimeGI
372638568ff22a4dea9c1ff448cec42e3e25aaf2
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Ammar Herzallah // // 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 "RenderLight.h" #include "Application.h" #include "Render/Renderer.h" #include "Render/RendererPipeline.h" #include "Render/RenderStageLightProbes.h" #include "Render/RenderData/Shaders/RenderShader.h" #include "Render/RenderData/Primitives/RenderSphere.h" #include "RenderTypes.h" #include "Render/VKInterface/VKIImage.h" #include "Render/VKInterface/VKIRenderPass.h" #include "Render/VKInterface/VKIFramebuffer.h" #include "Render/VKInterface/VKIDescriptor.h" // --- -- - -- --- --- -- - -- --- --- -- - -- --- --- -- - -- --- --- -- - -- --- --- -- - -- --- RenderLightProbe::RenderLightProbe() : mPosition(0.0f) , mRadius(0.0f) , mIsDirty(2) { } RenderLightProbe::~RenderLightProbe() { } void RenderLightProbe::Create() { VKIDevice* device = Application::Get().GetRenderer()->GetVKDevice(); Renderer* renderer = Application::Get().GetRenderer(); RendererPipeline* rpipeline = renderer->GetPipeline(); VkExtent2D size = { LIGHT_PROBES_TARGET_SIZE, LIGHT_PROBES_TARGET_SIZE }; // Irradiance Map. { mIrradiance = UniquePtr<VKIImage>(new VKIImage()); mIrradiance->SetImageInfo(VK_IMAGE_TYPE_2D, VK_FORMAT_R16G16B16A16_SFLOAT, size, VK_IMAGE_LAYOUT_UNDEFINED); mIrradiance->SetUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); mIrradiance->SetLayers(6, true); mIrradiance->Create(device); // Image View. mView[0] = UniquePtr<VKIImageView>(new VKIImageView()); mView[0]->SetType(VK_IMAGE_VIEW_TYPE_CUBE); mView[0]->SetViewInfo(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 6); mView[0]->Create(device, mIrradiance.get()); // Sampler. mSampler[0] = UniquePtr<VKISampler>(new VKISampler()); mSampler[0]->SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); mSampler[0]->SetFilter(VK_FILTER_LINEAR, VK_FILTER_LINEAR); mSampler[0]->CreateSampler(device); // Framebuffer for pre-filter pass mIrradianceFB = UniquePtr<VKIFramebuffer>(new VKIFramebuffer()); mIrradianceFB->SetSize(size); mIrradianceFB->SetLayers(6); mIrradianceFB->SetImgView(0, mView[0].get()); mIrradianceFB->CreateFrameBuffer(device, rpipeline->GetStageLightProbes()->GetIrradianceFilterPass()); } // Radiance Map. { mRadiance = UniquePtr<VKIImage>(new VKIImage()); mRadiance->SetImageInfo(VK_IMAGE_TYPE_2D, VK_FORMAT_R16G16B16A16_SFLOAT, size, VK_IMAGE_LAYOUT_UNDEFINED); mRadiance->SetUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); mRadiance->SetLayers(6, true); mRadiance->Create(device); // Image View. mView[1] = UniquePtr<VKIImageView>(new VKIImageView()); mView[1]->SetType(VK_IMAGE_VIEW_TYPE_CUBE); mView[1]->SetViewInfo(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 6); mView[1]->Create(device, mRadiance.get()); // Sampler. mSampler[1] = UniquePtr<VKISampler>(new VKISampler()); mSampler[1]->SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); mSampler[1]->SetFilter(VK_FILTER_LINEAR, VK_FILTER_LINEAR); mSampler[1]->CreateSampler(device); // Framebuffer for pre-filter pass mRadianceFB = UniquePtr<VKIFramebuffer>(new VKIFramebuffer()); mRadianceFB->SetSize(size); mRadianceFB->SetLayers(6); mRadianceFB->SetImgView(0, mView[1].get()); mRadianceFB->CreateFrameBuffer(device, rpipeline->GetStageLightProbes()->GetIrradianceFilterPass()); } { mLightingSet = UniquePtr<VKIDescriptorSet>(new VKIDescriptorSet()); mLightingSet->SetLayout(rpipeline->GetStageLightProbes()->GetLightingShader()->GetLayout()); mLightingSet->CreateDescriptorSet(device, Renderer::NUM_CONCURRENT_FRAMES); rpipeline->AddGBufferToDescSet(mLightingSet.get()); mLightingSet->AddDescriptor(6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[0].get(), mSampler[0].get()); mLightingSet->AddDescriptor(7, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[1].get(), mSampler[1].get()); mLightingSet->UpdateSets(); } { mVisualizeSet = UniquePtr<VKIDescriptorSet>(new VKIDescriptorSet()); mVisualizeSet->SetLayout(rpipeline->GetStageLightProbes()->GetVisualizeShader()->GetLayout()); mVisualizeSet->CreateDescriptorSet(device, Renderer::NUM_CONCURRENT_FRAMES); mVisualizeSet->AddDescriptor(RenderShader::COMMON_BLOCK_BINDING, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_ALL, rpipeline->GetUniforms().common->GetBuffers()); mVisualizeSet->AddDescriptor(10, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[0].get(), mSampler[0].get()); mVisualizeSet->AddDescriptor(11, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[1].get(), mSampler[1].get()); mVisualizeSet->UpdateSets(); } { mIrradianceFilterSet = UniquePtr<VKIDescriptorSet>(new VKIDescriptorSet()); mIrradianceFilterSet->SetLayout(rpipeline->GetStageLightProbes()->GetIrradianceFilterShader()->GetLayout()); mIrradianceFilterSet->CreateDescriptorSet(device, Renderer::NUM_CONCURRENT_FRAMES); mIrradianceFilterSet->AddDescriptor(RenderShader::COMMON_BLOCK_BINDING, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_ALL, rpipeline->GetUniforms().common->GetBuffers()); mIrradianceFilterSet->AddDescriptor(1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_GEOMETRY_BIT, renderer->GetSphere()->GetSphereUnifrom()->GetBuffers()); mIrradianceFilterSet->AddDescriptor(2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[1].get(), mSampler[1].get()); mIrradianceFilterSet->UpdateSets(); } } void RenderLightProbe::Destroy() { mIrradiance->Destroy(); mView[0]->Destroy(); mSampler[0]->Destroy(); mIrradianceFB->Destroy(); mRadiance->Destroy(); mView[1]->Destroy(); mSampler[1]->Destroy(); mRadianceFB->Destroy(); mLightingSet->Destroy(); mVisualizeSet->Destroy(); mIrradianceFilterSet->Destroy(); } // --- -- - -- --- --- -- - -- --- --- -- - -- --- --- -- - -- --- --- -- - -- --- --- -- - -- --- RenderIrradianceVolume::RenderIrradianceVolume() : mStart(0.0f) , mExtent(0.0f) , mCount(0) , mAtten(0.0f) { } RenderIrradianceVolume::~RenderIrradianceVolume() { } void RenderIrradianceVolume::SetVolume(const glm::vec3& start, const glm::vec3& extent, const glm::ivec3& count) { mStart = start; mExtent = extent; mCount = count; } uint32_t RenderIrradianceVolume::GetNumProbes() { return mCount.x * mCount.y * mCount.z; } glm::ivec3 RenderIrradianceVolume::GetProbeGridCoord(uint32_t index) { glm::ivec3 grid; grid.z = (index / (mCount.x * mCount.y)); index -= grid.z * (mCount.x * mCount.y); grid.y = (index / mCount.x); index -= grid.y * mCount.x; grid.x = index; return grid; } glm::vec3 RenderIrradianceVolume::GetProbePosition(uint32_t index) { glm::vec3 grid = GetProbeGridCoord(index); grid /= glm::vec3(mCount); return mStart + grid * mExtent + (mExtent / glm::vec3(mCount) * 0.5f); } uint32_t RenderIrradianceVolume::GetProbeLayer(uint32_t index, uint32_t face) { return index * 6 + face; } void RenderIrradianceVolume::Create() { CHECK(GetNumProbes() > 0); VKIDevice* device = Application::Get().GetRenderer()->GetVKDevice(); Renderer* renderer = Application::Get().GetRenderer(); RendererPipeline* rpipeline = renderer->GetPipeline(); VkExtent2D size = { IRRADIANCE_VOLUME_TARGET_SIZE, IRRADIANCE_VOLUME_TARGET_SIZE }; uint32_t numLayers = GetNumProbes() * 6; // Number of layers in light probe. // Irradiance Map. { mIrradiance = UniquePtr<VKIImage>(new VKIImage()); mIrradiance->SetImageInfo(VK_IMAGE_TYPE_2D, VK_FORMAT_R16G16B16A16_SFLOAT, size, VK_IMAGE_LAYOUT_UNDEFINED); mIrradiance->SetUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); mIrradiance->SetLayers(numLayers, true); mIrradiance->Create(device); // Image View. mView[0] = UniquePtr<VKIImageView>(new VKIImageView()); mView[0]->SetType(VK_IMAGE_VIEW_TYPE_CUBE_ARRAY); mView[0]->SetViewInfo(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, numLayers); mView[0]->Create(device, mIrradiance.get()); // Sampler. mSampler[0] = UniquePtr<VKISampler>(new VKISampler()); mSampler[0]->SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); mSampler[0]->SetFilter(VK_FILTER_LINEAR, VK_FILTER_LINEAR); mSampler[0]->CreateSampler(device); // Framebuffer for pre-filter pass mIrradianceFB = UniquePtr<VKIFramebuffer>(new VKIFramebuffer()); mIrradianceFB->SetSize(size); mIrradianceFB->SetLayers(numLayers); mIrradianceFB->SetImgView(0, mView[0].get()); mIrradianceFB->CreateFrameBuffer(device, rpipeline->GetStageLightProbes()->GetIrradianceFilterPass()); } // Radiance Map. { mRadiance = UniquePtr<VKIImage>(new VKIImage()); mRadiance->SetImageInfo(VK_IMAGE_TYPE_2D, VK_FORMAT_R16G16B16A16_SFLOAT, size, VK_IMAGE_LAYOUT_UNDEFINED); mRadiance->SetUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); mRadiance->SetLayers(numLayers, true); mRadiance->Create(device); // Image View. mView[1] = UniquePtr<VKIImageView>(new VKIImageView()); mView[1]->SetType(VK_IMAGE_VIEW_TYPE_CUBE_ARRAY); mView[1]->SetViewInfo(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, numLayers); mView[1]->Create(device, mRadiance.get()); // Sampler. mSampler[1] = UniquePtr<VKISampler>(new VKISampler()); mSampler[1]->SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE); mSampler[1]->SetFilter(VK_FILTER_LINEAR, VK_FILTER_LINEAR); mSampler[1]->CreateSampler(device); // Framebuffer for pre-filter pass mRadianceFB = UniquePtr<VKIFramebuffer>(new VKIFramebuffer()); mRadianceFB->SetSize(size); mRadianceFB->SetLayers(numLayers); mRadianceFB->SetImgView(0, mView[1].get()); mRadianceFB->CreateFrameBuffer(device, rpipeline->GetStageLightProbes()->GetIrradianceFilterPass()); } { mLightingSet = UniquePtr<VKIDescriptorSet>(new VKIDescriptorSet()); mLightingSet->SetLayout(rpipeline->GetStageLightProbes()->GetLightingVolumeShader()->GetLayout()); mLightingSet->CreateDescriptorSet(device, Renderer::NUM_CONCURRENT_FRAMES); rpipeline->AddGBufferToDescSet(mLightingSet.get()); mLightingSet->AddDescriptor(6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[0].get(), mSampler[0].get()); mLightingSet->AddDescriptor(7, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[1].get(), mSampler[1].get()); mLightingSet->UpdateSets(); } { mIrradianceFilterSet = UniquePtr<VKIDescriptorSet>(new VKIDescriptorSet()); mIrradianceFilterSet->SetLayout(rpipeline->GetStageLightProbes()->GetIrradianceArrayFilterShader()->GetLayout()); mIrradianceFilterSet->CreateDescriptorSet(device, Renderer::NUM_CONCURRENT_FRAMES); mIrradianceFilterSet->AddDescriptor(RenderShader::COMMON_BLOCK_BINDING, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_ALL, rpipeline->GetUniforms().common->GetBuffers()); mIrradianceFilterSet->AddDescriptor(1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_GEOMETRY_BIT, renderer->GetSphere()->GetSphereUnifrom()->GetBuffers()); mIrradianceFilterSet->AddDescriptor(2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, mView[1].get(), mSampler[1].get()); mIrradianceFilterSet->UpdateSets(); } } void RenderIrradianceVolume::Destroy() { mIrradiance->Destroy(); mView[0]->Destroy(); mSampler[0]->Destroy(); mIrradianceFB->Destroy(); mRadiance->Destroy(); mView[1]->Destroy(); mSampler[1]->Destroy(); mRadianceFB->Destroy(); mLightingSet->Destroy(); mIrradianceFilterSet->Destroy(); }
32.050891
115
0.753652
PolyAH
710e796ba96f393c07dc05a94e53bedbd64dbc21
5,904
cpp
C++
src/tablestore/core/impl/sync_client.cpp
TimeExceed/aliyun-tablestore-cpp-sdk
f8d2fdf500badf70073dff4e21a5d2d7aa7d3853
[ "BSD-3-Clause" ]
2
2020-02-24T06:51:55.000Z
2020-04-24T14:40:10.000Z
src/tablestore/core/impl/sync_client.cpp
TimeExceed/aliyun-tablestore-cpp-sdk
f8d2fdf500badf70073dff4e21a5d2d7aa7d3853
[ "BSD-3-Clause" ]
null
null
null
src/tablestore/core/impl/sync_client.cpp
TimeExceed/aliyun-tablestore-cpp-sdk
f8d2fdf500badf70073dff4e21a5d2d7aa7d3853
[ "BSD-3-Clause" ]
1
2020-02-24T06:51:57.000Z
2020-02-24T06:51:57.000Z
/* BSD 3-Clause License Copyright (c) 2017, Alibaba Cloud All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sync_client.hpp" #include "async_client.hpp" #include "async_client_base.hpp" #include "api_traits.hpp" #include "tablestore/util/try.hpp" #include "tablestore/util/threading.hpp" #include <boost/ref.hpp> #include <tr1/functional> using namespace std; using namespace std::tr1; using namespace std::tr1::placeholders; using namespace aliyun::tablestore::util; namespace aliyun { namespace tablestore { namespace core { namespace impl { namespace { template<Action kAction> void callback( Semaphore& sem, Optional<OTSError>& outErr, typename impl::ApiTraits<kAction>::ApiResponse& outResp, Optional<OTSError>& inErr, typename impl::ApiTraits<kAction>::ApiResponse& inResp) { if (inErr.present()) { moveAssign(outErr, util::move(inErr)); } else { moveAssign(outResp, util::move(inResp)); } sem.post(); } template<Action kAction> Optional<OTSError> go( typename impl::ApiTraits<kAction>::ApiResponse& resp, const typename impl::ApiTraits<kAction>::ApiRequest& req, impl::AsyncClientBase& ac) { typedef impl::AsyncClientBase::Context<kAction> Context; typedef typename impl::ApiTraits<kAction>::ApiResponse Response; Tracker tracker(Tracker::create(ac.randomGenerator())); Semaphore sem(0); Optional<OTSError> err; function<void(Optional<OTSError>&, Response&)> cb = bind(&callback<kAction>, boost::ref(sem), boost::ref(err), boost::ref(resp), _1, _2); auto_ptr<Context> ctx(new Context(ac, tracker)); TRY(ctx->build(req, cb)); ctx.release()->issue(); sem.wait(); return err; } } // namespace SyncClient::SyncClient(impl::AsyncClientBase* ac) : mAsyncClient(ac) {} SyncClient::SyncClient(AsyncClient& client) : mAsyncClient(client.mAsyncClient) {} util::Logger& SyncClient::mutableLogger() { return mAsyncClient->mutableLogger(); } const deque<shared_ptr<util::Actor> >& SyncClient::actors() const { return mAsyncClient->actors(); } const RetryStrategy& SyncClient::retryStrategy() const { return mAsyncClient->retryStrategy(); } Optional<OTSError> SyncClient::listTable( ListTableResponse& resp, const ListTableRequest& req) { return go<kApi_ListTable>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::createTable( CreateTableResponse& resp, const CreateTableRequest& req) { return go<kApi_CreateTable>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::deleteTable( DeleteTableResponse& resp, const DeleteTableRequest& req) { return go<kApi_DeleteTable>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::describeTable( DescribeTableResponse& resp, const DescribeTableRequest& req) { return go<kApi_DescribeTable>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::updateTable( UpdateTableResponse& resp, const UpdateTableRequest& req) { return go<kApi_UpdateTable>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::computeSplitsBySize( ComputeSplitsBySizeResponse& resp, const ComputeSplitsBySizeRequest& req) { return go<kApi_ComputeSplitsBySize>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::putRow(PutRowResponse& resp, const PutRowRequest& req) { return go<kApi_PutRow>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::getRow(GetRowResponse& resp, const GetRowRequest& req) { return go<kApi_GetRow>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::getRange(GetRangeResponse& resp, const GetRangeRequest& req) { return go<kApi_GetRange>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::updateRow( UpdateRowResponse& resp, const UpdateRowRequest& req) { return go<kApi_UpdateRow>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::deleteRow( DeleteRowResponse& resp, const DeleteRowRequest& req) { return go<kApi_DeleteRow>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::batchGetRow( BatchGetRowResponse& resp, const BatchGetRowRequest& req) { return go<kApi_BatchGetRow>(resp, req, *mAsyncClient); } Optional<OTSError> SyncClient::batchWriteRow( BatchWriteRowResponse& resp, const BatchWriteRowRequest& req) { return go<kApi_BatchWriteRow>(resp, req, *mAsyncClient); } } // namespace impl } // namespace core } // namespace tablestore } // namespace aliyun
29.668342
91
0.747121
TimeExceed
7116d4f2d25eb3519c6fe7e70d5d8418c62dcecb
3,155
cpp
C++
PLatformner/Motor2D/j2LifeItem.cpp
AdrianFR99/Raider-of-the-Lost-World
6684f25ad98a9870a4b02767c1912e0984b6ccd5
[ "MIT" ]
1
2020-06-07T14:41:18.000Z
2020-06-07T14:41:18.000Z
PLatformner/Motor2D/j2LifeItem.cpp
AdrianFR99/Raider-of-the-Lost-World
6684f25ad98a9870a4b02767c1912e0984b6ccd5
[ "MIT" ]
null
null
null
PLatformner/Motor2D/j2LifeItem.cpp
AdrianFR99/Raider-of-the-Lost-World
6684f25ad98a9870a4b02767c1912e0984b6ccd5
[ "MIT" ]
null
null
null
#include "j2LifeItem.h" #include "j1App.h" #include "j1Textures.h" #include "j1Render.h" #include "j2Collision.h" #include "j2EntityManager.h" #include "j1Audio.h" #include "j2Player.h" j2LifeItem::j2LifeItem():j2StaticEntity() { name = "RedGem"; pugi::xml_parse_result result2 = config.load_file("config.xml"); PathSound = config.child("config").child("entities").child("Items").child("FX").child("Life").attribute("path").as_string(); EntitiesEnable = true; type = ENTITY_TYPE::LIFE_ITEM; } j2LifeItem::~j2LifeItem() { } bool j2LifeItem::Start() { EntityText = App->tex->Load("textures/GemRed.png"); EntityRect = { 0,0,9,9 }; Offsets.colliderOffset = { 0,0 }; AnimationRect = { 0,0,9,9 }; LifeSound = App->audio->LoadFx(PathSound.GetString()); EntityCollider = App->collision->AddCollider(EntityRect, COLLIDER_ITEM, App->entities); colliders.add(EntityCollider); EntityCollider->SetPos(position.x + Offsets.colliderOffset.x , position.y + Offsets.colliderOffset.y); return true; } bool j2LifeItem::PreUpdate() { return true; } bool j2LifeItem::Update(float dt, bool do_logic) { return true; } bool j2LifeItem::PostUpdate() { App->render->Blit(EntityText, position.x, position.y, &AnimationRect, SDL_FLIP_NONE); return true; } bool j2LifeItem::CleanUp() { if (EntityCollider != nullptr) { for (int i = 0; i < colliders.count(); ++i) { colliders.At(i)->data->to_delete = true; colliders.At(i)->data = nullptr; } EntityCollider = nullptr; } App->tex->UnLoad(EntityText); App->entities->DestroyEntity(this); return true; } bool j2LifeItem::Load(pugi::xml_node& data) { for (pugi::xml_node EntityItem = data.child("Entitylife"); EntityItem; EntityItem = EntityItem.next_sibling("Entitylife")) { if (EntityItem.attribute("id").as_int() == id) { EntitiesEnable = EntityItem.attribute("Enabled").as_bool(); position.x = EntityItem.attribute("PositionX").as_int(); position.y = EntityItem.attribute("PositionY").as_int(); if (EntityItem.attribute("touched").as_bool() == false && touched == true) { EntityCollider = App->collision->AddCollider(EntityRect, COLLIDER_ITEM, App->entities); colliders.add(EntityCollider); EntityCollider->SetPos(position.x + Offsets.colliderOffset.x, position.y + Offsets.colliderOffset.y); } touched = EntityItem.attribute("touched").as_bool(); break; } } return true; } bool j2LifeItem::Save(pugi::xml_node& data) const { pugi::xml_node life = data.append_child("Entitylife"); life.append_attribute("id") = id; life.append_attribute("Enabled") = EntitiesEnable; life.append_attribute("PositionX") = position.x; life.append_attribute("PositionY") = position.y; life.append_attribute("touched") = touched; return true; } void j2LifeItem::OnCollision(Collider* c1, Collider* c2) { if (c2->type == COLLIDER_PLAYER) { touched = true; App->audio->PlayFx(LifeSound, 0); App->entities->player->HitsToRecive++; for (int i = 0; i < colliders.count(); ++i) { colliders.At(i)->data->to_delete = true; } EntityCollider = nullptr; EntitiesEnable = false; } }
19.968354
125
0.689699
AdrianFR99
711e5739b829f17754c8990508504e7fafebec08
2,573
cpp
C++
src/data/RtMotion.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
null
null
null
src/data/RtMotion.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
null
null
null
src/data/RtMotion.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * RtMotion.cpp defines a class to store subject motion * * Copyright 2007-2013, the MURFI dev team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include"RtMotion.h" //*** constructors/destructors ***// RtMotion::RtMotion() : RtData() { ACE_TRACE(("RtMRIImage::RtMotion()")); dataID.setModuleID("motion"); motion[TRANSLATION_X] = motion[TRANSLATION_Y] = motion[TRANSLATION_Z] = motion[ROTATION_X] = motion[ROTATION_Y] = motion[ROTATION_Z] = 0.0; } // construct with motion RtMotion::RtMotion(double tx, double ty, double tz, double rx, double ry, double rz) { ACE_TRACE(("RtMRIImage::RtMotion()")); dataID.setModuleID("motion"); setMotion(tx, ty, tz, rx, ry, rz); } RtMotion::~RtMotion() { } // set the motion vector void RtMotion::setMotion(Motion _motion) { memcpy(motion, _motion, NUM_MOTION_DIMENSIONS * sizeof (double)); } // set the motion vector void RtMotion::setMotion(double tx, double ty, double tz, double rx, double ry, double rz) { motion[TRANSLATION_X] = tx; motion[TRANSLATION_Y] = ty; motion[TRANSLATION_Z] = tz; motion[ROTATION_X] = rx; motion[ROTATION_Y] = ry; motion[ROTATION_Z] = rz; } // set a single motion dimension void RtMotion::setMotionDimension(double m, MotionDimension d) { if (d < 0 || d >= NUM_MOTION_DIMENSIONS) { return; } motion[d] = m; } // get the motion vector double* const RtMotion::getMotion() { return motion; } // get a single motion dimension double RtMotion::getMotionDimension(MotionDimension d) { if (d < 0 || d >= NUM_MOTION_DIMENSIONS) { return 0.0; } return motion[d]; } // serialize as xml (dummy function) TiXmlElement* RtMotion::serializeAsXML(TiXmlElement *requestElement) { return new TiXmlElement("motion"); } // unserialize xml (dummy function) void RtMotion::unserializeXML(TiXmlElement* element) { }
26.802083
77
0.650214
cdla
711ff260a7014389e2ce176840478ecd3f06dccf
868
hpp
C++
contrib/autoboost/autoboost/thread/csbl/memory/default_delete.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
contrib/autoboost/autoboost/thread/csbl/memory/default_delete.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
contrib/autoboost/autoboost/thread/csbl/memory/default_delete.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2013 Vicente J. Botet Escriba // // 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) // // 2013/10 Vicente J. Botet Escriba // Creation. #ifndef AUTOBOOST_CSBL_MEMORY_DEFAULT_DELETE_HPP #define AUTOBOOST_CSBL_MEMORY_DEFAULT_DELETE_HPP #include <autoboost/thread/csbl/memory/config.hpp> // 20.8.1 class template unique_ptr: // default_delete #if defined AUTOBOOST_NO_CXX11_SMART_PTR #include <autoboost/move/unique_ptr.hpp> namespace autoboost { namespace csbl { using ::autoboost::movelib::default_delete; } } #else namespace autoboost { namespace csbl { using ::std::default_delete; } } #endif // defined AUTOBOOST_NO_CXX11_SMART_PTR namespace autoboost { using ::autoboost::csbl::default_delete; } #endif // header
20.666667
80
0.753456
CaseyCarter
7122a27c62d75f08fe9887ebd7be1890f04d04bd
2,387
cxx
C++
examples/microservice.cxx
dmxvlx/microplugins
563dd6dd8c3331eb48872104b343cf5f53787d23
[ "BSL-1.0" ]
38
2018-08-26T16:39:21.000Z
2022-01-24T06:08:59.000Z
examples/microservice.cxx
dmxvlx/microplugins
563dd6dd8c3331eb48872104b343cf5f53787d23
[ "BSL-1.0" ]
1
2019-05-07T13:40:32.000Z
2019-05-07T17:57:26.000Z
examples/microservice.cxx
dmxvlx/microplugins
563dd6dd8c3331eb48872104b343cf5f53787d23
[ "BSL-1.0" ]
11
2018-09-07T03:02:21.000Z
2021-11-22T11:12:57.000Z
#ifndef MICROSERVICE_CXX #define MICROSERVICE_CXX // uncoment for disable debug information // #define NDEBUG #include "plugins.hpp" #include <csignal> static std::any service(std::any a1) { int ret = 0; std::shared_ptr<micro::plugins<>> manager = std::any_cast<std::shared_ptr<micro::plugins<>>>(a1); // we can do loop while manager->is_run() - for real service ... if (manager->is_run()) { std::shared_ptr<micro::iplugin<>> plugin1 = manager->get_plugin("plugin1"); std::shared_ptr<micro::iplugin<>> plugin2 = manager->get_plugin("bad_plugin1"); if (plugin1) { std::shared_future<std::any> r1, r2, r3, r4; r1 = plugin1->run<0>("test0"); r2 = plugin1->run<2>("sum2", 25, 25); r3 = plugin1->run<1>("method1", std::make_any<std::string>("method1 running ...")); r4 = plugin1->run<0>("lambda0"); r1.wait(); r2.wait(); r3.wait(), r4.wait(); std::clog << "task `plugin1::test0()' returned: " << std::any_cast<std::string>(r1.get()) << std::endl; std::clog << "task `plugin1::sum2(25, 25)' returned: " << std::any_cast<int>(r2.get()) << std::endl; std::clog << "task `plugin1::method1(...)' returned: " << std::any_cast<std::string>(r3.get()) << std::endl; std::clog << "task `plugin1::lambda0()' returned: " << std::any_cast<std::string>(r4.get()) << std::endl; } else { ret = -1; } manager->stop(); } return ret; } // signal handler static void signal_handler(int s) { micro::plugins<>::get()->stop(); std::exit(s); } int main(/*int argc, char* argv[]*/) { std::clog << "MAX_PLUGINS_ARGS: " << MAX_PLUGINS_ARGS << std::endl; std::signal(SIGABRT, &signal_handler); std::signal(SIGTERM, &signal_handler); std::signal(SIGKILL, &signal_handler); std::signal(SIGQUIT, &signal_handler); std::signal(SIGINT, &signal_handler); std::shared_ptr<micro::plugins<>> plugins = micro::plugins<>::get(); // create instance plugins->subscribe<1>("service", service); // service task is optionally // set max idle to 3 minutes - if no one task will not called in that period, // for each loaded plugin - it will be unloaded (0 - unlimited, default - 10) plugins->max_idle(3); plugins->run(); // run thread for manage plugins while (plugins->is_run()) { micro::sleep<micro::milliseconds>(250); } return plugins->error(); } #endif // MICROSERVICE_CXX
31.826667
114
0.63008
dmxvlx
712350123414e9a6632a4ec8d73bf2669626945a
708
hpp
C++
src/core/Game.hpp
cstegel/opengl-fireworks
5acc2e2e937cae632bf2cf8074d209ea22d719c8
[ "MIT" ]
1
2017-10-09T06:56:17.000Z
2017-10-09T06:56:17.000Z
src/core/Game.hpp
cstegel/opengl-fireworks
5acc2e2e937cae632bf2cf8074d209ea22d719c8
[ "MIT" ]
null
null
null
src/core/Game.hpp
cstegel/opengl-fireworks
5acc2e2e937cae632bf2cf8074d209ea22d719c8
[ "MIT" ]
null
null
null
#pragma once #include "graphics/GraphicsManager.hpp" #include "core/InputManager.hpp" #include "game/GameLogic.hpp" #include "audio/AudioManager.hpp" #include "physics/PhysicsManager.hpp" #include "Common.hpp" #include <Ecs.hh> #include <glm/glm.hpp> namespace fw { class Game { public: Game(); ~Game(); int Start(); glm::vec3 GetWorldUp() const; glm::vec3 GetWorldForward() const; static string RootDir(); GraphicsManager graphics; AudioManager audio; GameLogic logic; InputManager input; PhysicsManager physics; ecs::EntityManager entityManager; private: bool frame(); bool shouldStop(); double lastFrameTime; glm::vec3 worldUp; glm::vec3 worldForward; }; }
16.090909
39
0.716102
cstegel
7126919675c0c597ed2c142d3199384f6460458a
8,528
hpp
C++
global/matrix.hpp
thorfdbg/ssim
7d9d1b3c2b8e4338d8cec34088d948025c23e559
[ "Zlib" ]
9
2017-04-13T19:18:03.000Z
2021-01-21T15:29:48.000Z
global/matrix.hpp
thorfdbg/ssim
7d9d1b3c2b8e4338d8cec34088d948025c23e559
[ "Zlib" ]
1
2019-11-25T12:58:01.000Z
2019-12-05T18:15:55.000Z
global/matrix.hpp
thorfdbg/ssim
7d9d1b3c2b8e4338d8cec34088d948025c23e559
[ "Zlib" ]
1
2017-12-31T06:57:00.000Z
2017-12-31T06:57:00.000Z
/************************************************************************************ ** Copyright (C) 2005-2007 TU Berlin, Felix Oum, Thomas Richter ** ** ** ** 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. ** ** ** ** Felix Oum Thomas Richter ** ** thor@math.tu-berlin.de ** ** ** ************************************************************************************/ /* ** $Id: matrix.hpp,v 1.5 2008-03-04 14:12:24 thor Exp $ ** */ #ifndef GLOBAL_MATRIX_HPP #define GLOBAL_MATRIX_HPP /// Includes #include "global/types.hpp" #include "global/matrixbase.hpp" #include "std/string.hpp" #include "std/stdio.hpp" /// /// Type traits for the matrix class template <typename Entry> struct ElementTraits { // Not valid. Create a compiler error if this is // used. }; // // Type trait for all valid entry types we may put // into matrices. template <> struct ElementTraits<DOUBLE> { enum { isValid = true }; }; template <> struct ElementTraits<FLOAT> { enum { isValid = true }; }; template <> struct ElementTraits<ULONG> { enum { isValid = true }; }; template <> struct ElementTraits<LONG> { enum { isValid = true }; }; template <> struct ElementTraits<UWORD> { enum { isValid = true }; }; template <> struct ElementTraits<WORD> { enum { isValid = true }; }; template <> struct ElementTraits<UBYTE> { enum { isValid = true }; }; template <> struct ElementTraits<BYTE> { enum { isValid = true }; }; // We may also keep pointers here. template <typename T> struct ElementTraits<T *> { enum { isValid = true }; }; /// /// templated Matrix class template <typename Entry> class Matrix : public MatrixBase { // // The type buffer goes here: This is the origin of the // matrix array. Entry *m_pEntries; // public: // // Default constructor, do not allocate any memory. Matrix(void) : MatrixBase() { assert(ElementTraits<Entry>::isValid); } // // Destructor: Also cleans up the memory allocated here. ~Matrix(void) { // ...but in matrixbase. } // // Allocator for a matrix with given dimensions. Matrix(ULONG w,ULONG h) : MatrixBase(w * h * sizeof(Entry)) { assert(ElementTraits<Entry>::isValid); m_pEntries = static_cast<Entry *>(m_pMemory->m_pMem); m_ulWidth = w; m_ulHeight = h; m_ulEntriesPerRow = w; } // // Allocate a matrix that has been empty before. void Allocate(ULONG width,ULONG height) { assert(m_pMemory == NULL); // // First get the memory MatrixBase::Allocate(width * height * sizeof(Entry)); m_pEntries = static_cast<Entry *>(m_pMemory->m_pMem); m_ulWidth = width; m_ulHeight = height; m_ulEntriesPerRow = width; } // // Release the memory of a matrix explicitly. void Dispose(void) { MatrixBase::Release(); m_pEntries = NULL; } // // Copy a matrix over. The two matrices will afterwards use // the same memory. Use DuplicateFrom for a deep copy. Matrix(const Matrix<Entry> &o) : MatrixBase(o), m_pEntries(o.m_pEntries) { assert(ElementTraits<Entry>::isValid); } // // Assign this matrix to the second matrix. The two matrices // will use the same matrix coefficients afterwards. Matrix<Entry> &operator=(const Matrix<Entry> &o) { // First assign the base MatrixBase::operator=(o); // Then the element pointer. m_pEntries = o.m_pEntries; // return *this; } // // Build a new matrix out of a larger matrix by sharing a // coefficient window between the two. // x and y is the anchor position of the new matrix within the // old, w and h the dimension of the new matrix. Matrix(Matrix<Entry> &o,ULONG x,ULONG y,ULONG w,ULONG h) : MatrixBase(o) { assert(ElementTraits<Entry>::isValid); assert(x + w <= o.m_ulWidth); assert(y + h <= o.m_ulHeight); // // Now assign the matrix contents. m_pEntries = &o.At(x,y); m_ulEntriesPerRow = o.m_ulEntriesPerRow; m_ulWidth = w; m_ulHeight = h; } // // Assign this matrix to a sub-window of an existing // matrix, then sharing the memory between the two. void Extract(Matrix<Entry> &o,ULONG x,ULONG y,ULONG w,ULONG h) { assert(x + w <= o.m_ulWidth); assert(y + h <= o.m_ulHeight); // MatrixBase::operator=(o); m_pEntries = &o.At(x,y); m_ulEntriesPerRow = o.m_ulEntriesPerRow; m_ulWidth = w; m_ulHeight = h; } // // Get: Extract an element from the matrix Entry Get(ULONG x,ULONG y) const { assert(m_pEntries); assert(x < m_ulWidth && y < m_ulHeight); return m_pEntries[x+y*m_ulEntriesPerRow]; } // const Entry *Origin(void) const { return m_pEntries; } // // The same as a const lvalue: const Entry &At(ULONG x,ULONG y) const { assert(m_pEntries); assert(x < m_ulWidth && y < m_ulHeight); return m_pEntries[x+y*m_ulEntriesPerRow]; } // // The same as a non-const lvalue Entry &At(ULONG x,ULONG y) { assert(m_pEntries); assert(x < m_ulWidth && y < m_ulHeight); return m_pEntries[x+y*m_ulEntriesPerRow]; } // // Put: Place an element into the matrix. void Put(ULONG x,ULONG y,Entry v) { assert(m_pEntries); assert(x < m_ulWidth && y < m_ulHeight); m_pEntries[x+y*m_ulEntriesPerRow] = v; } // // The same again, for the purists that like to call this // "set" instead of "put". void Set(ULONG x,ULONG y,Entry v) { assert(m_pEntries); assert(x < m_ulWidth && y < m_ulHeight); m_pEntries[x+y*m_ulEntriesPerRow] = v; } // // Make a one-to-one copy from the original, creating // two indpendent copies, i.e. make a "deep copy". The // old contents is lost. This only works for PODs. void DuplicateFrom(const Matrix<Entry> &o) { Allocate(o.m_ulWidth * o.m_ulHeight * sizeof(Entry)); // m_ulWidth = o.m_ulWidth; m_ulHeight = o.m_ulHeight; m_ulEntriesPerRow = o.m_ulWidth; m_pEntries = static_cast<Entry *>(m_pMemory->m_pMem); if (o.m_ulWidth == o.m_ulEntriesPerRow) { memcpy(m_pEntries,o.m_pEntries, o.m_ulEntriesPerRow * o.m_ulHeight * sizeof(Entry)); } else { const Entry *src = o.m_pEntries; Entry *dst = m_pEntries; ULONG h = m_ulHeight; ULONG w = sizeof(Entry) * m_ulWidth; // while(h) { memcpy(dst,src,w); src += o.m_ulEntriesPerRow; dst += m_ulEntriesPerRow; h--; } } } // // Clean the contents of this matrix completely. // Warning! This works only well for PODs. void CleanMatrix(void) { if (m_pEntries) { // Quick method: Matrix is continous if (m_ulEntriesPerRow == m_ulWidth) { memset(m_pEntries,0,m_ulWidth * m_ulHeight * sizeof(Entry)); } else { Entry *row = m_pEntries; ULONG h = m_ulHeight; ULONG w = m_ulWidth * sizeof(Entry); while(h) { memset(row,0,w); row += m_ulEntriesPerRow; h--; } } } } }; /// /// #endif
30.134276
86
0.57493
thorfdbg
71273727389b20c5b0dce353fe6b1beafe9bb1c7
436
cpp
C++
Hallowen.cpp
OrlykM/Algotester
6d0702b191610795beb959d378ab1feef6191b68
[ "CC0-1.0" ]
null
null
null
Hallowen.cpp
OrlykM/Algotester
6d0702b191610795beb959d378ab1feef6191b68
[ "CC0-1.0" ]
null
null
null
Hallowen.cpp
OrlykM/Algotester
6d0702b191610795beb959d378ab1feef6191b68
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; int main() { int n; int k = 0; cin >> n; if (n >= 1 && n <= 100) { for (int i = 0; i < n; i++) { int j; cin >> j; if (j >= 1 && j <= 100) { if (j <= 2) { k++; } else if(j >= 3 && j <= 7) { k += 2; } else if(j >= 8 && j <= 47) { k += 3; } else if(j >= 48) { k += 4; } } } cout << k; return 0; } }
11.473684
30
0.321101
OrlykM
71292e82dbe5711bf4bad6b22bda2db965c51bb8
2,721
cc
C++
example/unicode.cc
ColinH/PEGTL-0.32
b8b2d4cbc0568936709775b9fc83a2eb34bdc0c3
[ "MIT" ]
1
2015-02-13T02:03:29.000Z
2015-02-13T02:03:29.000Z
example/unicode.cc
ColinH/PEGTL-0.32
b8b2d4cbc0568936709775b9fc83a2eb34bdc0c3
[ "MIT" ]
null
null
null
example/unicode.cc
ColinH/PEGTL-0.32
b8b2d4cbc0568936709775b9fc83a2eb34bdc0c3
[ "MIT" ]
1
2020-04-25T16:40:49.000Z
2020-04-25T16:40:49.000Z
// Copyright (c) 2008 Dr. Colin Hirsch // Please see license.txt for license. // Include the only public header file for the PEGTL. #include <pegtl.hh> namespace example { using namespace pegtl; // This example defines a rule for quoted strings with C-style backslash-escapes // that is compatible with UTF-8 input, i.e. the quoted string can contain UTF-8 // without ever truncating a multi-byte character. // The rule 'escaped' matches a backslash-escaped character; the use of ifmust<> // ensures that the backslash is followed by one of the appropriate characters. struct escaped : ifmust< one< '\\' >, one< '\\', '"', '\'', 'a', 'f', 'n', 'r', 't', 'v' > > {}; // A regular character is anything that is not an ASCII control character. This // also matches any byte of a unicode point-code with multi-byte encoding in UTF-8. struct regular : not_range< 0, 31 > {}; // This is simple, a character in the quoted string is either an escaped character // or a regular character. Note that the order of the two rules is important; with // sor< regular, escaped >, a backslash would always match rule 'regular', and rule // 'escaped' would never fire, so backslash would loose its special meaning (which, // regarding the grammar, is (a) that a subsequent " does not terminate the quoted // string, and (b) that it must be followed by one of a limited set of characters). struct character : sor< escaped, regular > {}; // A quoted string starts with a quote, and then contains characters until another // quote is encountered. Escaped quotes can be embedded, they will be matched by // rule 'escaped'. A seq<> could be used instead of the ifmust<>, however usually // a grammar will have only one rule that will match something starting with a quote, // and in this case the ifmust<> will produce a better error message (because an // input that starts with a quote, but does not continue with the string contents and // the corresponding closing quote, will produce an error in rule 'quoted', rather // than wherever any sor<> backtracking in the grammar might lead to). struct quoted : ifmust< one< '"' >, until< one< '"' >, character > > {}; // Note that rule 'quoted' will work fine with UTF-8 in the sense that the quoted // string can contain any UTF-8 character, however no validation of multi-byte // encoded poing-codes is performed, the data is simply passed through. (Full // support for UTF-8 will be included eventually.) } // example int main( int argc, char ** argv ) { for ( int i = 1; i < argc; ++i ) { pegtl::basic_parse_string< example::quoted >( argv[ i ] ); } return 0; }
42.515625
88
0.689085
ColinH
713a86b5355b6558b4897d56ebf95155705376c9
1,506
cpp
C++
test/client.cpp
adanselm/pbRPCpp
55ee89608bfd3d8e32d3880fd5f1f7c3386f167a
[ "BSL-1.0" ]
26
2015-03-31T05:57:21.000Z
2021-12-07T04:37:05.000Z
test/client.cpp
adanselm/pbRPCpp
55ee89608bfd3d8e32d3880fd5f1f7c3386f167a
[ "BSL-1.0" ]
2
2016-11-23T19:44:08.000Z
2019-05-29T08:37:03.000Z
test/client.cpp
adanselm/pbRPCpp
55ee89608bfd3d8e32d3880fd5f1f7c3386f167a
[ "BSL-1.0" ]
10
2015-07-19T13:02:14.000Z
2020-05-26T12:17:09.000Z
/** * Copyright Springbeats Sarl 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file ../LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ //#include "TcpRpcChannel.hpp" #include "RpcController.hpp" //#include "TcpRpcServer.hpp" //#include "UdpRpcChannel.hpp" #include "ShmRpcChannel.hpp" //#include "UdpRpcServer.hpp" //#include "EchoTestServer.hpp" #include "EchoTestClient.hpp" #include <boost/shared_ptr.hpp> #include <iostream> /* * */ int main(int argc, char** argv) { if(argc < 3) { std::cerr << "Usage: " << argv[0] << " PORT MSG_SIZE" << std::endl; return 1; } pbrpcpp::RpcController controller; const std::string addr("localhost"); const std::string port(argv[1]); int msg_size = 0; std::istringstream iss(argv[2]); iss >> msg_size; std::string bigData(msg_size, 'z'); // const std::string message(argv[2]); // std::cout << "targeting " << addr << ":" << port << " with msg: " << message << std::endl; shared_ptr<pbrpcpp::ShmRpcChannel> channel( new pbrpcpp::ShmRpcChannel( addr ) ); EchoTestClient client( channel ); echo::EchoRequest request; echo::EchoResponse response; request.set_message(bigData); client.echo( &controller, &request,&response, NULL, 1 ); if( controller.Failed() ) { std::cerr << "Failed." << std::endl; return 1; } std::cout << "Received: " << response.response().size() << " bytes" << std::endl; return 0; }
26.421053
94
0.641434
adanselm
7141b83a2b5eb78f1e48c55fc710376df72a6ee8
674
cpp
C++
tests/fuzzing/direct.cpp
graves501/arma3-unix-launcher
7f034833389af122da7a3948cf869124827216ba
[ "MIT" ]
161
2016-11-22T09:36:00.000Z
2022-03-25T06:14:51.000Z
tests/fuzzing/direct.cpp
graves501/arma3-unix-launcher
7f034833389af122da7a3948cf869124827216ba
[ "MIT" ]
138
2017-01-28T16:46:37.000Z
2022-03-30T05:36:53.000Z
tests/fuzzing/direct.cpp
graves501/arma3-unix-launcher
7f034833389af122da7a3948cf869124827216ba
[ "MIT" ]
36
2016-12-28T12:23:48.000Z
2022-03-31T22:17:32.000Z
#include <filesystem> #include <fstream> #include <string> #include <fmt/format.h> std::string FileReadAllText(std::filesystem::path const &path) { std::ifstream file(path); std::stringstream str; str << file.rdbuf(); return str.str(); } extern "C" int LLVMFuzzerTestOneInput(uint8_t const *data, size_t size); int main(int argc, char **argv) { if (argc != 2) { fmt::print("usage: {} INPUT_FILE\n", argv[0]); return 2; } auto file = FileReadAllText(argv[1]); uint8_t const *data = reinterpret_cast<uint8_t const *>(file.c_str()); size_t size = file.size(); LLVMFuzzerTestOneInput(data, size); return 0; }
21.741935
74
0.639466
graves501
71451e6f29660f350443856e18d9d76536d5659a
1,850
cpp
C++
src/render/frame_buffer.cpp
Tuebel/scigl_render
ec790d54ca4a14546348a5dd2f799d5abcc4bd36
[ "MIT" ]
null
null
null
src/render/frame_buffer.cpp
Tuebel/scigl_render
ec790d54ca4a14546348a5dd2f799d5abcc4bd36
[ "MIT" ]
null
null
null
src/render/frame_buffer.cpp
Tuebel/scigl_render
ec790d54ca4a14546348a5dd2f799d5abcc4bd36
[ "MIT" ]
null
null
null
#include <scigl_render/render/frame_buffer.hpp> #include <iostream> #include <stdexcept> namespace scigl_render { FrameBuffer::FrameBuffer(int width, int height, GLenum internal_format) { this->width = width; this->height = height; // Create framebuffer with renderbuffer attachements glGenFramebuffers(1, &fbo); activate(); glGenRenderbuffers(1, &color_rbo); glBindRenderbuffer(GL_RENDERBUFFER, color_rbo); glRenderbufferStorage(GL_RENDERBUFFER, internal_format, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, color_rbo); glGenRenderbuffers(1, &depth_stencil_rbo); glBindRenderbuffer(GL_RENDERBUFFER, depth_stencil_rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depth_stencil_rbo); // Check framebuffer, will check rbo, too, since it is attached if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { throw std::runtime_error("Framebuffer is not completed"); } deactivate(); } FrameBuffer::~FrameBuffer() { std::cout << "destroyed fbo\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); glDeleteRenderbuffers(1, &depth_stencil_rbo); glDeleteRenderbuffers(1, &color_rbo); } void FrameBuffer::activate() { glBindFramebuffer(GL_FRAMEBUFFER, fbo); } void FrameBuffer::deactivate() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void FrameBuffer::clear(float color, float depth, int stencil) { activate(); glClearColor(color, color, color, 1); glClearDepth(depth); glClearStencil(stencil); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); deactivate(); } } // namespace scigl_render
30.833333
77
0.757297
Tuebel
7145c53aec322c29c1822bf7d66f8ef651378e37
642
hpp
C++
converter/src/mapConverter/mapConverter.hpp
redthing1/Tiled2GBA
2272309292c6a2a0dee2a4e7cc81c2e97fab6157
[ "MIT" ]
14
2018-06-25T09:22:21.000Z
2021-12-11T20:06:25.000Z
converter/src/mapConverter/mapConverter.hpp
redthing1/Tiled2GBA
2272309292c6a2a0dee2a4e7cc81c2e97fab6157
[ "MIT" ]
20
2018-06-23T21:36:35.000Z
2021-05-25T16:21:14.000Z
converter/src/mapConverter/mapConverter.hpp
redthing1/Tiled2GBA
2272309292c6a2a0dee2a4e7cc81c2e97fab6157
[ "MIT" ]
2
2020-02-26T13:51:31.000Z
2021-09-30T07:02:33.000Z
#ifndef MAP_CONVERTER_H #define MAP_CONVERTER_H #include "../lib/tmxlite/Map.hpp" #include "../gba/gbaMap/gbaMap.hpp" #include "../lib/tmxlite/TileLayer.hpp" using namespace std; /** * Converts a TMX Map to a GBA Map. */ class MapConverter { public: /** * Convert a TMX Map. * @param tmxMap The TMX Map. * @return The GBA Map. */ GBAMap convert(const string &name, const tmx::Map &tmxMap); private: vector<const tmx::TileLayer*> getTileLayers(const vector<tmx::Layer::Ptr> &layers); vector<const tmx::ObjectGroup*> getObjectLayers(const vector<tmx::Layer::Ptr> &layers); }; #endif // MAP_CONVERTER_H
23.777778
91
0.679128
redthing1
7149a2e8b478439251df700081c674d7e70a4893
21,244
cpp
C++
src/nes6502.cpp
karangovil/nes6502
4abef3c303cbcc37870c72bcaf57c29d0b8fea21
[ "MIT" ]
null
null
null
src/nes6502.cpp
karangovil/nes6502
4abef3c303cbcc37870c72bcaf57c29d0b8fea21
[ "MIT" ]
null
null
null
src/nes6502.cpp
karangovil/nes6502
4abef3c303cbcc37870c72bcaf57c29d0b8fea21
[ "MIT" ]
null
null
null
#include "nes6502.h" #include "Bus.h" #include "utils.h" nes6502::nes6502() = default; nes6502::~nes6502() = default; uint8_t nes6502::read(uint16_t addr) { return bus->cpuRead(addr, false); } void nes6502::write(uint16_t addr, uint8_t data) { bus->cpuWrite(addr, data); } void nes6502::clock() { if (cycles == 0) { opcode = read(pc); pc++; // Get starting number of cycles cycles = lookup[opcode].cycles; uint8_t additional_cycle1 = (this->*lookup[opcode].addrmode)(); uint8_t additional_cycle2 = (this->*lookup[opcode].operate)(); cycles += (additional_cycle1 & additional_cycle2); } cycles--; } // Forces the CPU into a known state. // Registers are set to 0x00, status register is cleared // except for unused bit. An absolute address is read from // location 0xFFFC which contains a second address that the // program counter is set to. This is known to the programmer void nes6502::reset() { addr_abs = 0xFFFC; uint16_t lo = read(addr_abs + 0); uint16_t hi = read(addr_abs + 1); pc = (hi << 8) | lo; a = 0; x = 0; y = 0; stkp = 0xFD; status = 0x00 | U; addr_rel = 0x0000; addr_abs = 0x0000; fetched = 0x00; cycles = 8; } // Interrupt reqs only happen if the "disable interrupt" // flag is 0. IRQs can be happen anytime but the current // instr is allowed to finish and then the current pc and // status register is stored on stack. When the routine that // services the interrupt is finished, status register and pc // can be restored (RTI instr). Once IRQ is finished, a // programmable addr is read from a hard coded location, 0x00FE void nes6502::irq() { if (GetFlag(I) == 0) { write(0x0100 + stkp, (pc << 8) & 0x00FF); stkp--; write(0x0100 + stkp, pc & 0x00FF); stkp--; SetFlag(B, 0); SetFlag(U, 1); SetFlag(I, 1); write(0x0100 + stkp, status); stkp--; addr_abs = 0xFFFE; uint16_t lo = read(addr_abs + 0); uint16_t hi = read(addr_abs + 1); pc = (hi << 8) | lo; cycles = 7; } } // A non maskable interrupt cannot be ignored. // Same as irq except reads the new pc from 0xFFFA void nes6502::nmi() { write(0x0100 + stkp, (pc << 8) & 0x00FF); stkp--; write(0x0100 + stkp, pc & 0x00FF); stkp--; SetFlag(B, 0); SetFlag(U, 1); SetFlag(I, 1); write(0x0100 + stkp, status); stkp--; addr_abs = 0xFFFE; uint16_t lo = read(addr_abs + 0); uint16_t hi = read(addr_abs + 1); pc = (hi << 8) | lo; cycles = 8; } // Flag functions // Get the value of the given flag uint8_t nes6502::GetFlag(FLAGS6502 f) { return ((status & f) > 0) ? 1 : 0; } // Set or clear thje value of the given flag void nes6502::SetFlag(FLAGS6502 f, bool v) { if (v) status |= f; else status &= ~f; } // Addressing Modes // Implied: There is no additional data required for this instr // The instr does something very simple let sets a status bit // We will target the accumulator, for instrs like PHA uint8_t nes6502::IMP() { fetched = a; return 0; } // Immediate: The instr expects the next byte to be used as a // value, so we'll prep the read addr to point to next byte uint8_t nes6502::IMM() { addr_abs = pc++; return 0; } // Zero page: To save program bytes, zero page addressing // allows to absolutely address a location in the first 0xFF // bytes of addr range which only requires one byte instead // of the usual two. uint8_t nes6502::ZP0() { addr_abs = read(pc); pc++; addr_abs &= 0x00FF;// extract LO 8 bytes of the addr return 0; } // Zero page with X offset: Similar to ZP0 but contents of X // register are added to the supplied single byte addr. Useful // for iterating through range within first page uint8_t nes6502::ZPX() { addr_abs = (read(pc) + x); pc++; addr_abs &= 0x00FF; return 0; } // Zero page with Y offset uint8_t nes6502::ZPY() { addr_abs = (read(pc) + y); pc++; addr_abs &= 0x00FF; return 0; } // Relative: Exclusive to branch instrs. The addr must // reside within -128 to 127 of the branch instr i.e. // cannot directly branch of any addr in the addressable range uint8_t nes6502::REL() { addr_rel = read(pc); pc++; if (addr_rel & 0x80) addr_rel |= 0xFF00; return 0; } // Absolute: Full 16 bit addr is loaded and used uint8_t nes6502::ABS() { uint16_t lo = read(pc); pc++; uint16_t hi = read(pc); pc++; addr_abs = (hi << 8) | lo; return 0; } // Absolute with X Offset: Same as absolute but X register // is added to the supplied 2 byte addr. If the resulting addr // changes the page, addition cycle is needed uint8_t nes6502::ABX() { uint16_t lo = read(pc); pc++; uint16_t hi = read(pc); pc++; addr_abs = (hi << 8) | lo; addr_abs += x; // check if the HI byte has changed after adding X if ((addr_abs & 0xFF00) != (hi << 8)) return 1; else return 0; } // Absolute with Y Offset uint8_t nes6502::ABY() { uint16_t lo = read(pc); pc++; uint16_t hi = read(pc); pc++; addr_abs = (hi << 8) | lo; addr_abs += y; if ((addr_abs & 0xFF00) != (hi << 8)) return 1; else return 0; } // Indirect: The supplied 16-bit addr is read to get the // actual 16-bit addr. Bug: If the LO byte of the supplied // addr is 0xFF, then to read the HI byte of the actual addr // we need to cross a page bdry. This doesn't actually work // on the chip as designed, instead it wraps back around in // the same page, yielding in invalid actual addr uint8_t nes6502::IND() { uint16_t ptr_lo = read(pc); pc++; uint16_t ptr_hi = read(pc); pc++; uint16_t ptr = (ptr_hi << 8) | ptr_lo; if (ptr_lo == 0x00FF)// Simulate page boundary hardware bug { addr_abs = (read(ptr & 0xFF00) << 8) | read(ptr + 0); } else// behave normally { addr_abs = (read(ptr + 1) << 8) | read(ptr + 0); } return 0; } // Indirect X: Supplied 8 bit addr is offset by X register // to a location in page 0x00. The actual 16 bit addr is read // from this location uint8_t nes6502::IZX() { uint16_t t = read(pc); pc++; uint16_t lo = read((uint16_t)(t + (uint16_t)x) & 0x00FF); uint16_t hi = read((uint16_t)(t + (uint16_t)x + 1) & 0x00FF); addr_abs = (hi << 8) | lo; return 0; } // Indirect Y: Supplied 8 bit addr indexes a location in page 0x00 // From here, the actual 16 bit addr is read, and the contents of Y // register is added to offset it. If the offset causes a change in // page, then an additional clock cycle is needed uint8_t nes6502::IZY() { uint16_t t = read(pc); pc++; uint16_t lo = read(t & 0x00FF); uint16_t hi = read((t + 1) & 0x00FF); addr_abs = (hi << 8) | lo; addr_abs += y; if ((addr_abs & 0xFF00) != (hi << 8)) return 1; else return 0; } // Instructions // Function to source the data required by the instr uint8_t nes6502::fetch() { if (!(lookup[opcode].addrmode == &nes6502::IMP)) fetched = read(addr_abs); return fetched; } // Add with carry in uint8_t nes6502::ADC() { fetch(); // add in 16 bit to capture any carry bit which // will exist in bit 8 of 16 bit word temp = (uint16_t)a + (uint16_t)fetched + (uint16_t)GetFlag(C); // carry flag out exists in the HI bit 0 SetFlag(C, temp > 255); SetFlag(Z, (temp & 0x00FF) == 0x0000); // set the signed overflow flag SetFlag(V, (~((uint16_t)a ^ (uint16_t)fetched) & ((uint16_t)a ^ (uint16_t)temp)) & 0x0080); SetFlag(N, temp & 0x80); // load the result into accumulator (8-bit) a = temp & 0x00FF; return 1; } uint8_t nes6502::SBC() { fetch(); uint16_t value = ((uint16_t)fetched) ^ 0x00FF; temp = (uint16_t)a + value + (uint16_t)GetFlag(C); SetFlag(C, temp < 255); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(V, (temp ^ (uint16_t)a) & (temp ^ value) & 0x0080); SetFlag(N, temp & 0x80); a = temp & 0x00FF; return 1; } // Typical order of events for most instrs // 1. Fetch the data // 2. Perform computation // 3. Store the results in appropriate places // 4. Set flags of the status register // 5. Return if the instr has potential to require // additional clock cycle // Bitwise logic AND // Flags out: N, Z uint8_t nes6502::AND() { fetch(); a = a & fetched; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); return 1; } // Bitwise logic XOR // Flags out: N, Z uint8_t nes6502::EOR() { fetch(); a = a ^ fetched; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); return 1; } // Bitwise logic OR // Flags out: N, Z uint8_t nes6502::ORA() { fetch(); a = a | fetched; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); return 1; } // Test bits in memory with accumulator uint8_t nes6502::BIT() { fetch(); temp = a & fetched; SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, fetched & (1 << 7)); SetFlag(V, fetched & (1 << 6)); return 0; } // Branch if Carry set uint8_t nes6502::BCS() { if (GetFlag(C) == 1) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Carry clear uint8_t nes6502::BCC() { if (GetFlag(C) == 0) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Equal uint8_t nes6502::BEQ() { if (GetFlag(Z) == 1) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Not Equal uint8_t nes6502::BNE() { if (GetFlag(Z) == 0) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Negative uint8_t nes6502::BMI() { if (GetFlag(N) == 1) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Positive uint8_t nes6502::BPL() { if (GetFlag(N) == 0) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Overflow Clear uint8_t nes6502::BVC() { if (GetFlag(V) == 0) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Branch if Overflow Set uint8_t nes6502::BVS() { if (GetFlag(V) == 1) { cycles++; addr_abs = pc + addr_rel; if ((addr_abs & 0xFF00) != (pc & 0xFF00)) cycles++; pc = addr_abs; } return 0; } // Program sourced interrupts uint8_t nes6502::BRK() { pc++; SetFlag(I, 1); write(0x0100 + stkp, (pc >> 8) & 0x00FF); stkp--; write(0x0100 + stkp, pc & 0x00FF); SetFlag(B, 1); write(0x0100 + stkp, status); stkp--; SetFlag(B, 0); pc = (uint16_t)read(0xFFFE) | ((uint16_t)read(0xFFFF) << 8); return 0; } // Clear Carry flag uint8_t nes6502::CLC() { SetFlag(C, false); return 0; } // Clear Decimal flag uint8_t nes6502::CLD() { SetFlag(D, false); return 0; } // Disable Interrupts / Clear Interrupts flag uint8_t nes6502::CLI() { SetFlag(I, false); return 0; } // Clear Overflow flag uint8_t nes6502::CLV() { SetFlag(V, false); return 0; } // Compare Accumulator // Flags out: N, C, Z uint8_t nes6502::CMP() { fetch(); temp = (uint16_t)a - (uint16_t)fetched; SetFlag(C, a >= fetched); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); return 0; } // Compare X register // Flags out: N, C, Z uint8_t nes6502::CPX() { fetch(); temp = (uint16_t)x - (uint16_t)fetched; SetFlag(C, x >= fetched); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); return 0; } // Compare Y register // Flags out: N, C, Z uint8_t nes6502::CPY() { fetch(); temp = (uint16_t)y - (uint16_t)fetched; SetFlag(C, y >= fetched); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); return 0; } // Decrement value at memory location // Flags out: N, Z uint8_t nes6502::DEC() { fetch(); temp = fetched - 1; write(addr_abs, temp & 0x00FF); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); return 0; } // Decrement X register // Flags out: N, Z uint8_t nes6502::DEX() { x--; SetFlag(Z, x == 0x00); SetFlag(N, temp & 0x80); return 0; } // Decrement Y register // Flags out: N, Z uint8_t nes6502::DEY() { y--; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); return 0; } // Increment value at memory location // Flags out: N, Z uint8_t nes6502::INC() { fetch(); temp = fetched + 1; write(addr_abs, temp & 0x00FF); SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); return 0; } // Increment X register // Flags out: N, Z uint8_t nes6502::INX() { x++; SetFlag(Z, x == 0x00); SetFlag(N, temp & 0x80); return 0; } // Increment Y register // Flags out: N, Z uint8_t nes6502::INY() { y++; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); return 0; } // Jump to location uint8_t nes6502::JMP() { pc = addr_abs; return 0; } // Jump to Sub-Routine // Push current pc to stack, pc = addr uint8_t nes6502::JSR() { pc--; write(0x0100 + stkp, (pc >> 8) & 0x00FF); stkp--; write(0x0100 + stkp, pc & 0x00FF); stkp--; pc = addr_abs; return 0; } // Load the accumulator // Flags out: N, Z uint8_t nes6502::LDA() { fetch(); a = fetched; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); return 1; } // Load the X register // Flags out: N, Z uint8_t nes6502::LDX() { fetch(); x = fetched; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); return 1; } // Load the Y register // Flags out: N, Z uint8_t nes6502::LDY() { fetch(); y = fetched; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); return 1; } // Shift left one bit // shift one bt right (memory or accumulator) uint8_t nes6502::ASL() { fetch(); temp = (uint16_t)fetched << 1; SetFlag(C, (temp & 0xFF00) > 0); SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, temp & 0x80); if (lookup[opcode].addrmode == &nes6502::IMP) a = temp & 0x00FF; else write(addr_abs, temp & 0x00FF); return 0; } // Logical Shift right // shift one bt right (memory or accumulator) uint8_t nes6502::LSR() { fetch(); SetFlag(C, fetched & 0x0001); temp = fetched >> 1; SetFlag(Z, (temp & 0x00FF) == 0x0000); SetFlag(N, temp & 0x0080); if (lookup[opcode].addrmode == &nes6502::IMP) a = temp & 0x00FF; else write(addr_abs, temp & 0x00FF); return 0; } uint8_t nes6502::NOP() { switch (opcode) { case 0x1C: case 0x3C: case 0x5C: case 0x7C: case 0xDC: case 0xFC: return 1; break; } return 0; } // Push accumulator to stack // Note that addr 0x0100 is hard coded in 6502 // as the base location for the stack pointer // stkp is an offset to that base location uint8_t nes6502::PHA() { write(0x0100 + stkp, a); stkp--; return 0; } // Push status register to stack // Break flag is set to 1 before push uint8_t nes6502::PHP() { write(0x0100 + stkp, status | B | U); SetFlag(B, 0); SetFlag(U, 0); stkp--; return 0; } // Pop accumulator off the stack // Flags set: N, Z uint8_t nes6502::PLA() { stkp++; a = read(0x0100 + stkp); SetFlag(Z, a = 0x00); SetFlag(N, a & 0x80); return 0; } // Pop status register off the stack uint8_t nes6502::PLP() { stkp++; status = read(0x0100 + stkp); SetFlag(U, 1); return 0; } // Rotate one bit left (memory or accumulator) uint8_t nes6502::ROL() { fetch(); temp = (uint16_t)(fetched << 1) | GetFlag(C); SetFlag(C, temp & 0x01); SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, temp & 0x0080); if (lookup[opcode].addrmode == &nes6502::IMP) a = temp & 0x00FF; else write(addr_abs, temp & 0x00FF); return 0; } // Rotate one bit right (memory or accumulator) uint8_t nes6502::ROR() { fetch(); temp = (uint16_t)(GetFlag(C) << 7) | (fetched << 1); SetFlag(C, fetched & 0x01); SetFlag(Z, (temp & 0x00FF) == 0x00); SetFlag(N, temp & 0x0080); if (lookup[opcode].addrmode == &nes6502::IMP) a = temp & 0x00FF; else write(addr_abs, temp & 0x00FF); return 0; } // Return from interrupt uint8_t nes6502::RTI() { stkp++; status = read(0x0100 + stkp); status &= ~B; status &= ~U; stkp++; pc = (uint16_t)read(0x0100 + stkp); stkp++; pc |= (uint16_t)read(0x0100 + stkp) << 8; return 0; } uint8_t nes6502::RTS() { stkp++; pc = (uint16_t)read(0x0100 + stkp); stkp++; pc |= (uint16_t)read(0x0100 + stkp) << 8; pc++; return 0; } // Set Carry flag uint8_t nes6502::SEC() { SetFlag(C, true); return 0; } // Set Decimal flag uint8_t nes6502::SED() { SetFlag(D, true); return 0; } // Set Interrupt flag / Enable interrupts uint8_t nes6502::SEI() { SetFlag(I, true); return 0; } // Store Accumulator at addr uint8_t nes6502::STA() { write(addr_abs, a); return 0; } // Store X register at addr uint8_t nes6502::STX() { write(addr_abs, x); return 0; } // Store Y register at addr uint8_t nes6502::STY() { write(addr_abs, y); return 0; } // Transfer Accumulator to X register // Flags out: N, Z uint8_t nes6502::TAX() { x = a; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); return 0; } // Transfer Accumulator to Y register // Flags out: N, Z uint8_t nes6502::TAY() { y = a; SetFlag(Z, y == 0x00); SetFlag(N, y & 0x80); return 0; } // Transfer X register to Accumulator // Flags out: N, Z uint8_t nes6502::TXA() { a = x; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); return 0; } // Transfer Y register to Accumulator // Flags out: N, Z uint8_t nes6502::TYA() { a = y; SetFlag(Z, a == 0x00); SetFlag(N, a & 0x80); return 0; } // Transfer X register to Stack pointer uint8_t nes6502::TXS() { stkp = x; return 0; } // Transfer Stack register to X register // Flags out: N, Z uint8_t nes6502::TSX() { x = stkp; SetFlag(Z, x == 0x00); SetFlag(N, x & 0x80); return 0; } // Capture illegal opcodes uint8_t nes6502::XXX() { return 0; } // Helper functions bool nes6502::complete() { return cycles == 0; } std::map<uint16_t, std::string> nes6502::disassemble(uint16_t nStart, uint16_t nStop) { uint32_t addr = nStart; uint8_t value = 0x00; uint8_t lo = 0x00; uint8_t hi = 0x00; std::map<uint16_t, std::string> mapLines; uint16_t line_addr = 0; while (addr <= (uint32_t)nStop) { line_addr = addr; // Prefix line with instr addr std::string sInst = "$" + hex(addr, 4) + ": "; // read instr and get its readable name uint8_t opcode = bus->cpuRead(addr, true); addr++; sInst += lookup[opcode].name + " "; // get operands from desired locations, and form the // instr based upon its addressing mode. These routines // mimmick the actual fetch routine of the 6502 in // order to get accurate data as part of the instr if (lookup[opcode].addrmode == &nes6502::IMP) { sInst += " {IMP}"; } else if (lookup[opcode].addrmode == &nes6502::IMM) { value = bus->cpuRead(addr, true); addr++; sInst += "#$" + hex(value, 2) + " {IMM}"; } else if (lookup[opcode].addrmode == &nes6502::ZP0) { lo = bus->cpuRead(addr, true); addr++; hi = 0x00; sInst += "$" + hex(lo, 2) + " {ZP0}"; } else if (lookup[opcode].addrmode == &nes6502::ZPX) { lo = bus->cpuRead(addr, true); addr++; hi = 0x00; sInst += "$" + hex(lo, 2) + ", X {ZPX}"; } else if (lookup[opcode].addrmode == &nes6502::ZPY) { lo = bus->cpuRead(addr, true); addr++; hi = 0x00; sInst += "$" + hex(lo, 2) + ", Y {ZPY}"; } else if (lookup[opcode].addrmode == &nes6502::IZX) { lo = bus->cpuRead(addr, true); addr++; hi = 0x00; sInst += "($" + hex(lo, 2) + ", X) {IZX}"; } else if (lookup[opcode].addrmode == &nes6502::IZY) { lo = bus->cpuRead(addr, true); addr++; hi = 0x00; sInst += "($" + hex(lo, 2) + ", Y) {IZY}"; } else if (lookup[opcode].addrmode == &nes6502::ABS) { lo = bus->cpuRead(addr, true); addr++; hi = bus->cpuRead(addr, true); addr++; sInst += "$" + hex((uint16_t)(hi << 8) | lo, 4) + " {ABS}"; } else if (lookup[opcode].addrmode == &nes6502::ABX) { lo = bus->cpuRead(addr, true); addr++; hi = bus->cpuRead(addr, true); addr++; sInst += "$" + hex((uint16_t)(hi << 8) | lo, 4) + ", X {ABX}"; } else if (lookup[opcode].addrmode == &nes6502::ABY) { lo = bus->cpuRead(addr, true); addr++; hi = bus->cpuRead(addr, true); addr++; sInst += "$" + hex((uint16_t)(hi << 8) | lo, 4) + ", Y {ABY}"; } else if (lookup[opcode].addrmode == &nes6502::IND) { lo = bus->cpuRead(addr, true); addr++; hi = bus->cpuRead(addr, true); addr++; sInst += "($" + hex((uint16_t)(hi << 8) | lo, 4) + ") {IND}"; } else if (lookup[opcode].addrmode == &nes6502::REL) { value = bus->cpuRead(addr, true); addr++; sInst += "$" + hex(value, 2) + "[$" + hex(addr + (int8_t)value, 4) + "] {REL}"; } // Add the formed string to the map using the instr's addr // as the key for lookup later as the instrs as variable // in length, so a straight up incremental index is not sufficient mapLines[line_addr] = sInst; } return mapLines; }
19.597786
93
0.602241
karangovil
714b6117d61a2f5a55e09d5a87a01b7f0f6c7637
240
cpp
C++
src/UOJ_1573 - (1176543) Accepted.cpp
miguelarauj1o/UOJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
80
2015-01-07T01:18:40.000Z
2021-05-04T15:23:18.000Z
src/UOJ_1573 - (1176543) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
1
2019-01-07T01:13:32.000Z
2019-01-07T01:13:32.000Z
src/UOJ_1573 - (1176543) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
28
2015-03-05T11:53:23.000Z
2020-07-05T15:50:42.000Z
#include <cstdio> #include <cmath> using namespace std; int main() { int a, b, c, v, x; while(scanf("%i %i %i", &a, &b, &c) && (a || b || c)) { v = a * b * c; x = (int) cbrt(v); printf("%i\n", x); } return 0; }
14.117647
55
0.4375
miguelarauj1o
714fc9a6851a4d4a365fec9a68ddd461a34428b5
3,797
hpp
C++
adaptivlib/include/adaptiv/utility/input/numeric_parsers.hpp
seriouslyhypersonic/adaptiv_co
2421d7dc91d0291dd45702a2a2ddadab9adda91d
[ "BSL-1.0" ]
null
null
null
adaptivlib/include/adaptiv/utility/input/numeric_parsers.hpp
seriouslyhypersonic/adaptiv_co
2421d7dc91d0291dd45702a2a2ddadab9adda91d
[ "BSL-1.0" ]
null
null
null
adaptivlib/include/adaptiv/utility/input/numeric_parsers.hpp
seriouslyhypersonic/adaptiv_co
2421d7dc91d0291dd45702a2a2ddadab9adda91d
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) Nuno Alves de Sousa 2019 * * Use, modification and distribution is subject to 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 ADAPTIV_NUMERIC_PARSERS_HPP #define ADAPTIV_NUMERIC_PARSERS_HPP #include <adaptiv/macros.hpp> #include <boost/spirit/home/x3.hpp> ADAPTIV_NAMESPACE_BEGIN ADAPTIV_UTILITY_NAMESPACE_BEGIN ADAPTIV_INPUT_NAMESPACE_BEGIN /// Numeric X3 parsers namespace parsers::numeric { namespace x3 = boost::spirit::x3; /** * @brief Metafunction that maps a specific numeric type to an X3 parser * @tparam T The numeric type to associate with the X3 parser * @typedef \c attribute_type type alias for the corresponding X3 * numeric parser attribute (i.e. type \c T) * @typedef \c tag type alias for the respective x3::rule tag * @static Member \c name for the x3::rule name * @static Member \c parser_def, i.e. the underlying X3 parser */ template<class T> struct get_numeric_parser { }; template<> struct get_numeric_parser<float> { using attribute_type = float; using tag = class float_tag; inline static char const* name = "expecting float"; inline static x3::float_type parser = x3::float_; }; template<> struct get_numeric_parser<double> { using attribute_type = double; using tag = class double_tag; inline static char const* name = "expecting double"; inline static x3::double_type parser = x3::double_; }; template<> struct get_numeric_parser<short> { using attribute_type = short; using tag = class short_tag; inline static char const* name = "expecting short"; inline static x3::short_type parser = x3::short_; }; template<> struct get_numeric_parser<unsigned short> { using attribute_type = unsigned short; using tag = class unsigned_short_tag; inline static char const* name = "expecting unsigned short"; inline static x3::ushort_type parser = x3::ushort_; }; template<> struct get_numeric_parser<int> { using attribute_type = int; using tag = class int_tag; inline static char const* name = "expecting int"; inline static x3::int_type parser = x3::int_; }; template<> struct get_numeric_parser<unsigned int> { using attribute_type = unsigned int; using tag = class uint_tag; inline static char const* name = "expecting unsigned int"; inline static x3::uint_type parser = x3::uint_; }; // No x3::uint_ parser template<> struct get_numeric_parser<long> { using attribute_type = long; using tag = class long_tag; inline static char const* name = "expecting long"; inline static x3::long_type parser = x3::long_; }; template<> struct get_numeric_parser<unsigned long> { using attribute_type = unsigned long; using tag = class unsigned_long_tag; inline static char const* name = "expecting unsigned long"; inline static x3::ulong_type parser = x3::ulong_; }; template<> struct get_numeric_parser<long long> { using attribute_type = long long; using tag = class long_long_tag; inline static char const* name = "expecting long long"; inline static x3::long_type parser = x3::long_; }; template<> struct get_numeric_parser<unsigned long long> { using attribute_type = unsigned long long; using tag = class unsigned_long_long_tag; inline static char const* name = "expecting unsigned long long"; inline static x3::ulong_longtype parser = x3::ulong_long; }; } // namespace parsers::numeric ADAPTIV_INPUT_NAMESPACE_END ADAPTIV_UTILITY_NAMESPACE_END ADAPTIV_NAMESPACE_END #endif //ADAPTIV_NUMERIC_PARSERS_HPP
26.186207
79
0.70108
seriouslyhypersonic
71527f3e27262169c4f065b3b95d2fb683121ece
1,263
cpp
C++
src/services/DeviceService.cpp
nick-lrg/microSDC
a0a95edcf74164cfecf699f77e57d7f84a9c0b68
[ "BSD-3-Clause" ]
null
null
null
src/services/DeviceService.cpp
nick-lrg/microSDC
a0a95edcf74164cfecf699f77e57d7f84a9c0b68
[ "BSD-3-Clause" ]
null
null
null
src/services/DeviceService.cpp
nick-lrg/microSDC
a0a95edcf74164cfecf699f77e57d7f84a9c0b68
[ "BSD-3-Clause" ]
null
null
null
#include "services/DeviceService.hpp" #include "Log.hpp" #include "WebServer/Request.hpp" #include "datamodel/MDPWSConstants.hpp" #include "dpws/MetadataProvider.hpp" #include "services/SoapFault.hpp" static constexpr const char* TAG = "DeviceService"; DeviceService::DeviceService(std::shared_ptr<const MetadataProvider> metadata) : metadata_(std::move(metadata)) { } std::string DeviceService::getURI() const { return metadata_->getDeviceServicePath(); } void DeviceService::handleRequest(std::unique_ptr<Request> req) { const auto requestEnvelope = req->getEnvelope(); const auto& soapAction = requestEnvelope.Header().Action(); if (soapAction == MDPWS::WS_ACTION_GET) { MESSAGEMODEL::Envelope responseEnvelope; fillResponseMessageFromRequestMessage(responseEnvelope, requestEnvelope); responseEnvelope.Header().Action() = WS::ADDRESSING::URIType(MDPWS::WS_ACTION_GET_RESPONSE); metadata_->fillDeviceMetadata(responseEnvelope); req->respond(responseEnvelope); } else if (soapAction == MDPWS::WS_ACTION_GET_METADATA_REQUEST) { LOG(LogLevel::WARNING, "HANDLE ACTION_GETMETADATA_REQUEST"); } else { LOG(LogLevel::ERROR, "Unknown soap action " << soapAction); req->respond(SoapFault().envelope()); } }
30.071429
96
0.751386
nick-lrg
715c27336801fe475132011ce3ac8c396049937c
172
cpp
C++
src/util/dumpstack/enable_dump.cpp
HouQiming/ama
b7dddb425892e1d4d95312b330061911489e242b
[ "BSD-2-Clause" ]
24
2022-01-06T20:26:42.000Z
2022-02-18T07:56:44.000Z
src/util/dumpstack/enable_dump.cpp
HouQiming/ama
b7dddb425892e1d4d95312b330061911489e242b
[ "BSD-2-Clause" ]
null
null
null
src/util/dumpstack/enable_dump.cpp
HouQiming/ama
b7dddb425892e1d4d95312b330061911489e242b
[ "BSD-2-Clause" ]
4
2022-01-06T20:26:44.000Z
2022-01-14T06:59:48.000Z
#include "./dumpstack.h" #pragma no_auto_header() struct AutoEnableStackDump { AutoEnableStackDump() {DumpStack::EnableDump();} }; static AutoEnableStackDump enabler{};
19.111111
49
0.767442
HouQiming
715d37bebeb9a4807c3716b840a4e813bc966c76
1,123
cpp
C++
KTLT_doan1/boss.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
KTLT_doan1/boss.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
KTLT_doan1/boss.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
#include "boss.h" static const string BossSprite[] = { " _____|___|_|___|_____ ", " |___________________| ", " |___________________| ", " |=|=====|===|=====|=| ", " |=|======\\=/======|=| ", " V V V " }; void DrawBoss(position bossPos) { for (int i = 0; i < 6; i++) { for (int j = -11; j <= 11; j++) { if(bossPos.c + j < boardWidth - 1 && bossPos.c + j > 0) SetBoardValue(bossPos.r + i, bossPos.c + j, BossSprite[i][j+11]); } } } void CreateBoss(int& bossHp, int& maxBossHP, position& bossPos) { bossHp = maxBossHP; maxBossHP += 2; bossPos = { 1, boardWidth / 2 }; DrawBoss(bossPos); } void BossMovement(position playerPos, position& bossPos) { if (bossPos.c > playerPos.c) { bossPos.c--; DrawBoss(bossPos); } else if (bossPos.c < playerPos.c) { bossPos.c++; DrawBoss(bossPos); } } void DestroyBoss(position bossPos) { for (int i = 0; i < 6; i++) { for (int j = -10; j <= 10; j++) { if (bossPos.c + j < boardWidth - 1 && bossPos.c + j > 0) SetBoardValue(bossPos.r + i, bossPos.c + j); } } }
19.701754
70
0.524488
ipupro2
7161a0f8fcdf17e561d47746b676481f4e038093
6,251
cpp
C++
jogo/pacman.cpp
eduardo-gomes/cefet-public
559b55194c425b3df83e85c78ed7ede424b9537d
[ "Unlicense" ]
null
null
null
jogo/pacman.cpp
eduardo-gomes/cefet-public
559b55194c425b3df83e85c78ed7ede424b9537d
[ "Unlicense" ]
7
2019-11-12T00:58:09.000Z
2019-11-19T19:34:49.000Z
jogo/pacman.cpp
eduardo-gomes/cefet-public
559b55194c425b3df83e85c78ed7ede424b9537d
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #include <ncurses.h> using namespace std; /*int mapa[9][7] = { {-1, -1, -1,-1, -1, -1, -1}, {-1, 0, 0, 0, 0, 0, -1}, {-1, 0, -1, 0, -1, 0, -1}, {0, 0, -1, 0, -1, 0, 0}, {-1, 0, -1, 0, -1, 0, -1}, {0, 0, -1, 0, -1, 0, 0}, {-1, 0, -1, -1, -1, 0, -1}, {-1, 0, 0, 0, 0, 0, -1}, {-1, -1, -1, -1, -1, -1, -1}}; int mapaori[9][7] = { {-1, -1, -1, -1, -1, -1, -1}, {-1, 0, 0, 0, 0, 0, -1}, {-1, 0, -1, 0, -1, 0, -1}, {0, 0, -1, 0, -1, 0, 0}, {-1, 0, -1, 0, -1, 0, -1}, {0, 0, -1, 0, -1, 0, 0}, {-1, 0, -1, -1, -1, 0, -1}, {-1, 0, 0, 0, 0, 0, -1}, {-1, -1, -1, -1, -1, -1, -1}};*/ bool vivo = 1; int mapadist[20][19], mapa[20][19] = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, -1}, {-1, 0, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, 0, -1}, {-1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1}, {-1, -1, -1, -1, 0, -1, 0, -1, -1, 0, -1, -1, 0, -1, 0, -1, -1, -1, -1}, {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, {-1, 0, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, 0, -1}, {-1, 0, -1, 0, -1, 0, 0, -1, 0, -1, -1, -1, 0, 0, -1, 0, -1, 0, -1}, {-1, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1}, {-1, 0, -1, 0, -1, 0, 0, -1, -1, -1, -1, -1, 0, 0, -1, 0, -1, 0, -1}, {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, {-1, 0, 0, -1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, 0, -1}, {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, 0, -1}, {-1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, -1}, {-1, 0, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, 0, -1}, {-1, 0, 0, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, 0, 0, -1}, {-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; struct posidire{ int x; int y; int dx; int dy; }; struct posi{ int x; int y; }; posi dire[4] = {{.x = 0, .y = 1}, {.x = 1, .y = 0}, {.x = 0, .y = -1}, {.x = -1, .y = 0}}; posi mapas = {.x = 19, .y = 20}; posi player = {.x = 1, .y = 1}; posi p1dire = {.x = 1, .y = 0}; posidire inimi[3] = {{.x = 9, .y = 8, .dx = 1, .dy = 0}, {.x = 9, .y = 8, .dx = 1, .dy = 0}, {.x = 9, .y = 8, .dx = 1, .dy = 0}}; void printmapa(){ move(0, 0); for(int i = 0; i < mapas.y; ++i){ for(int j = 0; j < mapas.x; ++j){ if(mapa[i][j] == -1){ printw("#"); }else if (mapa[i][j] == 0){ if(i == player.y && j == player.x){ printw("@"); }else{ printw(" "); } } } printw("\n"); } refresh(); } void playerdist(){ for(int i = 0; i < mapas.y; ++i){ memcpy(mapadist[i], mapa[i], sizeof(int) * mapas.x); } queue<pair<int, int> > fila; fila.push(make_pair(player.y, player.x)); int dst = 0; mapadist[player.y][player.x] = 0; while(!fila.empty()){ pair<int, int> now = fila.front(); fila.pop(); for(int i = 0; i < 4; ++i){ if(mapadist[now.first + dire[i].y][now.second + dire[i].x] == 0){ fila.push(make_pair(now.first + dire[i].y, now.second + dire[i].x)); mapadist[now.first + dire[i].y][now.second + dire[i].x] = dst++; } } } } int inimicanchange(int ini){ int count = 0; for(int i = 0; i < 4; ++i){ if(mapa[inimi[ini].y + dire[i].y][inimi[ini].x + dire[i].x] != -1) count++; } return count; } void inimirand(int ini){ int rd = rand() % 4; if(inimi[ini].dy == -dire[rd].y && inimi[ini].dx == -dire[rd].x && inimicanchange(ini) > 2) return; inimi[ini].dy = dire[rd].y; inimi[ini].dx = dire[rd].x; } void moveinimi(int ini){ if (mapa[inimi[ini].y + inimi[ini].dy][inimi[ini].x + inimi[ini].dx] == -1) { while (mapa[inimi[ini].y + inimi[ini].dy][inimi[ini].x + inimi[ini].dx] == -1){ inimirand(ini); } } inimi[ini].y += inimi[ini].dy; inimi[ini].x += inimi[ini].dx; if(inimicanchange(ini) > 2) inimirand(ini); } void iniAI(int ini){ if(inimicanchange(ini) > 2){ for(int i = 0; i < 4; ++i){ if (mapadist[inimi[ini].y][inimi[ini].x] > mapadist[inimi[ini].y + dire[i].y][inimi[ini].x + dire[i].x] && mapa[inimi[ini].y + dire[i].y][inimi[ini].x + dire[i].x] != -1){ inimi[ini].dy = dire[i].y; inimi[ini].dx = dire[i].x; } } } moveinimi(ini); } void printinimi(int ini){ attron(COLOR_PAIR(ini+1)); mvprintw(inimi[ini].y, inimi[ini].x, "$"); attroff(COLOR_PAIR(ini+1)); move(0, 0); } int death(){ for(int i = 0; i < 3; ++i){ if (player.x == inimi[i].x && player.y == inimi[i].y){ return 1; } } return 0; } void p1anda(){ if(mapa[player.y + p1dire.y][player.x +p1dire.x] == 0){ player.x += p1dire.x; player.y += p1dire.y; } } void procentrada(char ent){ if(ent == 's'){ p1dire.x = 0; p1dire.y = 1; return; } if(ent == 'w'){ p1dire.x = 0; p1dire.y = -1; return; } if(ent == 'a'){ p1dire.x = -1; p1dire.y = 0; return; } if(ent == 'd'){ p1dire.x = 1; p1dire.y = 0; return; } } void printa(){ printmapa(); printinimi(0); printinimi(1); printinimi(2); } clock_t t = clock(), ini1 = clock(), ini2 = clock(), ini3 = clock() + CLOCKS_PER_SEC * 10; void inimigos(){ if(clock() > ini1 + CLOCKS_PER_SEC * 0.2){ moveinimi(0); printa(); ini1 = clock(); } if(clock() > ini2 + CLOCKS_PER_SEC * 0.15){ moveinimi(1); printa(); ini2 = clock(); } playerdist(); if(clock() > ini3 + CLOCKS_PER_SEC * 0.02){ //moveinimi(2); iniAI(2); printa(); ini3 = clock(); } } int main(){ char pressed, last; initscr(); timeout(0); noecho(); start_color(); init_pair(1, COLOR_BLUE, COLOR_BLACK); init_pair(2, COLOR_YELLOW, COLOR_BLACK); init_pair(3, COLOR_RED, COLOR_BLACK); while(vivo){ pressed = getch(); if(pressed >= 'a' && pressed <= 'z'){ procentrada(pressed); //break; //printf("%c", pressed); } //printw("a"); if(clock() > t + CLOCKS_PER_SEC * 0.1){ p1anda(); printa(); t = clock(); } inimigos(); if (death()) vivo = !vivo; if(pressed == ';') break; } if(!vivo){ clock_t endcoold = clock() + CLOCKS_PER_SEC * 3; while(endcoold > clock()); } endwin(); }
27.060606
174
0.457047
eduardo-gomes
7166c7bdd8636e29675296a987aefc0546dd38bc
25,742
hxx
C++
GOOSE_FatWaterDecomposition/optnet/_base/point.hxx
pdaude/CREAM_PDFF
56bc7639b3e027f6656ac33720863d0953a85b45
[ "Apache-2.0" ]
null
null
null
GOOSE_FatWaterDecomposition/optnet/_base/point.hxx
pdaude/CREAM_PDFF
56bc7639b3e027f6656ac33720863d0953a85b45
[ "Apache-2.0" ]
null
null
null
GOOSE_FatWaterDecomposition/optnet/_base/point.hxx
pdaude/CREAM_PDFF
56bc7639b3e027f6656ac33720863d0953a85b45
[ "Apache-2.0" ]
null
null
null
/* ========================================================================== | | $Id: point.hxx 2137 2007-07-02 03:26:31Z kangli $ | | Written by Kang Li <kangl@cmu.edu> | Department of Electrical and Computer Engineering | Carnegie Mellon University | ========================================================================== | This file is a part of the OptimalNet library. ========================================================================== | Copyright (c) 2003-2007 Kang Li <kangl@cmu.edu>. All rights reserved. | | Version: MPL 1.1/GPL 2.0/LGPL 2.1 | | The contents of this file are subject to the Mozilla Public License | Version 1.1 (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.mozilla.org/MPL/ | | Software distributed under the License is distributed on an "AS IS" | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See | the License for the specific language governing rights and limitations | under the License. | | The Original Code is OptimalNet (optnet) Library code. | | The Initial Developer of the Original Code is Kang Li. Portions | created by the Initial Developer are Copyright (C) 2003-2007 the | Initial Developer. All Rights Reserved. | | Contributor(s): None | | Alternatively, the contents of this file may be used under the terms | of either of the GNU General Public License Version 2 or later (the | "GPL"), or the GNU Lesser General Public License Version 2.1 or later | (the "LGPL"), in which case the provisions of the GPL or the LGPL are | applicable instead of those above. If you wish to allow use of your | version of this file only under the terms of either the GPL or the | LGPL, and not to allow others to use your version of this file under | the terms of the MPL, indicate your decision by deleting the | provisions above and replace them with the notice and other provisions | required by the GPL or the LGPL. If you do not delete the provisions | above, a recipient may use your version of this file under the terms | of any one of the MPL, the GPL or the LGPL. ========================================================================== */ #ifndef ___POINT_HXX___ # define ___POINT_HXX___ # if defined(_MSC_VER) && (_MSC_VER > 1000) # pragma once # pragma warning(disable: 4284) # pragma warning(disable: 4786) # endif # include <cmath> # include <cassert> # include <cstddef> # ifdef min // # undef min // # endif // These would interfere with # ifdef max // std::numerical_limits<_T>::max # undef max // std::numerical_limits<_T>::min # endif // # include <limits> /// @namespace optnet namespace optnet { /////////////////////////////////////////////////////////////////////////// /// @class point /// @brief Multidimensional point type. /////////////////////////////////////////////////////////////////////////// template <typename _T, int _Dim> struct point { typedef _T value_type; typedef _T& reference; typedef const _T& const_reference; typedef _T* pointer; typedef const _T* const_pointer; typedef size_t size_type; point() { clear(); } # ifdef __OPTNET_CRAPPY_MSC__ template<typename _Point> point(const _Point& rhs) { assert(_Dim == rhs.dim()); for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(rhs.v[i]); } # else // normal compilers point(const point& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = rhs.v[i]; } template<typename _T2> point(const point<_T2, _Dim>& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(rhs.v[i]); } # endif // // operator = // /////////////////////////////////////////////////////////////////////// # ifdef __OPTNET_CRAPPY_MSC__ template<typename _Point> inline point& operator=(const _Point& rhs) { assert(_Dim == rhs.dim()); for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(rhs.v[i]); return *this; } # else // normal compilers inline point& operator=(const point& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = rhs.v[i]; return *this; } template<typename _T2> inline point& operator=(const point<_T2, _Dim>& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(rhs.v[i]); return *this; } # endif /////////////////////////////////////////////////////////////////////// /// Point component access. /// /// @param i The index of the component. /// /// @return A constant reference to the i-th component. /////////////////////////////////////////////////////////////////////// inline const_reference operator[](const size_type& i) const { return v[i]; } /////////////////////////////////////////////////////////////////////// /// Point component access. /// /// @param i The index of the component. /// /// @return A reference to the i-th component. /////////////////////////////////////////////////////////////////////// inline reference operator[](const size_type& i) { return v[i]; } // // operator += // /////////////////////////////////////////////////////////////////////// # ifndef __OPTNET_CRAPPY_MSC__ inline point& operator+=(const point& rhs) { for (int i = 0; i < _Dim; ++i) v[i] += rhs.v[i]; return *this; } # endif template<typename _T2> inline point& operator+=(const point<_T2, _Dim>& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(v[i] + rhs.v[i]); return *this; } # define POINT_OPERATOR_AE_PROTO(type) \ inline point& operator+=(const type& rhs) \ { \ for (int i = 0; i < _Dim; ++i) \ v[i] = static_cast<value_type>(v[i] + rhs); \ return *this; \ } POINT_OPERATOR_AE_PROTO(float ) POINT_OPERATOR_AE_PROTO(double ) POINT_OPERATOR_AE_PROTO(long double ) POINT_OPERATOR_AE_PROTO(char ) POINT_OPERATOR_AE_PROTO(int ) POINT_OPERATOR_AE_PROTO(long ) POINT_OPERATOR_AE_PROTO(short ) POINT_OPERATOR_AE_PROTO(unsigned char ) POINT_OPERATOR_AE_PROTO(unsigned int ) POINT_OPERATOR_AE_PROTO(unsigned long ) POINT_OPERATOR_AE_PROTO(unsigned short ) // // operator -= // /////////////////////////////////////////////////////////////////////// # ifndef __OPTNET_CRAPPY_MSC__ inline point& operator-=(const point& rhs) { for (int i = 0; i < _Dim; ++i) v[i] -= rhs.v[i]; return *this; } # endif template<typename _T2> inline point& operator-=(const point<_T2, _Dim>& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(v[i] - rhs.v[i]); return *this; } # define POINT_OPERATOR_SE_PROTO(type) \ inline point& operator-=(const type& rhs) \ { \ for (int i = 0; i < _Dim; ++i) \ v[i] = static_cast<value_type>(v[i] - rhs); \ return *this; \ } POINT_OPERATOR_SE_PROTO(float ) POINT_OPERATOR_SE_PROTO(double ) POINT_OPERATOR_SE_PROTO(long double ) POINT_OPERATOR_SE_PROTO(char ) POINT_OPERATOR_SE_PROTO(int ) POINT_OPERATOR_SE_PROTO(long ) POINT_OPERATOR_SE_PROTO(short ) POINT_OPERATOR_SE_PROTO(unsigned char ) POINT_OPERATOR_SE_PROTO(unsigned int ) POINT_OPERATOR_SE_PROTO(unsigned long ) POINT_OPERATOR_SE_PROTO(unsigned short ) // // operator *= // /////////////////////////////////////////////////////////////////////// # ifndef __OPTNET_CRAPPY_MSC__ inline point& operator*=(const point& rhs) { for (int i = 0; i < _Dim; ++i) v[i] *= rhs.v[i]; return *this; } # endif template<typename _T2> inline point& operator*=(const point<_T2, _Dim>& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(v[i] * rhs.v[i]); return *this; } # define POINT_OPERATOR_ME_PROTO(type) \ inline point& operator*=(const type& rhs) \ { \ for (int i = 0; i < _Dim; ++i) \ v[i] = static_cast<value_type>(v[i] * rhs); \ return *this; \ } POINT_OPERATOR_ME_PROTO(float ) POINT_OPERATOR_ME_PROTO(double ) POINT_OPERATOR_ME_PROTO(long double ) POINT_OPERATOR_ME_PROTO(char ) POINT_OPERATOR_ME_PROTO(int ) POINT_OPERATOR_ME_PROTO(long ) POINT_OPERATOR_ME_PROTO(short ) POINT_OPERATOR_ME_PROTO(unsigned char ) POINT_OPERATOR_ME_PROTO(unsigned int ) POINT_OPERATOR_ME_PROTO(unsigned long ) POINT_OPERATOR_ME_PROTO(unsigned short ) // // operator /= // /////////////////////////////////////////////////////////////////////// # ifndef __OPTNET_CRAPPY_MSC__ inline point& operator/=(const point& rhs) { for (int i = 0; i < _Dim; ++i) v[i] /= rhs.v[i]; return *this; } # endif template<typename _T2> inline point& operator/=(const point<_T2, _Dim>& rhs) { for (int i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(v[i] / rhs.v[i]); return *this; } # define POINT_OPERATOR_DE_PROTO(type) \ inline point& operator/=(const type& rhs) \ { \ for (int i = 0; i < _Dim; ++i) \ v[i] = static_cast<value_type>(v[i] / rhs); \ return *this; \ } POINT_OPERATOR_DE_PROTO(float ) POINT_OPERATOR_DE_PROTO(double ) POINT_OPERATOR_DE_PROTO(long double ) POINT_OPERATOR_DE_PROTO(char ) POINT_OPERATOR_DE_PROTO(int ) POINT_OPERATOR_DE_PROTO(long ) POINT_OPERATOR_DE_PROTO(short ) POINT_OPERATOR_DE_PROTO(unsigned char ) POINT_OPERATOR_DE_PROTO(unsigned int ) POINT_OPERATOR_DE_PROTO(unsigned long ) POINT_OPERATOR_DE_PROTO(unsigned short ) // // operator < // /////////////////////////////////////////////////////////////////////// /// Compares two points. /// /// @return Returns true if the point is less than the point on the /// right-hand side, false otherwise. /////////////////////////////////////////////////////////////////////// inline bool operator< (const point& rhs) const { return memcmp(v, rhs.v, sizeof(value_type) * _Dim) < 0; } // // operator == // # ifndef __OPTNET_CRAPPY_MSC__ /////////////////////////////////////////////////////////////////////// /// Compares two points. /// /// @return Returns true if the two points are equal. /////////////////////////////////////////////////////////////////////// inline bool operator==(const point& rhs) const { for (int i = 0; i < _Dim; ++i) if (v[i] != rhs.v[i]) return false; return true; } # endif /////////////////////////////////////////////////////////////////////// /// Compares two points. /// /// @return Returns true if the two points are equal. /////////////////////////////////////////////////////////////////////// template <typename _T2> inline bool operator==(const point<_T2, _Dim>& rhs) const { for (int i = 0; i < _Dim; ++i) if (v[i] != static_cast<value_type>(rhs.v[i])) return false; return true; } // // operator != // # ifndef __OPTNET_CRAPPY_MSC__ /////////////////////////////////////////////////////////////////////// /// Compares two points. /// /// @return Returns true if the two points are not equal. /////////////////////////////////////////////////////////////////////// inline bool operator!=(const point& rhs) const { return !(*this == rhs); } # endif /////////////////////////////////////////////////////////////////////// /// Compares two points. /// /// @return Returns true if the two points are not equal. /////////////////////////////////////////////////////////////////////// template <typename _T2> inline bool operator!=(const point<_T2, _Dim>& rhs) const { return !(*this == rhs); } // // operator - // /////////////////////////////////////////////////////////////////////// /// Negate the coordinates of the point. /// /// @return The negated point. /////////////////////////////////////////////////////////////////////// inline point operator-() const { point pt; for (int i = 0; i < _Dim; ++i) pt.v[i] = -v[i]; return pt; } /////////////////////////////////////////////////////////////////////// /// Computes the dot-product of two points (vectors). /// /// @return The computed dot-product. /////////////////////////////////////////////////////////////////////// # ifndef __OPTNET_CRAPPY_MSC__ inline value_type dot(const point& rhs) { value_type ans = value_type(); for (int i = 0; i < _Dim; ++i) ans += v[i] * rhs.v[i]; return ans; } # endif /////////////////////////////////////////////////////////////////////// /// Computes the dot-product of two points (vectors). /// /// @return The computed dot-product. /////////////////////////////////////////////////////////////////////// template<typename _T2> inline value_type dot(const point<_T2, _Dim>& rhs) { value_type ans = value_type(); for (int i = 0; i < _Dim; ++i) ans += v[i] * static_cast<value_type>(rhs.v[i]); return ans; } /////////////////////////////////////////////////////////////////////// /// Returns the squared Euclidean distance between the point and /// the origin. /// /// @return The computed squared length. /////////////////////////////////////////////////////////////////////// inline value_type length2() const { value_type ans = value_type(); for (int i = 0; i < _Dim; ++i) ans += v[i] * v[i]; return ans; } /////////////////////////////////////////////////////////////////////// /// Returns the Euclidean distance between the point and the origin. /// /// @return The computed length. /////////////////////////////////////////////////////////////////////// inline value_type length() const { value_type ans = length2(); return static_cast<value_type>(sqrt((double)(ans))); } /////////////////////////////////////////////////////////////////////// /// Normalize the point such that its distance to the origin is one. /////////////////////////////////////////////////////////////////////// inline void normalize() { int i; value_type len = length(); if (len > std::numeric_limits<value_type>::epsilon()) { double invlen = 1.0 / (double)len; for (i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(v[i] * invlen); } else { for (i = 0; i < _Dim; ++i) v[i] = static_cast<value_type>(0); } } /////////////////////////////////////////////////////////////////////// /// Sets the point to zero. /////////////////////////////////////////////////////////////////////// inline void clear() { for (value_type* p = v; p != v + _Dim; ++p) *p = value_type(); // Clear value. } /////////////////////////////////////////////////////////////////////// /// Returns the dimension of the point. /// /// @return The dimension of the point. Same as the _Dim template /// parameter. /////////////////////////////////////////////////////////////////////// inline size_type dim() const { return size_type(_Dim); } /////////////////////////////////////////////////////////////////////// /// Point components. /// /// @remarks Note that point[x] = point.v[x]. /////////////////////////////////////////////////////////////////////// value_type v[_Dim]; }; // // operator + // /////////////////////////////////////////////////////////////////////////// template <typename _T, int _Dim> inline point<_T, _Dim> operator+ (const point<_T, _Dim>& lhs, const point<_T, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj += rhs; return obj; } # ifndef __OPTNET_CRAPPY_MSC__ template <typename _T, typename _T2, int _Dim> inline point<_T, _Dim> operator+ (const point<_T, _Dim>& lhs, const point<_T2, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj += rhs; return obj; } # endif /////////////////////////////////////////////////////////////////////////// # define POINT_OPERATOR_AR_PROTO(type) \ template <typename _T, int _Dim> \ inline point<_T, _Dim> \ operator+ (const point<_T, _Dim>& lhs, const type& rhs) \ { \ point<_T, _Dim> obj(lhs); obj += rhs; return obj; \ } POINT_OPERATOR_AR_PROTO(float ) POINT_OPERATOR_AR_PROTO(double ) POINT_OPERATOR_AR_PROTO(long double ) POINT_OPERATOR_AR_PROTO(char ) POINT_OPERATOR_AR_PROTO(int ) POINT_OPERATOR_AR_PROTO(long ) POINT_OPERATOR_AR_PROTO(short ) POINT_OPERATOR_AR_PROTO(unsigned char ) POINT_OPERATOR_AR_PROTO(unsigned int ) POINT_OPERATOR_AR_PROTO(unsigned long ) POINT_OPERATOR_AR_PROTO(unsigned short ) /////////////////////////////////////////////////////////////////////////// # define POINT_OPERATOR_AL_PROTO(type) \ template <typename _T, int _Dim> \ inline point<_T, _Dim> \ operator+ (const type& lhs, const point<_T, _Dim>& rhs) \ { \ point<_T, _Dim> obj(rhs); obj += lhs; return obj; \ } POINT_OPERATOR_AL_PROTO(float ) POINT_OPERATOR_AL_PROTO(double ) POINT_OPERATOR_AL_PROTO(long double ) POINT_OPERATOR_AL_PROTO(char ) POINT_OPERATOR_AL_PROTO(int ) POINT_OPERATOR_AL_PROTO(long ) POINT_OPERATOR_AL_PROTO(short ) POINT_OPERATOR_AL_PROTO(unsigned char ) POINT_OPERATOR_AL_PROTO(unsigned int ) POINT_OPERATOR_AL_PROTO(unsigned long ) POINT_OPERATOR_AL_PROTO(unsigned short ) // // operator - // /////////////////////////////////////////////////////////////////////////// template <typename _T, int _Dim> inline point<_T, _Dim> operator- (const point<_T, _Dim>& lhs, const point<_T, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj -= rhs; return obj; } # ifndef __OPTNET_CRAPPY_MSC__ template <typename _T, typename _T2, int _Dim> inline point<_T, _Dim> operator- (const point<_T, _Dim>& lhs, const point<_T2, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj -= rhs; return obj; } # endif //__OPTNET_CRAPPY_MSC__ /////////////////////////////////////////////////////////////////////////// # define POINT_OPERATOR_SR_PROTO(type) \ template <typename _T, int _Dim> \ inline point<_T, _Dim> \ operator- (const point<_T, _Dim>& lhs, const type& rhs) \ { \ point<_T, _Dim> obj(lhs); obj -= rhs; return obj; \ } POINT_OPERATOR_SR_PROTO(float ) POINT_OPERATOR_SR_PROTO(double ) POINT_OPERATOR_SR_PROTO(long double ) POINT_OPERATOR_SR_PROTO(char ) POINT_OPERATOR_SR_PROTO(int ) POINT_OPERATOR_SR_PROTO(long ) POINT_OPERATOR_SR_PROTO(short ) POINT_OPERATOR_SR_PROTO(unsigned char ) POINT_OPERATOR_SR_PROTO(unsigned int ) POINT_OPERATOR_SR_PROTO(unsigned long ) POINT_OPERATOR_SR_PROTO(unsigned short ) // // operator * // /////////////////////////////////////////////////////////////////////////// template <typename _T, int _Dim> inline point<_T, _Dim> operator* (const point<_T, _Dim>& lhs, const point<_T, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj *= rhs; return obj; } # ifndef __OPTNET_CRAPPY_MSC__ template <typename _T, typename _T2, int _Dim> inline point<_T, _Dim> operator* (const point<_T, _Dim>& lhs, const point<_T2, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj *= rhs; return obj; } # endif //__OPTNET_CRAPPY_MSC__ /////////////////////////////////////////////////////////////////////////// # define POINT_OPERATOR_MR_PROTO(type) \ template <typename _T, int _Dim> \ inline point<_T, _Dim> \ operator* (const point<_T, _Dim>& lhs, const type& rhs) \ { \ point<_T, _Dim> obj(lhs); obj *= rhs; return obj; \ } POINT_OPERATOR_MR_PROTO(float ) POINT_OPERATOR_MR_PROTO(double ) POINT_OPERATOR_MR_PROTO(long double ) POINT_OPERATOR_MR_PROTO(char ) POINT_OPERATOR_MR_PROTO(int ) POINT_OPERATOR_MR_PROTO(long ) POINT_OPERATOR_MR_PROTO(short ) POINT_OPERATOR_MR_PROTO(unsigned char ) POINT_OPERATOR_MR_PROTO(unsigned int ) POINT_OPERATOR_MR_PROTO(unsigned long ) POINT_OPERATOR_MR_PROTO(unsigned short ) /////////////////////////////////////////////////////////////////////////// # define POINT_OPERATOR_ML_PROTO(type) \ template <typename _T, int _Dim> \ inline point<_T, _Dim> \ operator* (const type& lhs, const point<_T, _Dim>& rhs) \ { \ point<_T, _Dim> obj(rhs); obj *= lhs; return obj; \ } POINT_OPERATOR_ML_PROTO(float ) POINT_OPERATOR_ML_PROTO(double ) POINT_OPERATOR_ML_PROTO(long double ) POINT_OPERATOR_ML_PROTO(char ) POINT_OPERATOR_ML_PROTO(int ) POINT_OPERATOR_ML_PROTO(long ) POINT_OPERATOR_ML_PROTO(short ) POINT_OPERATOR_ML_PROTO(unsigned char ) POINT_OPERATOR_ML_PROTO(unsigned int ) POINT_OPERATOR_ML_PROTO(unsigned long ) POINT_OPERATOR_ML_PROTO(unsigned short ) // // operator / // /////////////////////////////////////////////////////////////////////////// template <typename _T, int _Dim> inline point<_T, _Dim> operator/ (const point<_T, _Dim>& lhs, const point<_T, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj /= rhs; return obj; } # ifndef __OPTNET_CRAPPY_MSC__ template <typename _T, typename _T2, int _Dim> inline point<_T, _Dim> operator/ (const point<_T, _Dim>& lhs, const point<_T2, _Dim>& rhs) { point<_T, _Dim> obj(lhs); obj /= rhs; return obj; } # endif //__OPTNET_CRAPPY_MSC__ /////////////////////////////////////////////////////////////////////////// # define POINT_OPERATOR_DR_PROTO(type) \ template <typename _T, int _Dim> \ inline point<_T, _Dim> \ operator/ (const point<_T, _Dim>& lhs, const type& rhs) \ { \ point<_T, _Dim> obj(lhs); obj /= rhs; return obj; \ } POINT_OPERATOR_DR_PROTO(float ) POINT_OPERATOR_DR_PROTO(double ) POINT_OPERATOR_DR_PROTO(long double ) POINT_OPERATOR_DR_PROTO(char ) POINT_OPERATOR_DR_PROTO(int ) POINT_OPERATOR_DR_PROTO(long ) POINT_OPERATOR_DR_PROTO(short ) POINT_OPERATOR_DR_PROTO(unsigned char ) POINT_OPERATOR_DR_PROTO(unsigned int ) POINT_OPERATOR_DR_PROTO(unsigned long ) POINT_OPERATOR_DR_PROTO(unsigned short ) } // namespace #endif // ___POINT_HXX___
35.555249
75
0.461153
pdaude
7176b56b20914f7d98308e9c403a8a0b18a40fcb
14,985
cpp
C++
src/Window.cpp
lintopher0315/gadget
9bcd399aa087f6e82a9353e883d004c50d92c9d5
[ "MIT" ]
9
2021-03-14T05:49:21.000Z
2021-12-13T12:46:00.000Z
src/Window.cpp
lintopher0315/gadget
9bcd399aa087f6e82a9353e883d004c50d92c9d5
[ "MIT" ]
null
null
null
src/Window.cpp
lintopher0315/gadget
9bcd399aa087f6e82a9353e883d004c50d92c9d5
[ "MIT" ]
null
null
null
#include "Window.h" #include "Frame.h" #include "FileHelper.h" Window::Window(wxWindow *parent) : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize) { SetMinClientSize(wxSize(500, 100)); sizer = new wxBoxSizer(wxVERTICAL); panel = new Panel(this); statusBar = new StatusBar(this); commandBar = new CommandBar(this); sizer->Add(panel, 1, wxEXPAND | wxALL, 0); sizer->Add(statusBar, 0, wxEXPAND | wxALL, -3); sizer->Add(commandBar, 0, wxEXPAND | wxALL, 0); SetSizer(sizer); command = new Command(); mode = NORMAL_MODE; currEditor = 0; lastCopiedMode = EDIT_MODE; } Frame *Window::getFrame(void) const { return (Frame *)GetParent(); } Editor *Window::getCurrentEditor(void) const { return (Editor *)panel->GetPage(currEditor); } void Window::executeNormal(const int& cmdInd) { switch(cmdInd) { case 0: doInsertion(); break; case 1: doBasicMovement(); break; case 2: doNewLine(); break; case 3: doIntraLineJump(); break; case 4: doInterLineJump(); break; case 5: doTabChange(); break; case 6: doWordJump(); break; case 7: doCharSearch(); break; case 8: doVisualMode(); break; case 9: doLineMode(); break; case 10: doPaste(); break; case 11: doVisOrLineOrNormalDelete(); break; case 12: doLineCut(); break; } command->clear(); commandBar->Clear(); updateStatus(); } void Window::executeCommand(const int& cmdInd) { switch(cmdInd) { case 0: doQuitFile(); break; case 1: doSaveFile(); break; case 2: doOpenFile(); break; case 3: doNewTab(); break; case 4: doSplitTab(); break; case 5: doOpenHelpFile(); break; } command->clear(); commandBar->Clear(); updateStatus(); } void Window::executeVisual(const int& cmdInd) { switch(cmdInd) { case 0: doBasicVisMovement(); break; case 1: doVisOrLineOrNormalDelete(); break; case 2: doVisOrLineCaseChange(); break; case 3: doVisInterLineJump(); break; case 4: doVisOrLineCopy(); break; case 5: doVisWordJump(); break; case 6: doVisIntraLineJump(); break; case 7: doVisCharSearch(); break; } command->clear(); commandBar->Clear(); updateStatus(); } void Window::executeLine(const int& cmdInd) { switch(cmdInd) { case 0: doBasicLineMovement(); break; case 1: doVisOrLineOrNormalDelete(); break; case 2: doVisOrLineCaseChange(); break; case 3: doLineShift(); break; case 4: doVisOrLineCopy(); break; case 5: doLineInterLineJump(); break; } command->clear(); commandBar->Clear(); updateStatus(); } void Window::doInsertion(void) { Editor *e = getCurrentEditor(); mode = EDIT_MODE; if (command->cmd == "a") { e->append(); } else if (command->cmd == "A") { e->LineEnd(); } else if (command->cmd == "I") { e->VCHome(); } } void Window::doBasicMovement(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "h") { e->caretLeft(parsedCmd.first); } else if (parsedCmd.second == "j") { e->caretDown(parsedCmd.first); } else if (parsedCmd.second == "k") { e->caretUp(parsedCmd.first); } else if (parsedCmd.second == "l") { e->caretRight(parsedCmd.first); } } void Window::doNewLine(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "o") { e->insertLineBelow(parsedCmd.first); } else if (parsedCmd.second == "O") { e->insertLineAbove(parsedCmd.first); } } void Window::doIntraLineJump(void) { Editor *e = getCurrentEditor(); if (command->cmd == "_") { e->VCHome(); } else if (command->cmd == "$") { e->LineEnd(); e->caretLeft(1); } else if (command->cmd == "0") { e->Home(); } } void Window::doInterLineJump(void) { Editor *e = getCurrentEditor(); if (command->cmd == "gg") { e->GotoLine(0); } else if (command->cmd == "G") { e->GotoLine(e->GetLineCount() - 1); } else { std::pair<int, std::string> parsedCmd = command->parseNormal(); e->GotoLine(parsedCmd.first - 1); } } void Window::doTabChange(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); if (parsedCmd.first != panel->GetSelection() + 1) { panel->setTab(parsedCmd.first); } } void Window::doWordJump(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "w") { e->wordRight(parsedCmd.first); } else { e->wordLeft(parsedCmd.first); } } void Window::doCharSearch(void) { Editor *e = getCurrentEditor(); if (command->cmd[0] == 'f') { e->charSearchAhead(command->cmd[1], 1); } else if (command->cmd[0] == 'F') { e->charSearchBehind(command->cmd[1], 1); } else if (command->cmd[0] == 't') { e->charSearchAhead(command->cmd[1], 0); } else if (command->cmd[0] == 'T') { e->charSearchBehind(command->cmd[1], 0); } } void Window::doVisualMode(void) { mode = VISUAL_MODE; } void Window::doLineMode(void) { Editor *e = getCurrentEditor(); mode = LINE_MODE; e->SetAnchor(e->lineStartPos()); e->SetCurrentPos(e->lineEndPos()); } void Window::doPaste(void) { Editor *e = getCurrentEditor(); if (lastCopiedMode == EDIT_MODE) { return; } if (lastCopiedMode == VISUAL_MODE || lastCopiedMode == NORMAL_MODE) { if (command->cmd == "p") { e->CharRight(); } e->Paste(); } else if (lastCopiedMode == LINE_MODE) { if (command->cmd == "P") { e->Home(); e->NewLine(); e->caretUp(1); e->Paste(); } else if (command->cmd == "p") { e->LineEnd(); e->NewLine(); e->Paste(); } std::string line = std::string(e->GetCurLine().mb_str()); if (line.empty() || line == "\n") { e->DeleteBack(); } e->VCHome(); } } void Window::doLineCut(void) { Editor *e = getCurrentEditor(); if (command->cmd == "D") { e->cutToLineEnd(); lastCopiedMode = NORMAL_MODE; } else { std::pair<int, std::string> parsedCmd = command->parseNormal(); e->cutLines(parsedCmd.first); lastCopiedMode = LINE_MODE; } mode = NORMAL_MODE; } void Window::doQuitFile(void) { // later: check if curr editor saved before exiting panel->deleteCurr(); } void Window::doSaveFile(void) { std::vector<std::string> parsedCmd = command->parseCommand(); Editor *e = getCurrentEditor(); if (parsedCmd.size() == 1) { if (e->relPath == "") { // later this should display an error: editor has no file return; } } else { if (FileHelper::isValidPath(getFrame()->cwd, parsedCmd[1])) { e->relPath = parsedCmd[1]; panel->SetPageText(currEditor, parsedCmd[1]); } else { // also display error return; } } if (FileHelper::isValidPath(getFrame()->cwd, e->relPath)) { if (!FileHelper::isExistingPath(getFrame()->cwd, e->relPath)) { // reload file tree e->SaveFile(getFrame()->cwd + e->relPath); getFrame()->tree->reloadTree(); } else { e->SaveFile(getFrame()->cwd + e->relPath); } e->saved = true; } if (parsedCmd[0] == "wq") { panel->deleteCurr(); } } void Window::doOpenFile(void) { std::vector<std::string> parsedCmd = command->parseCommand(); Editor *e = getCurrentEditor(); // later: check if curr editor saved before replacing if (FileHelper::isValidPath(getFrame()->cwd, parsedCmd[1])) { e->relPath = parsedCmd[1]; panel->SetPageText(currEditor, parsedCmd[1]); e->SetEditable(true); e->SetReadOnly(false); e->ClearAll(); int lexer = FileHelper::getLexerFromExtension(e->relPath); e->applyLexer(lexer); if (FileHelper::isExistingPath(getFrame()->cwd, parsedCmd[1])) { e->loadFormatted(getFrame()->cwd + e->relPath); if (FileHelper::isReadOnlyFile(getFrame()->cwd, e->relPath)) { e->SetEditable(false); e->SetReadOnly(true); e->readOnly = true; } else { e->readOnly = false; } e->saved = true; } // else indicate that it's a new file } } void Window::doNewTab(void) { std::vector<std::string> parsedCmd = command->parseCommand(); if (parsedCmd.size() == 1) { panel->AddPage(new Editor(panel, NULL_LEX), "[NO FILE]", true); return; } for (int i = 1; i < parsedCmd.size(); ++i) { if (!FileHelper::isValidPath(getFrame()->cwd, parsedCmd[i])) { continue; } int lexer = FileHelper::getLexerFromExtension(parsedCmd[i]); panel->AddPage(new Editor(panel, lexer), parsedCmd[i], true); Editor *e = getCurrentEditor(); e->relPath = parsedCmd[i]; if (FileHelper::isExistingPath(getFrame()->cwd, parsedCmd[i])) { e->loadFormatted(getFrame()->cwd + e->relPath); if (FileHelper::isReadOnlyFile(getFrame()->cwd, e->relPath)) { e->SetEditable(false); e->SetReadOnly(true); e->readOnly = true; } else { e->readOnly = false; } e->saved = true; } } } void Window::doSplitTab(void) { if (command->cmd == "split") { panel->Split(currEditor, wxBOTTOM); } else { panel->Split(currEditor, wxRIGHT); } } void Window::doOpenHelpFile(void) { panel->AddPage(new HelpFile(panel), "Help", true); } void Window::doBasicVisMovement(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "h") { e->caretLeftVis(parsedCmd.first); } else if (parsedCmd.second == "j") { e->caretDownVis(parsedCmd.first); } else if (parsedCmd.second == "k") { e->caretUpVis(parsedCmd.first); } else if (parsedCmd.second == "l") { e->caretRightVis(parsedCmd.first); } } void Window::doVisOrLineOrNormalDelete(void) { Editor *e = getCurrentEditor(); lastCopiedMode = mode; e->cutSelection(); mode = NORMAL_MODE; } void Window::doVisOrLineCaseChange(void) { Editor *e = getCurrentEditor(); if (command->cmd == "u") { e->caseChangeSelection(false); } else if (command->cmd == "U") { e->caseChangeSelection(true); } e->removeSelection(); mode = NORMAL_MODE; } void Window::doVisInterLineJump(void) { Editor *e = getCurrentEditor(); if (command->cmd == "gg") { e->jumpStartVis(); } else if (command->cmd == "G") { e->jumpEndVis(); } else { std::pair<int, std::string> parsedCmd = command->parseNormal(); e->jumpLineVis(parsedCmd.first - 1); } } void Window::doVisOrLineCopy(void) { Editor *e = getCurrentEditor(); lastCopiedMode = mode; e->copySelection(); e->removeSelection(); mode = NORMAL_MODE; } void Window::doVisWordJump(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "w") { e->wordRightVis(parsedCmd.first); } else { e->wordLeftVis(parsedCmd.first); } } void Window::doVisIntraLineJump(void) { Editor *e = getCurrentEditor(); if (command->cmd == "_") { e->lineHomeVis(); } else if (command->cmd == "$") { e->lineEndVis(); } else if (command->cmd == "0") { e->lineStartVis(); } } void Window::doVisCharSearch(void) { Editor *e = getCurrentEditor(); if (command->cmd[0] == 'f') { e->charSearchAheadVis(command->cmd[1], 1); } else if (command->cmd[0] == 'F') { e->charSearchBehindVis(command->cmd[1], 1); } else if (command->cmd[0] == 't') { e->charSearchAheadVis(command->cmd[1], 0); } else if (command->cmd[0] == 'T') { e->charSearchBehindVis(command->cmd[1], 0); } } void Window::doBasicLineMovement(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "j") { e->caretDownLine(parsedCmd.first); } else if (parsedCmd.second == "k") { e->caretUpLine(parsedCmd.first); } } void Window::doLineShift(void) { std::pair<int, std::string> parsedCmd = command->parseNormal(); Editor *e = getCurrentEditor(); if (parsedCmd.second == "<") { e->shiftLine(parsedCmd.first, 0); } else if (parsedCmd.second == ">") { e->shiftLine(parsedCmd.first, 1); } e->removeSelection(); mode = NORMAL_MODE; } void Window::doLineInterLineJump(void) { Editor *e = getCurrentEditor(); if (command->cmd == "gg") { e->jumpStartLine(); } else if (command->cmd == "G") { e->jumpEndLine(); } else { std::pair<int, std::string> parsedCmd = command->parseNormal(); e->jumpLineLine(parsedCmd.first - 1); } } void Window::updateStatus(void) { if (panel->GetPageCount() == 0) { return; } Editor *e = getCurrentEditor(); if (mode == NORMAL_MODE) { statusBar->modeDisplay->setText(" ~NORMAL~"); statusBar->modeDisplay->setBackground(wxColour(219, 131, 0)); e->SetCaretForeground(wxColour(219, 131, 0)); } else if (mode == EDIT_MODE) { statusBar->modeDisplay->setText(" ~EDIT~"); statusBar->modeDisplay->setBackground(wxColour(120, 161, 109)); e->SetCaretForeground(wxColour(120, 161, 109)); } else if (mode == VISUAL_MODE) { statusBar->modeDisplay->setText(" ~VISUAL~"); statusBar->modeDisplay->setBackground(wxColour(147, 196, 82)); e->SetCaretForeground(wxColour(147, 196, 82)); } else if (mode == LINE_MODE) { statusBar->modeDisplay->setText(" ~LINE~"); statusBar->modeDisplay->setBackground(wxColour(222, 149, 222)); e->SetCaretForeground(wxColour(222, 149, 222)); } if (e->relPath == "") { statusBar->pathDisplay->setText("[NO FILE]"); statusBar->pathDisplay->setForeground(wxColour(227, 11, 11)); statusBar->pathDisplay->setBackground(wxColour(214, 141, 141)); } else { std::string pathText = getFrame()->cwd + e->relPath; std::string panelText = std::string(panel->GetPageText(currEditor).mb_str()); if (!e->saved) { pathText += "***"; statusBar->pathDisplay->setForeground(wxColour(82, 7, 7)); statusBar->pathDisplay->setBackground(wxColour(214, 141, 141)); statusBar->pathDisplay->BeginBold(); statusBar->pathDisplay->setText(pathText); statusBar->pathDisplay->EndBold(); if (panelText[0] != '*') { panel->SetPageText(currEditor, "*" + panelText); } } else { statusBar->pathDisplay->setForeground(wxColour(82, 7, 7)); statusBar->pathDisplay->setBackground(wxColour(214, 141, 141)); statusBar->pathDisplay->setText(pathText); if (panelText[0] == '*') { panel->SetPageText(currEditor, panelText.substr(1, panelText.size()-1)); } } if (e->readOnly) { statusBar->pathDisplay->AppendText(" [R]"); } } int curr = e->currLine() + 1; int len = e->GetLineCount(); int percent = (int)((double)curr * 100 / len); statusBar->positionDisplay->setText(std::to_string(curr) + "," + std::to_string(e->linePos() + 1) + " | " + std::to_string(percent) + "%"); wxColour colour = statusBar->positionDisplay->getForeground(); colour.Set(255 - (int)((double)percent * 2.55), 12, 174 - (int)((double)percent * 1.7)); statusBar->positionDisplay->setForeground(colour); statusBar->sizeDisplay->setText(std::to_string(e->GetLength()) + " bytes | " + std::to_string(len) + " lines"); }
22.299107
140
0.630764
lintopher0315
71822d5fc3114e6d14285b01a710e83ed9738d73
1,579
cpp
C++
01-Array/03-Kth-max-min.cpp
satputesagar/450-Coding-Question
1fc3f00756090e079aa591d1ad1c0b5992e5e9c7
[ "MIT" ]
null
null
null
01-Array/03-Kth-max-min.cpp
satputesagar/450-Coding-Question
1fc3f00756090e079aa591d1ad1c0b5992e5e9c7
[ "MIT" ]
null
null
null
01-Array/03-Kth-max-min.cpp
satputesagar/450-Coding-Question
1fc3f00756090e079aa591d1ad1c0b5992e5e9c7
[ "MIT" ]
null
null
null
//Kth smallest element /* Given an array arr[] and a number K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct. /* COMPLEXITY - O(n) SAMPLE INPUT 2 6 7 10 4 3 20 15 3 5 7 10 4 20 15 4 OUTPUT 7 15 */ /* Complexity : O(n^2) int kthSmallest(int arr[], int l, int r, int k) { //code here int temp; for(int i=0; i<k; i++) { for(int j=i+1; j<r+1 && i<r; j++) { if(arr[j]<arr[i]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } return arr[k-1]; } */ //complexity: O(nlogn) #include<bits/stdc++.h> using namespace std; int kthSmallest(int *, int, int, int); int main() { // ios_base::sync_with_stdio(false); // cin.tie(NULL); int test_case; cin>>test_case; while(test_case--) { int number_of_elements; cin>>number_of_elements; int a[number_of_elements]; for(int i=0;i<number_of_elements;i++) cin>>a[i]; int k; cin>>k; cout<<kthSmallest(a, 0, number_of_elements-1, k)<<endl; } return 0; }// } Driver Code Ends //User function template for C++ // arr : given array // l : starting index of the array i.e 0 // r : ending index of the array i.e size-1 // k : find kth smallest element and return using this function int kthSmallest(int arr[], int l, int r, int k) { sort(arr, arr + r+1); return arr[k-1]; }
19.024096
189
0.552248
satputesagar
71886609110068a50145e918b8650e1fa1e90b77
1,996
cpp
C++
Examples/Primes/LibPrimes_component/Implementations/Cpp/Stub/libprimes_sievecalculator.cpp
tristanbarback/AutomaticComponentToolkit
8fe5406a06c5bcec87a1ebb025cb92ee30bc11bd
[ "BSD-2-Clause" ]
null
null
null
Examples/Primes/LibPrimes_component/Implementations/Cpp/Stub/libprimes_sievecalculator.cpp
tristanbarback/AutomaticComponentToolkit
8fe5406a06c5bcec87a1ebb025cb92ee30bc11bd
[ "BSD-2-Clause" ]
null
null
null
Examples/Primes/LibPrimes_component/Implementations/Cpp/Stub/libprimes_sievecalculator.cpp
tristanbarback/AutomaticComponentToolkit
8fe5406a06c5bcec87a1ebb025cb92ee30bc11bd
[ "BSD-2-Clause" ]
null
null
null
/*++ Copyright (C) 2018 Automatic Component Toolkit Developers All rights reserved. Abstract: This is a stub class definition of CLibPrimesSieveCalculator */ #include "libprimes_sievecalculator.hpp" #include "libprimes_interfaceexception.hpp" // Include custom headers here. #include <cmath> using namespace LibPrimes; /************************************************************************************************************************* Class definition of CLibPrimesSieveCalculator **************************************************************************************************************************/ void CLibPrimesSieveCalculator::Calculate() { primes.clear(); std::vector<bool> strikenOut(m_value + 1); for (LibPrimes_uint64 i = 0; i <= m_value; i++) { strikenOut[i] = i < 2; } LibPrimes_uint64 sqrtValue = (LibPrimes_uint64)(std::sqrt(m_value)); int progressStep = (int)std::ceil(sqrtValue / 20.0f); for (LibPrimes_uint64 i = 2; i <= sqrtValue; i++) { if (m_Callback) { if (i % progressStep == 0) { bool shouldAbort = false; (*m_Callback)(float(i) / sqrtValue, &shouldAbort); if (shouldAbort) { throw ELibPrimesInterfaceException(LIBPRIMES_ERROR_CALCULATIONABORTED); } } } if (!strikenOut[i]) { primes.push_back(i); for (LibPrimes_uint64 j = i * i; j < m_value; j += i) { strikenOut[j] = true; } } } for (LibPrimes_uint64 i = sqrtValue; i <= m_value; i++) { if (!strikenOut[i]) { primes.push_back(i); } } } void CLibPrimesSieveCalculator::GetPrimes (LibPrimes_uint64 nPrimesBufferSize, LibPrimes_uint64 * pPrimesNeededCount, LibPrimes_uint64 * pPrimesBuffer) { if (primes.size() == 0) throw ELibPrimesInterfaceException(LIBPRIMES_ERROR_NORESULTAVAILABLE); if (pPrimesNeededCount) *pPrimesNeededCount = (unsigned int)primes.size(); if (nPrimesBufferSize >= primes.size() && pPrimesBuffer) { for (size_t i = 0; i < primes.size(); i++) { pPrimesBuffer[i] = primes[i]; } } }
24.341463
151
0.608216
tristanbarback
718ddf1c9f0eb61a1a7155b13e2a1b33e1023e6b
7,065
cpp
C++
src/NodeHive.cpp
dwarfofdawn/Ant_Game
3a4ea222d5ae9fea991e7e5cf5063ea9fcec9906
[ "MIT" ]
null
null
null
src/NodeHive.cpp
dwarfofdawn/Ant_Game
3a4ea222d5ae9fea991e7e5cf5063ea9fcec9906
[ "MIT" ]
null
null
null
src/NodeHive.cpp
dwarfofdawn/Ant_Game
3a4ea222d5ae9fea991e7e5cf5063ea9fcec9906
[ "MIT" ]
null
null
null
#include "NodeHive.h" #include "warp/Renderer.h" #include "WorldClient.h" #include "TaskConquer.h" #include "Options.h" #include "Client.h" #include "Server.h" #include <cstring> #include <cmath> namespace ant{ warp::Color hiveColor(1, 0, 0, 1); // controls spead of heartbeat TODO(florian): make this dynamic and hive based const int bpm = 90; const int heartbeatCycle = 60000 / bpm; NodeHive::NodeHive(int x, int y, int owner, bool onServer) : Node(x, y, onServer), spawnCounter(1000), owner(owner), freeJobs(0), numWorkers(0), pulseTimer(0){ setInteresting(true); setDeletable(false); setResourceMaxAll(10000); setResourceMaxTotal(500); storeResource(0, 100); } NodeHive::NodeHive(int x, int y, int id, int owner, bool onServer) : Node(x, y, id, onServer), spawnCounter(1000), owner(owner), freeJobs(0), numWorkers(0), pulseTimer(0){ setInteresting(true); setDeletable(false); setResourceMaxAll(10000); setResourceMaxTotal(500); storeResource(0, 100); } NodeHive::~NodeHive(){ } void NodeHive::render(){ // warp::drawRect(getX(), getY(), 2500, 2500, 0, hiveColor); Node::render(); // warp::drawCircle(getX(), getY(), 150 * getPercentageFullTotal() + 100, hiveColor); warp::drawSprite(getX(), getY(), 300 * getPercentageFullTotal() + 200 + 50 * pulseRenderValue, 300 * getPercentageFullTotal() + 200 + 50 * pulseRenderValue, 0, "steampunk_heart1"); } void NodeHive::produceAnt(){ int effects[options::getNumResourceEffects()]; std::memset(effects, 0, sizeof(int) * options::getNumResourceEffects()); bool usedResources[NUM_RESOURCES]; int numResources = 0; for(int i = 0; i < NUM_RESOURCES; i++){ usedResources[i] = false; } int cost = options::getAntCost(); for(int i = 0; i < NUM_RESOURCES; i++){ if(!usedResources[i]){ if(hasResource(i, cost)){ for(int j = 0; j < options::getNumResourceEffects(); j++){ effects[j] += options::getRessourceEffectMatrix(i)[j]; } usedResources[i] = true; numResources ++; if(numResources > 1){ cost -= options::getCombinedRessourceCostReduction(); i = 0; } } } } if(numResources > 0){ for(int i = 0; i < NUM_RESOURCES; i++){ getResources(i, cost); } Ant *a = new Ant(getX(), getY(), world::getNewAntId()); a->setCurrentNode(this); /*printf("current effect matrix: %d %d %d %d %d %d %d %d %d %d %d\n", effects[0], effects[1], effects[2], effects[3], effects[4], effects[5], effects[6], effects[7], effects[8], effects[9], effects[10]); TODO decide what to do with the effect code spawnCounter -= effects[0]; a->setLifetime(options::getAntLifetime() + effects[1]); a->setStrength(options::getAntStrength() + effects[2]); a->setAbility(CONQUER, effects[3] == 0); a->setSpeed(options::getAntSpeed() + effects[4]); a->setAbility(CONSTRUCTION, effects[5] == 0); a->setRallySpeedBonus(effects[6]); a->setConqueringPower(options::getAntConqueringPower() + (effects[7] > 0 ? options::getConqueringThreshold() : 0)); a->setAbility(ECONOMY, effects[8] == 0); a->setHarvestTimeReduction(effects[9]); a->setAbility(MILITARY, effects[10] == 0);*/ world::spawnAnt(a); } } void NodeHive::updateConqueringProgressBy(int player, int amount){ if(conqueringProcess.find(player) == conqueringProcess.end()){ conqueringProcess[player] = 0; } conqueringProcess[player] += amount; for(auto a : conqueringProcess){ if(a.first != player){ conqueringProcess[a.first] -= amount; if(conqueringProcess[a.first] < 0){ conqueringProcess[a.first] = 0; } } } if(conqueringProcess[player] > options::getConqueringThreshold()){ conqueringProcess[player] = options::getConqueringThreshold(); if(owner != player){ owner = player; unsigned char data[8]; writeIntToBuffer(getId(), data, 0); writeIntToBuffer(player, data, 4); server::broadcastPacket(NODE_HIVE_CONQUERED, data, 8); } } } void NodeHive::update(float updateFactor){ if(owner == world::getPlayerId() && !onServer){ if(spawnCounter > 0){ spawnCounter -= updateFactor * 1000; } else{ spawnCounter = 0; if(getAntCounter() < 5000){ produceAnt(); } spawnCounter += options::getAntSpawnCooldown(); } } Node::update(updateFactor); pulseTimer += updateFactor * 1000; pulseValue = pulseTimer > heartbeatCycle / 2 ? 0.3398 : (1 - pow(pulseTimer / (heartbeatCycle / 4.0) - 1, 2) + 0.3398); pulseRenderValue = ((pulseTimer + heartbeatCycle / 4) % heartbeatCycle) > heartbeatCycle / 2 ? 0.3398 : (1 - pow(((pulseTimer + heartbeatCycle / 4) % heartbeatCycle) / (heartbeatCycle / 4.0) - 1, 2) + 0.3398); //pulseValue = pulseTimer < 500 ? 1 - pow(pulseTimer / 250.0 - 1, 2) : pulseTimer > 750 && pulseTimer < 1250 ? 1 - pow((pulseTimer - 750) / 250.0 - 1, 2) : 0; pulseTimer %= heartbeatCycle; } int NodeHive::getCreationPacketSize(){ return 12; } void NodeHive::writeCreationPacket(unsigned char *buff){ writeIntToBuffer(getX(), buff, 0); writeIntToBuffer(getY(), buff, 4); writeIntToBuffer(getId(), buff, 8); } void NodeHive::updatePathTo(Node *goal, int dist){ Node::updatePathTo(goal, dist); if(goal == world::getMainHive()){ updateTaskState(); } } void NodeHive::updateTaskState(){ if(freeJobs < 1 && numWorkers < options::getConqueringThreshold() && owner != world::getPlayerId() && getDirectionTo(world::getMainHive()) != NULL){ TaskConquer *t = new TaskConquer(this); t->setStart(this); world::addTask(t); } } void NodeHive::onTaskAccepted(Task *t){ if(t->getType() == CONQUER){ freeJobs --; numWorkers ++; updateTaskState(); } Node::onTaskAccepted(t); } void NodeHive::onTaskAborted(Task *t){ if(t->getType() == CONQUER ){ if(t->getState() == 0){ freeJobs ++; } numWorkers --; } Node::onTaskAborted(t); } void NodeHive::onTaskFinished(Task *t){ if(t->getType() == CONQUER){ unsigned char data[9]; writeIntToBuffer(getId(), data, 0); writeIntToBuffer(world::getPlayerId(), data, 4); data[8] = t->getServant()->getConqueringPower(); client::sendPacket(NODE_HIVE_CONQUERING, data, 9); numWorkers --; } Node::onTaskFinished(t); } PACKET_TYPE NodeHive::getCreationPacketType(){ return NEW_NODE_HIVE; } NodeHive *createNodeHiveFromPacket(unsigned char *buff){ return new NodeHive(readIntFromBuffer(buff, 0), readIntFromBuffer(buff, 4), readIntFromBuffer(buff, 8), false, false); } void NodeHive::setOwner(int i){ owner = i; } float NodeHive::getPulseStrength() { return pulseValue; } }
31.681614
253
0.618117
dwarfofdawn
718f95d0b00bda03156101f80b3cc958c7df7480
330
hpp
C++
lib/inc/pxp-agent/action_output.hpp
Dorin-Pleava/pxp-agent
eef236da8046fc185e0ca39d0a479cf00b9c60ad
[ "Apache-2.0" ]
28
2015-10-09T04:48:31.000Z
2022-01-31T15:04:01.000Z
lib/inc/pxp-agent/action_output.hpp
Dorin-Pleava/pxp-agent
eef236da8046fc185e0ca39d0a479cf00b9c60ad
[ "Apache-2.0" ]
495
2015-10-05T18:47:47.000Z
2021-11-01T23:40:01.000Z
lib/inc/pxp-agent/action_output.hpp
Dorin-Pleava/pxp-agent
eef236da8046fc185e0ca39d0a479cf00b9c60ad
[ "Apache-2.0" ]
67
2015-10-06T03:28:16.000Z
2022-03-31T17:25:37.000Z
#ifndef SRC_AGENT_ACTION_OUTPUT_HPP #define SRC_AGENT_ACTION_OUTPUT_HPP #include <leatherman/json_container/json_container.hpp> #include <string> namespace PXPAgent { struct ActionOutput { int exitcode; std::string std_out; std::string std_err; }; } // namespace PXPAgent #endif // SRC_AGENT_ACTION_OUTPUT_HPP
17.368421
55
0.769697
Dorin-Pleava
718fc3bff445a4885e244a44e7a9f9a7c85dcc8f
2,447
hpp
C++
include/ads/basis_data.hpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
7
2018-01-19T00:19:19.000Z
2021-06-22T00:53:00.000Z
include/ads/basis_data.hpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
66
2021-06-22T22:44:21.000Z
2022-03-16T15:18:00.000Z
include/ads/basis_data.hpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
6
2017-04-13T19:42:27.000Z
2022-03-26T18:46:24.000Z
// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com> // SPDX-License-Identifier: MIT #ifndef ADS_BASIS_DATA_HPP #define ADS_BASIS_DATA_HPP #include <utility> #include <vector> #include <boost/range/counting_range.hpp> #include "ads/bspline/bspline.hpp" namespace ads { using element_id = int; using dof_id = int; // TODO: use proper multidimensional arrays // NOLINTNEXTLINE(cppcoreguidelines-special-member-functions, hicpp-special-member-functions) struct basis_data { using range_type = decltype(boost::counting_range(0, 0)); std::vector<int> first_dofs; std::vector<std::pair<int, int>> element_ranges; int degree; int elements; int dofs; int derivatives; int quad_order; int elem_division; std::vector<double> points; bspline::basis basis; double**** b; double** x; const double* w; double* J; ~basis_data(); basis_data(const basis_data& other); basis_data& operator=(const basis_data& other) { auto tmp = other; swap(*this, tmp); return *this; } basis_data(bspline::basis basis, int derivatives) : basis_data{std::move(basis), derivatives, basis.degree + 1, 1} { } basis_data(bspline::basis basis, int derivatives, int quad_order, int elem_division); int first_dof(element_id e) const { return first_dofs[e / elem_division]; } int last_dof(element_id e) const { return first_dof(e) + dofs_per_element() - 1; } int dofs_per_element() const { return degree + 1; } range_type dof_range(element_id e) const { return boost::counting_range(first_dof(e), last_dof(e) + 1); } range_type element_range(dof_id dof) const { return boost::counting_range(element_ranges[dof].first, element_ranges[dof].second + 1); } friend void swap(basis_data& a, basis_data& b) noexcept { using std::swap; swap(a.first_dofs, b.first_dofs); swap(a.element_ranges, b.element_ranges); swap(a.degree, b.degree); swap(a.elements, b.elements); swap(a.dofs, b.dofs); swap(a.derivatives, b.derivatives); swap(a.quad_order, b.quad_order); swap(a.elem_division, b.elem_division); swap(a.points, b.points); swap(a.basis, b.basis); swap(a.b, b.b); swap(a.x, b.x); swap(a.w, b.w); swap(a.J, b.J); } }; } // namespace ads #endif // ADS_BASIS_DATA_HPP
26.89011
96
0.655088
Pan-Maciek
719120079fa53295a9123dd95107cdf7de7a5185
6,114
cpp
C++
Tests/CPP_Bindings/Source/TextureProperty.cpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
171
2015-04-30T21:54:02.000Z
2022-03-13T13:33:59.000Z
Tests/CPP_Bindings/Source/TextureProperty.cpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
190
2015-07-21T22:15:54.000Z
2022-03-30T15:48:37.000Z
Tests/CPP_Bindings/Source/TextureProperty.cpp
alexanderoster/lib3mf
30d5c2e0e8ed7febb5c10a84dc2db9d53fee6d05
[ "BSD-2-Clause" ]
80
2015-04-30T22:15:54.000Z
2022-03-09T12:38:49.000Z
/*++ Copyright (C) 2019 3MF Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Abstract: UnitTest_TextureProperties.cpp: Defines Unittests for texture properties --*/ #include "UnitTest_Utilities.h" #include "lib3mf_implicit.hpp" namespace Lib3MF { class TextureProperty : public Lib3MFTest { protected: virtual void SetUp() { model = wrapper->CreateModel(); std::vector<sPosition> vctVertices; std::vector<sTriangle> vctTriangles; fnCreateBox(vctVertices, vctTriangles); mesh = model->AddMeshObject(); mesh->SetGeometry(vctVertices, vctTriangles); model->AddBuildItem(mesh.get(), getIdentityTransform()); std::string sRelationshipType_Texture = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"; std::string sPath_Texture = "/3D/Textures/MyTexture.png"; textureAttachment = model->AddAttachment(sPath_Texture, sRelationshipType_Texture); textureAttachment->ReadFromFile(sTestFilesPath + "Textures/tex1.png"); texture2D = model->AddTexture2DFromAttachment(textureAttachment.get()); } virtual void TearDown() { model.reset(); } PModel model; PMeshObject mesh; PAttachment textureAttachment; PTexture2D texture2D; }; TEST_F(TextureProperty, SetGet_Texture2DGroup) { std::vector<sTex2Coord> coords(0); auto texture2DGroup = model->AddTexture2DGroup(texture2D.get()); std::vector<sTriangleProperties> properties(mesh->GetTriangleCount()); for (size_t i = 0; i < mesh->GetTriangleCount(); i++) { properties[i].m_ResourceID = texture2DGroup->GetResourceID(); coords.push_back({ 1.0*i / mesh->GetTriangleCount(), 1.0 - 1.0*i / mesh->GetTriangleCount() }); properties[i].m_PropertyIDs[0] = texture2DGroup->AddTex2Coord(coords.rbegin()[0]); coords.push_back({ 1.0*((uint64_t) i + 1) / mesh->GetTriangleCount(), 1.0 - 1.0*i / mesh->GetTriangleCount() }); properties[i].m_PropertyIDs[1] = texture2DGroup->AddTex2Coord(coords.rbegin()[0]); coords.push_back({ 1.0*i / mesh->GetTriangleCount(), 1.0 - 1.0*((uint64_t)i + 1) / mesh->GetTriangleCount() }); properties[i].m_PropertyIDs[2] = texture2DGroup->AddTex2Coord(coords.rbegin()[0]); } mesh->SetAllTriangleProperties(properties); std::vector<sTriangleProperties> obtainedProperties; mesh->GetAllTriangleProperties(obtainedProperties); int count = 0; for (size_t i = 0; i < mesh->GetTriangleCount(); i++) { EXPECT_EQ(obtainedProperties[i].m_ResourceID, properties[i].m_ResourceID); for (size_t j = 0; j < 3; j++) { EXPECT_EQ(obtainedProperties[i].m_PropertyIDs[j], properties[i].m_PropertyIDs[j]); } sTriangleProperties currentProperty; mesh->GetTriangleProperties(Lib3MF_uint32(i), currentProperty); auto currentTexture2DGroup = model->GetTexture2DGroupByID(currentProperty.m_ResourceID); EXPECT_EQ(currentProperty.m_ResourceID, properties[i].m_ResourceID); for (size_t j = 0; j < 3; j++) { EXPECT_EQ(currentProperty.m_PropertyIDs[j], properties[i].m_PropertyIDs[j]); sTex2Coord uvcoord = currentTexture2DGroup->GetTex2Coord(currentProperty.m_PropertyIDs[j]); EXPECT_DOUBLE_EQ(uvcoord.m_U, coords[count].m_U); EXPECT_DOUBLE_EQ(uvcoord.m_V, coords[count++].m_V); } } std::vector<Lib3MF_uint32> properties2D; texture2DGroup->GetAllPropertyIDs(properties2D); } TEST_F(TextureProperty, WriteRead) { auto texture2DGroup = model->AddTexture2DGroup(texture2D.get()); std::vector<sTriangleProperties> properties(mesh->GetTriangleCount()); for (size_t i = 0; i < mesh->GetTriangleCount(); i++) { properties[i].m_ResourceID = texture2DGroup->GetResourceID(); properties[i].m_PropertyIDs[0] = texture2DGroup->AddTex2Coord({ 1.0*i / mesh->GetTriangleCount(), 1.0 - 1.0*i / mesh->GetTriangleCount() }); properties[i].m_PropertyIDs[1] = texture2DGroup->AddTex2Coord({ 1.0*(i + 1) / mesh->GetTriangleCount(), 1.0 - 1.0*i / mesh->GetTriangleCount() }); properties[i].m_PropertyIDs[2] = texture2DGroup->AddTex2Coord({ 1.0*i / mesh->GetTriangleCount(), 1.0 - 1.0*(i + 1) / mesh->GetTriangleCount() }); } mesh->SetAllTriangleProperties(properties); auto writer = model->QueryWriter("3mf"); std::vector<Lib3MF_uint8> buffer; writer->WriteToBuffer(buffer); // writer->WriteToFile("Texture_Out.3mf"); auto readModel = wrapper->CreateModel(); auto reader = readModel->QueryReader("3mf"); // reader->ReadFromFile("Texture_Out.3mf"); reader->ReadFromBuffer(buffer); int texture2DGroupCount = 0; auto iterator = readModel->GetTexture2DGroups(); while (iterator->MoveNext()) { auto texture2Dgroup = iterator->GetCurrentTexture2DGroup(); ASSERT_EQ(texture2Dgroup->GetCount(), properties.size()*3); texture2DGroupCount++; auto localTexture2D = texture2Dgroup->GetTexture2D(); ASSERT_EQ(localTexture2D->GetAttachment()->GetStreamSize(), texture2D->GetAttachment()->GetStreamSize()); } ASSERT_EQ(texture2DGroupCount, 1); } }
41.310811
149
0.74632
alexanderoster
719b2e2e242ac6050345a20260344dea8b72cd2d
3,633
cpp
C++
BFS/127. Word Ladder.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
BFS/127. Word Ladder.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
BFS/127. Word Ladder.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
/* 127. Word Ladder Time Space Difficulty O(n * d) O(d) Medium Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transformed word. For example, Given: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log","cog"] As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", return its length 5. Note: Return 0 if there is no such transformation sequence. All words have the same length. All words contain only lowercase alphabetic characters. You may assume no duplicates in the word list. You may assume beginWord and endWord are non-empty and are not the same. UPDATE (2017/1/20): The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes. */ class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string>unused(wordList.begin(),wordList.end()); queue<string>toVisit; int dist = 1; addWord(toVisit,beginWord,unused); while(toVisit.size()){ int cursize = toVisit.size(); for(int i = 0; i<cursize;i++){ string top = toVisit.front(); if(top == endWord) return dist+1; toVisit.pop(); addWord(toVisit,top,unused); } dist++; } return 0; } void addWord(queue<string>& toVisit, string word, unordered_set<string>& unused){ for(int j = 0; j<word.length(); j++){ for(int i = 0; i<26; i++){ string cur = word; char at = 'a'+i; if(at != word[j]){ cur[j] = at; if(unused.count(cur)>0){ unused.erase(cur); toVisit.push(cur); } } } } } }; class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& worddict) { unordered_set<string>head, tail, *phead, *ptail; unordered_set<string>wordDict(worddict.begin(),worddict.end()); head.insert(beginWord); if(wordDict.count(endWord)>0) tail.insert(endWord); int dist = 2; while(head.size() && tail.size()){ if(head.size()<tail.size()){ phead = &head; ptail = &tail; }else{ phead = &tail; ptail = &head; } unordered_set<string>temp; for(auto itr = phead->begin(); itr!= phead->end(); itr++){ string word = *itr; wordDict.erase(word); for(int p = 0; p<word.length(); p++){ char letter = word[p]; for(int k = 0; k<26; k++){ word[p] = 'a'+k; if(ptail->count(word)>0) return dist; if(wordDict.count(word)>0) { temp.insert(word); wordDict.erase(word); } } word[p] = letter; } } dist++; swap(*phead, temp); } return 0; } };
32.72973
161
0.504542
beckswu
719c060dc5ed31dfe4bad61ae6336adc82223860
4,318
cpp
C++
src/Instrument.cpp
devinacker/decomposer
32a7b5b5972ffe795bd56312c34a7bcc3283dd2d
[ "MIT" ]
6
2016-04-19T03:23:48.000Z
2019-07-12T00:40:23.000Z
src/Instrument.cpp
devinacker/decomposer
32a7b5b5972ffe795bd56312c34a7bcc3283dd2d
[ "MIT" ]
null
null
null
src/Instrument.cpp
devinacker/decomposer
32a7b5b5972ffe795bd56312c34a7bcc3283dd2d
[ "MIT" ]
null
null
null
#include "Instrument.h" Instrument* Instrument::channelInstruments[16] = {0}; void Instrument::send(int time, MIDIOutput *out, quint8 data0, quint8 data1, quint8 data2) { if (!out || channel > 15) return; // always play MIDI events on this instrument's channel if (data0 & 0x80) data0 = EVENT_REROUTE(data0, channel); checkInit(time, out); if (time >= 0) out->streamSend(time, data0, data1, data2); else out->send(data0, data1, data2); } // ------------------------------------------------------------------------------------------------ void Instrument::send(int time, MIDIOutput *out, const QByteArray &data) { if (!out || channel > 15) return; checkInit(time, out); if (time >= 0) out->streamSend(time, data); else out->send(data); } // ------------------------------------------------------------------------------------------------ void Instrument::sendRPN(int time, MIDIOutput *out, quint16 param, quint16 value) { if (!out || channel > 15) return; checkInit(time, out); if (time >= 0) out->streamSendRPN(time, channel, param, value); else out->sendRPN(channel, param, value); } // ------------------------------------------------------------------------------------------------ void Instrument::sendNRPN(int time, MIDIOutput *out, quint16 param, quint16 value) { if (!out || channel > 15) return; checkInit(time, out); if (time >= 0) out->streamSendNRPN(time, channel, param, value); else out->sendNRPN(channel, param, value); } // ------------------------------------------------------------------------------------------------ void Instrument::init(int time, MIDIOutput *out) { if (!out || channel > 15) return; channelInstruments[channel] = this; shouldReset = false; // controller reset this->send(time, out, EVENT_CONTROL(channel), CC_ALL_CONTROLLERS_OFF); if (time > 0) time = 0; // send program and bank this->send(time, out, EVENT_CONTROL(channel), CC_BANK_MSB, bank); this->send(time, out, EVENT_CONTROL(channel), CC_BANK_LSB, bankLSB); this->send(time, out, EVENT_PROGRAM(channel), program); // send pitch bend range this->sendRPN(time, out, RPN_PITCH_BEND_RANGE, bendRange * (1 << 7)); // center pitch wheel this->pitch(time, out, 0x2000); // send transpose/finetune double intPart; double decPart = modf(transpose, &intPart); this->sendRPN(time, out, RPN_MASTER_TUNE, (64 + (int)(intPart)) << 7); this->sendRPN(time, out, RPN_MASTER_FINETUNE, (64 + (int)(64 * decPart)) << 7); // init macros for (int i = 0; i < macros.size(); i++) { const InstrumentMacro &m = macros.at(i); this->macro(time, out, i, 0, m.init); } } // ------------------------------------------------------------------------------------------------ void Instrument::noteOn(int time, MIDIOutput *out, quint8 note, quint8 velocity) { if (velocity > 127) velocity = this->velocity; this->send(time, out, EVENT_NOTEON(channel), note, velocity); } // ------------------------------------------------------------------------------------------------ void Instrument::noteOff(int time, MIDIOutput *out, quint8 note, quint8 velocity) { if (velocity > 127) velocity = this->velocity; this->send(time, out, EVENT_NOTEOFF(channel), note, velocity); } // ------------------------------------------------------------------------------------------------ void Instrument::pitch(int time, MIDIOutput *out, quint16 value) { currentPitch = value; qint16 center = 81.92 * pitchCenter; if (value + center > 0x3FFF) value = 0x3FFF; else if (center < 0 && -center > value) value = 0; else value += center; this->send(time, out, EVENT_PITCH(channel), MIDI_LSB(value), MIDI_MSB(value)); } // ------------------------------------------------------------------------------------------------ void Instrument::macro(int time, MIDIOutput *out, uint num, quint8 note, quint16 param) { if (num >= (uint)macros.size()) return; InstrumentMacro &m = macros[num]; m.current = param; switch (m.type) { case InstrumentMacro::MacroCC: this->send(time, out, EVENT_CONTROL(channel), m.num, m.current); break; case InstrumentMacro::MacroNRPN: this->sendNRPN(time, out, m.num, m.current); break; case InstrumentMacro::MacroSysEx: { QByteArray data = m.formatSysEx(channel, param, note); this->send(time, out, data); } break; } }
26.9875
99
0.557202
devinacker
719e12ed749446677019364e9eda830d14cf36c2
2,578
cpp
C++
src/OctreeVisualization.cpp
Tsarpf/procgen
1701358649838fb3cc8804d3f1fcb6a8f74ad1bc
[ "WTFPL" ]
6
2019-11-13T07:42:34.000Z
2021-02-05T09:33:58.000Z
src/OctreeVisualization.cpp
Tsarpf/procgen
1701358649838fb3cc8804d3f1fcb6a8f74ad1bc
[ "WTFPL" ]
null
null
null
src/OctreeVisualization.cpp
Tsarpf/procgen
1701358649838fb3cc8804d3f1fcb6a8f74ad1bc
[ "WTFPL" ]
2
2019-11-13T07:37:22.000Z
2020-07-24T13:01:42.000Z
#include "OctreeVisualization.h" #include "Octree.h" #include "utils.h" #include <GL/glew.h> OctreeVisualization::OctreeVisualization(GLuint program) : m_program(program) { } OctreeVisualization::~OctreeVisualization() { } void OctreeVisualization::Initialize() { auto [vao, vbo] = createCubeVAO(m_cubePoints); m_vao = vao; m_vbo = vbo; } void OctreeVisualization::Build(const Octree* node) { OctreeVisualizationData stuff = { node->m_size, node->m_min }; m_visualizationData.push_back(stuff); const auto octreeChildren = node->GetChildren(); if (!octreeChildren) { return; } auto children = octreeChildren->children; for (const Octree* child : children) { if (child) { Build(child); } } } void OctreeVisualization::DrawVisualization(const float time) { glBindVertexArray(m_vao); glBindBuffer(GL_ARRAY_BUFFER, m_vbo); GLint posAttrib = glGetAttribLocation(m_program, "position"); glEnableVertexAttribArray(posAttrib); glVertexAttribPointer( posAttrib, // attribute 3, // number of elements per vertex, here (x,y,z) GL_FLOAT, GL_FALSE, m_stride * sizeof(float), 0 ); GLint colorAttrib = glGetAttribLocation(m_program, "inColor"); glEnableVertexAttribArray(colorAttrib); glVertexAttribPointer( colorAttrib, // attribute 3, // number of elements per vertex, here (R,G,B) GL_FLOAT, // the type of each element GL_FALSE, // take our values as-is m_stride * sizeof(float), // no extra data between each position (void*)(3 * sizeof(float)) // offset of first element ); //printf("draw visualization thing\n"); GLint modelUniform = glGetUniformLocation(m_program, "Model"); for (const auto& viz : m_visualizationData) { if (viz.size < 4) { continue; } glm::mat4 translate = glm::translate ( glm::mat4(1.0f), viz.min ); glm::mat4 rotate = glm::mat4(1.0f); rotate = glm::rotate( rotate, time * glm::radians(60.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 scale = glm::mat4(1.0f); scale[0] = glm::vec4(viz.size, 0, 0, 0); scale[1] = glm::vec4(0, viz.size, 0, 0); scale[2] = glm::vec4(0, 0, viz.size, 0); //this should be correct but isn't? //glUniformMatrix4fv(modelUniform, 1, GL_FALSE, glm::value_ptr(model * translate * rotate * scale)); glUniformMatrix4fv(modelUniform, 1, GL_FALSE, glm::value_ptr(rotate * translate * scale)); glBindVertexArray(m_vao); glDrawArrays(GL_TRIANGLES, 0, m_cubePoints.size()); } glBindVertexArray(0); }
25.029126
102
0.665632
Tsarpf
719f0341e883b08ce02119c83a223584750def0c
1,380
cpp
C++
SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiCheckBox.cpp
Risist/Project-skeletal-animation
1f39d572521bfa0fef7ce9aebf32152608e3dc33
[ "MIT" ]
null
null
null
SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiCheckBox.cpp
Risist/Project-skeletal-animation
1f39d572521bfa0fef7ce9aebf32152608e3dc33
[ "MIT" ]
null
null
null
SkeletalAnimation/SkeletalAnimation/Re/Graphics/Gui/GuiCheckBox.cpp
Risist/Project-skeletal-animation
1f39d572521bfa0fef7ce9aebf32152608e3dc33
[ "MIT" ]
null
null
null
/// Code from ReEngine library /// all rights belongs to Risist (Maciej Dominiak) (risistt@gmail.com) #include <Re\Graphics\Gui\GuiCheckBox.h> namespace Gui { CheckBox::CheckBox() : value(false) { } void Gui::CheckBox::onUpdate(RenderTarget & target, RenderStates states) { shortKey.reset(); mouseKey.reset(); sh.setPosition(getActualPosition()); bool mouseOn = isMouseOnWindow(); if ((mouseKey.isReady() && mouseOn) || shortKey.isReady()) { assert(eventOnPress); eventOnPress(); value = !value; //sh.setFillColor(statePressed.cl); //statePressed.ts.set(sh); } if (value) { sh.setFillColor(statePressed.cl); statePressed.ts.set(sh); } else { sh.setFillColor(stateMouseOut.cl); stateMouseOut.ts.set(sh); } target.draw(sh, states); } void Gui::CheckBox::serialiseF(std::ostream & file, Res::DataScriptSaver & saver) const { Base::serialiseF(file, saver); saver.save("value", value, false); stateMouseOn.serialise_Index("on", file, saver); stateMouseOut.serialise_Index("off", file, saver); } void Gui::CheckBox::deserialiseF(std::istream & file, Res::DataScriptLoader & loader) { Base::deserialiseF(file, loader); value = loader.load("value", false); setWh(halfWh*2.f); statePressed.deserialise_Index("on", file, loader); stateMouseOut.deserialise_Index("off", file, loader); } }
20.294118
88
0.684058
Risist
71a0ac418ae00368e51c23f844c280e66c4c84db
1,375
hpp
C++
android-29/android/R_color.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/R_color.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/R_color.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../JObject.hpp" namespace android { class R_color : public JObject { public: // Fields static jint background_dark(); static jint background_light(); static jint black(); static jint darker_gray(); static jint holo_blue_bright(); static jint holo_blue_dark(); static jint holo_blue_light(); static jint holo_green_dark(); static jint holo_green_light(); static jint holo_orange_dark(); static jint holo_orange_light(); static jint holo_purple(); static jint holo_red_dark(); static jint holo_red_light(); static jint primary_text_dark(); static jint primary_text_dark_nodisable(); static jint primary_text_light(); static jint primary_text_light_nodisable(); static jint secondary_text_dark(); static jint secondary_text_dark_nodisable(); static jint secondary_text_light(); static jint secondary_text_light_nodisable(); static jint tab_indicator_text(); static jint tertiary_text_dark(); static jint tertiary_text_light(); static jint transparent(); static jint white(); static jint widget_edittext_dark(); // QJniObject forward template<typename ...Ts> explicit R_color(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} R_color(QJniObject obj); // Constructors R_color(); // Methods }; } // namespace android
26.960784
148
0.737455
YJBeetle
71a6b1f7cfe63e3a5fb261d9efa1e38222d28f59
11,719
cpp
C++
src/swrast_setup/old/ss_vb.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
src/swrast_setup/old/ss_vb.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
src/swrast_setup/old/ss_vb.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
/* $Id: ss_vb.c,v 1.22 2002/10/29 20:29:00 brianp Exp $ */ /* * Mesa 3-D graphics library * Version: 4.1 * * Copyright (C) 1999-2002 Brian Paul All Rights Reserved. * * 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 * BRIAN PAUL 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. * * Authors: * Keith Whitwell <keith@tungstengraphics.com> */ #include "glheader.h" #include "colormac.h" #include "context.h" #include "macros.h" #include "imports.h" #include "swrast/swrast.h" #include "tnl/t_context.h" #include "math/m_vector.h" #include "math/m_translate.h" #include "ss_context.h" #include "ss_vb.h" static void do_import( struct vertex_buffer *VB, struct gl_client_array *to, struct gl_client_array *from ) { GLuint count = VB->Count; if (!to->Ptr) { to->Ptr = ALIGN_MALLOC( VB->Size * 4 * sizeof(GLchan), 32 ); to->Type = CHAN_TYPE; } /* No need to transform the same value 3000 times. */ if (!from->StrideB) { to->StrideB = 0; count = 1; } else to->StrideB = 4 * sizeof(GLchan); _math_trans_4chan( (GLchan (*)[4]) to->Ptr, from->Ptr, from->StrideB, from->Type, from->Size, 0, count); } static void import_float_colors( GLcontext *ctx ) { struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; struct gl_client_array *to = &SWSETUP_CONTEXT(ctx)->ChanColor; do_import( VB, to, VB->ColorPtr[0] ); VB->ColorPtr[0] = to; } static void import_float_spec_colors( GLcontext *ctx ) { struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; struct gl_client_array *to = &SWSETUP_CONTEXT(ctx)->ChanSecondaryColor; do_import( VB, to, VB->SecondaryColorPtr[0] ); VB->SecondaryColorPtr[0] = to; } /* Provides a RasterSetup function which prebuilds vertices for the * software rasterizer. This is required for the triangle functions * in this module, but not the rest of the swrast module. */ #define COLOR 0x1 #define INDEX 0x2 #define TEX0 0x4 #define MULTITEX 0x8 #define SPEC 0x10 #define FOG 0x20 #define POINT 0x40 #define MAX_SETUPFUNC 0x80 static setup_func setup_tab[MAX_SETUPFUNC]; static interp_func interp_tab[MAX_SETUPFUNC]; static copy_pv_func copy_pv_tab[MAX_SETUPFUNC]; #define IND (0) #define TAG(x) x##_none #include "ss_vbtmp.h" #define IND (COLOR) #define TAG(x) x##_color #include "ss_vbtmp.h" #define IND (COLOR|SPEC) #define TAG(x) x##_color_spec #include "ss_vbtmp.h" #define IND (COLOR|FOG) #define TAG(x) x##_color_fog #include "ss_vbtmp.h" #define IND (COLOR|SPEC|FOG) #define TAG(x) x##_color_spec_fog #include "ss_vbtmp.h" #define IND (COLOR|TEX0) #define TAG(x) x##_color_tex0 #include "ss_vbtmp.h" #define IND (COLOR|TEX0|SPEC) #define TAG(x) x##_color_tex0_spec #include "ss_vbtmp.h" #define IND (COLOR|TEX0|FOG) #define TAG(x) x##_color_tex0_fog #include "ss_vbtmp.h" #define IND (COLOR|TEX0|SPEC|FOG) #define TAG(x) x##_color_tex0_spec_fog #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX) #define TAG(x) x##_color_multitex #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|SPEC) #define TAG(x) x##_color_multitex_spec #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|FOG) #define TAG(x) x##_color_multitex_fog #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|SPEC|FOG) #define TAG(x) x##_color_multitex_spec_fog #include "ss_vbtmp.h" #define IND (COLOR|POINT) #define TAG(x) x##_color_point #include "ss_vbtmp.h" #define IND (COLOR|SPEC|POINT) #define TAG(x) x##_color_spec_point #include "ss_vbtmp.h" #define IND (COLOR|FOG|POINT) #define TAG(x) x##_color_fog_point #include "ss_vbtmp.h" #define IND (COLOR|SPEC|FOG|POINT) #define TAG(x) x##_color_spec_fog_point #include "ss_vbtmp.h" #define IND (COLOR|TEX0|POINT) #define TAG(x) x##_color_tex0_point #include "ss_vbtmp.h" #define IND (COLOR|TEX0|SPEC|POINT) #define TAG(x) x##_color_tex0_spec_point #include "ss_vbtmp.h" #define IND (COLOR|TEX0|FOG|POINT) #define TAG(x) x##_color_tex0_fog_point #include "ss_vbtmp.h" #define IND (COLOR|TEX0|SPEC|FOG|POINT) #define TAG(x) x##_color_tex0_spec_fog_point #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|POINT) #define TAG(x) x##_color_multitex_point #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|SPEC|POINT) #define TAG(x) x##_color_multitex_spec_point #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|FOG|POINT) #define TAG(x) x##_color_multitex_fog_point #include "ss_vbtmp.h" #define IND (COLOR|MULTITEX|SPEC|FOG|POINT) #define TAG(x) x##_color_multitex_spec_fog_point #include "ss_vbtmp.h" #define IND (INDEX) #define TAG(x) x##_index #include "ss_vbtmp.h" #define IND (INDEX|FOG) #define TAG(x) x##_index_fog #include "ss_vbtmp.h" #define IND (INDEX|POINT) #define TAG(x) x##_index_point #include "ss_vbtmp.h" #define IND (INDEX|FOG|POINT) #define TAG(x) x##_index_fog_point #include "ss_vbtmp.h" /*********************************************************************** * Additional setup and interp for back color and edgeflag. ***********************************************************************/ #define GET_COLOR(ptr, idx) (((GLchan (*)[4])((ptr)->Ptr))[idx]) static void interp_extras( GLcontext *ctx, GLfloat t, GLuint dst, GLuint out, GLuint in, GLboolean force_boundary ) { struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; if (VB->ColorPtr[1]) { INTERP_4CHAN( t, GET_COLOR(VB->ColorPtr[1], dst), GET_COLOR(VB->ColorPtr[1], out), GET_COLOR(VB->ColorPtr[1], in) ); if (VB->SecondaryColorPtr[1]) { INTERP_3CHAN( t, GET_COLOR(VB->SecondaryColorPtr[1], dst), GET_COLOR(VB->SecondaryColorPtr[1], out), GET_COLOR(VB->SecondaryColorPtr[1], in) ); } } else if (VB->IndexPtr[1]) { VB->IndexPtr[1]->data[dst] = (GLuint) (GLint) LINTERP( t, (GLfloat) VB->IndexPtr[1]->data[out], (GLfloat) VB->IndexPtr[1]->data[in] ); } if (VB->EdgeFlag) { VB->EdgeFlag[dst] = VB->EdgeFlag[out] || force_boundary; } interp_tab[SWSETUP_CONTEXT(ctx)->SetupIndex](ctx, t, dst, out, in, force_boundary); } static void copy_pv_extras( GLcontext *ctx, GLuint dst, GLuint src ) { struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; if (VB->ColorPtr[1]) { COPY_CHAN4( GET_COLOR(VB->ColorPtr[1], dst), GET_COLOR(VB->ColorPtr[1], src) ); if (VB->SecondaryColorPtr[1]) { COPY_3V( GET_COLOR(VB->SecondaryColorPtr[1], dst), GET_COLOR(VB->SecondaryColorPtr[1], src) ); } } else if (VB->IndexPtr[1]) { VB->IndexPtr[1]->data[dst] = VB->IndexPtr[1]->data[src]; } copy_pv_tab[SWSETUP_CONTEXT(ctx)->SetupIndex](ctx, dst, src); } /*********************************************************************** * Initialization ***********************************************************************/ static void emit_invalid( GLcontext *ctx, GLuint start, GLuint end, GLuint newinputs ) { _mesa_debug(ctx, "swrast_setup: invalid setup function\n"); (void) (ctx && start && end && newinputs); } static void interp_invalid( GLcontext *ctx, GLfloat t, GLuint edst, GLuint eout, GLuint ein, GLboolean force_boundary ) { _mesa_debug(ctx, "swrast_setup: invalid interp function\n"); (void) (ctx && t && edst && eout && ein && force_boundary); } static void copy_pv_invalid( GLcontext *ctx, GLuint edst, GLuint esrc ) { _mesa_debug(ctx, "swrast_setup: invalid copy_pv function\n"); (void) (ctx && edst && esrc ); } static void init_standard( void ) { GLuint i; for (i = 0 ; i < Elements(setup_tab) ; i++) { setup_tab[i] = emit_invalid; interp_tab[i] = interp_invalid; copy_pv_tab[i] = copy_pv_invalid; } init_none(); init_color(); init_color_spec(); init_color_fog(); init_color_spec_fog(); init_color_tex0(); init_color_tex0_spec(); init_color_tex0_fog(); init_color_tex0_spec_fog(); init_color_multitex(); init_color_multitex_spec(); init_color_multitex_fog(); init_color_multitex_spec_fog(); init_color_point(); init_color_spec_point(); init_color_fog_point(); init_color_spec_fog_point(); init_color_tex0_point(); init_color_tex0_spec_point(); init_color_tex0_fog_point(); init_color_tex0_spec_fog_point(); init_color_multitex_point(); init_color_multitex_spec_point(); init_color_multitex_fog_point(); init_color_multitex_spec_fog_point(); init_index(); init_index_fog(); init_index_point(); init_index_fog_point(); } /* debug only */ #if 0 static void printSetupFlags(const GLcontext *ctx, char *msg, GLuint flags ) { _mesa_debug(ctx, "%s(%x): %s%s%s%s%s%s%s\n", msg, (int) flags, (flags & COLOR) ? "color, " : "", (flags & INDEX) ? "index, " : "", (flags & TEX0) ? "tex0, " : "", (flags & MULTITEX) ? "multitex, " : "", (flags & SPEC) ? "spec, " : "", (flags & FOG) ? "fog, " : "", (flags & POINT) ? "point, " : ""); } #endif void _swsetup_choose_rastersetup_func(GLcontext *ctx) { SScontext *swsetup = SWSETUP_CONTEXT(ctx); TNLcontext *tnl = TNL_CONTEXT(ctx); int funcindex = 0; if (ctx->RenderMode == GL_RENDER) { if (ctx->Visual.rgbMode) { funcindex = COLOR; if (ctx->Texture._EnabledUnits > 1) funcindex |= MULTITEX; /* a unit above unit[0] is enabled */ else if (ctx->Texture._EnabledUnits == 1) funcindex |= TEX0; /* only unit 0 is enabled */ if (ctx->_TriangleCaps & DD_SEPARATE_SPECULAR) funcindex |= SPEC; } else { funcindex = INDEX; } if (ctx->Point._Attenuated || (ctx->VertexProgram.Enabled && ctx->VertexProgram.PointSizeEnabled)) funcindex |= POINT; if (ctx->Fog.Enabled) funcindex |= FOG; } else if (ctx->RenderMode == GL_FEEDBACK) { if (ctx->Visual.rgbMode) funcindex = (COLOR | TEX0); /* is feedback color subject to fogging? */ else funcindex = INDEX; } else funcindex = 0; swsetup->SetupIndex = funcindex; tnl->Driver.Render.BuildVertices = setup_tab[funcindex]; if (ctx->_TriangleCaps & (DD_TRI_LIGHT_TWOSIDE|DD_TRI_UNFILLED)) { tnl->Driver.Render.Interp = interp_extras; tnl->Driver.Render.CopyPV = copy_pv_extras; } else { tnl->Driver.Render.Interp = interp_tab[funcindex]; tnl->Driver.Render.CopyPV = copy_pv_tab[funcindex]; } ASSERT(tnl->Driver.Render.BuildVertices); ASSERT(tnl->Driver.Render.BuildVertices != emit_invalid); } void _swsetup_vb_init( GLcontext *ctx ) { (void) ctx; init_standard(); /* printSetupFlags(ctx); */ }
26.217002
78
0.650397
OS2World
71a70cdd2ec1adf5f452fbf4c9036a8ffbf8911c
11,473
cpp
C++
src/Tiger/TigerImport.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/Tiger/TigerImport.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/Tiger/TigerImport.cpp
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2004, Laminar Research. * * 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 "TIGERImport.h" #include "ParamDefs.h" #include "PerfUtils.h" #include "ConfigSystem.h" #include "MapAlgs.h" // This tags all roads as having their CFCCs for enums - useful for raw data analysis #define ENCODE_ROAD_CFCC 0 /* TODO: ADD COUNTERS OF ALL PHENOMENA TODO: build major catagories of land classes.... */ /* Census Feature Classification Codes - areas. These codes are applied to points or areas and either result in a land class (basically a zoning decision that will autogen buildings later) or a point object. The 'allow_from_point' field allows a single point object to apply a land class to the underlying polygon. This is appropriate for big things where the presence of the object would dominate the block. It is not appropriate for small things that might just be one single building instance in a land use. */ #define DO_CHECKS 0 struct WaterCodeInfo_t { string name; int is_wet; }; hash_map<string, WaterCodeInfo_t> kWaterCodes; bool ReadWaterLine(const vector<string>& tokens, void * ref) { if (tokens.size() != 3) return false; WaterCodeInfo_t code; code.name = tokens[2]; code.is_wet = 1; if (kWaterCodes.find(tokens[1]) != kWaterCodes.end()) fprintf(stderr,"WARNING: duplicate water cfcc %s\n", tokens[1].c_str()); kWaterCodes[tokens[1]] = code; return true; } // Census features may be GT-polygon based or point-based...there isn't a lot of logic to the database except for some broad restrictions. // (And since we are in the 'D' catagory virtually everything is point or area.) // // Census feature type use_gt_poly require_gt_poly action // Area 0 x Add point feature based on GT-poly center-point // Area 1 x Add area feature for GT-poly // Point x 0 Add point feature based on landmark point // Point x 1 Skip Feature struct FeatureInfo_t { string name; int feature_type; int use_gt_poly; // If this is set and we are an area feature in the census, make an area feature. int require_gt_poly; // If this is set and we are an area not an area feature in the census, ignore and dump the feature. int water_ok; // Can import on water int water_required; // Must import on water }; hash_map<string,FeatureInfo_t> kFeatureCodes; bool ReadFeatureLine(const vector<string>& tokens, void * ref) { if (tokens.size() != 8) return false; FeatureInfo_t info; info.name = tokens[2]; info.feature_type = LookupToken(tokens[3].c_str()); if (info.feature_type == -1) { fprintf(stderr,"WARNING: unknown enum %s\n", tokens[3].c_str()); return false; } info.use_gt_poly = atoi(tokens[4].c_str()); info.require_gt_poly = atoi(tokens[5].c_str()); info.water_ok = atoi(tokens[6].c_str()); info.water_required = atoi(tokens[7].c_str()); if (kFeatureCodes.find(tokens[1]) != kFeatureCodes.end()) fprintf(stderr,"WARNING: duplicate feature cfcc %s\n", tokens[1].c_str()); kFeatureCodes[tokens[1]] = info; return true; } struct RoadInfo_t { string cfcc; int network_type; int underpassing; int tunnel; }; hash_map<string, RoadInfo_t> kRoadCodes; bool ReadRoadLine(const vector<string>& tokens, void * ref) { if (tokens.size() != 5) return false; RoadInfo_t info; info.network_type = LookupToken(tokens[2].c_str()); if (info.network_type == -1) { fprintf(stderr,"Unknown enum %s\n", tokens[2].c_str()); return false; } info.underpassing = atoi(tokens[3].c_str()); info.tunnel = atoi(tokens[4].c_str()); if (kRoadCodes.find(tokens[1]) != kRoadCodes.end()) fprintf(stderr,"WARNING: duplicate net cfcc %s\n", tokens[1].c_str()); kRoadCodes[tokens[1]] = info; return true; } int LookupWaterCFCC(const char * inCode) { hash_map<string,WaterCodeInfo_t>::iterator i = kWaterCodes.find(inCode); if (i == kWaterCodes.end()) return 0; return i->second.is_wet; } RoadInfo_t * LookupNetCFCC(const char * inCode) { hash_map<string,RoadInfo_t>::iterator i = kRoadCodes.find(inCode); if (i == kRoadCodes.end()) { #if ENCODE_ROAD_CFCC static RoadInfo_t info; info.cfcc = inCode; info.network_type = road_Unknown; info.underpassing = 0; info.tunnel = 0; return &info; #endif return NULL; } return &i->second; } FeatureInfo_t * LookupFeatureCFCC(const char * inCode) { hash_map<string, FeatureInfo_t>::iterator i = kFeatureCodes.find(inCode); if (i == kFeatureCodes.end()) return NULL; return &i->second; } void LoadTigerConfig() { RegisterLineHandler("TIGER_WATER", ReadWaterLine, NULL); RegisterLineHandler("TIGER_FEATURE", ReadFeatureLine, NULL); RegisterLineHandler("TIGER_NETWORK", ReadRoadLine, NULL); LoadConfigFile("tiger_import.txt"); } void TIGERImport( const ChainInfoMap& chains, const LandmarkInfoMap& landmarks, const PolygonInfoMap& polygons, Pmwx& ioMap, ProgressFunc prog) { static bool first_time = true; if (first_time) { LoadTigerConfig(); first_time = false; } for (ChainInfoMap::const_iterator chainIter = chains.begin(); chainIter != chains.end(); ++chainIter) { RoadInfo_t * net_cfcc = LookupNetCFCC(chainIter->second.cfcc.c_str()); if (net_cfcc) { if (net_cfcc->tunnel) { chainIter->second.startNode->pm_vertex->data().mTunnelPortal = true; chainIter->second.endNode->pm_vertex->data().mTunnelPortal = true; } else { GISNetworkSegment_t nl; nl.mFeatType = net_cfcc->network_type; #if ENCODE_ROAD_CFCC nl.mRepType = LookupTokenCreate(chainIter->second.cfcc.c_str()); #else nl.mRepType = NO_VALUE; #endif for (WTPM_Line::HalfedgeVector::const_iterator he = chainIter->second.pm_edges.first.begin(); he != chainIter->second.pm_edges.first.end(); ++he) { (*he)->data().mSegments.push_back(nl); (*he)->data().mParams[he_IsUnderpassing] = net_cfcc->underpassing; } } } int water_cfcc = LookupWaterCFCC(chainIter->second.cfcc.c_str()); if (water_cfcc) { for (WTPM_Line::HalfedgeVector::const_iterator he = chainIter->second.pm_edges.first.begin(); he != chainIter->second.pm_edges.first.end(); ++he) { (*he)->data().mParams[he_IsRiver] = 1; } } for (WTPM_Line::HalfedgeVector::const_iterator he = chainIter->second.pm_edges.first.begin(); he != chainIter->second.pm_edges.first.end(); ++he) (*he)->data().mParams[he_TIGER_TLID] = chainIter->first; for (WTPM_Line::HalfedgeVector::const_iterator he = chainIter->second.pm_edges.second.begin(); he != chainIter->second.pm_edges.second.end(); ++he) (*he)->data().mParams[he_TIGER_TLID] = chainIter->first; } for (PolygonInfoMap::const_iterator polyIter = polygons.begin(); polyIter != polygons.end(); ++polyIter) { if (polyIter->second.water) polyIter->second.pm_face->data().mTerrainType = terrain_Water; } Point_2 sw, ne; CalcBoundingBox(ioMap, sw, ne); // ioMap.Index(); int skip = 0; int nolo = 0; CGAL::Arr_landmarks_point_location<Arrangement_2> locator(ioMap); for (LandmarkInfoMap::const_iterator landIter = landmarks.begin(); landIter != landmarks.end(); ++landIter) { FeatureInfo_t * land_cfcc = LookupFeatureCFCC(landIter->second.cfcc.c_str()); if (land_cfcc) { bool has_poly = !landIter->second.cenid_polyid.empty(); if (land_cfcc->require_gt_poly && !has_poly) continue; // Lack of area feature from poitn landmark if (land_cfcc->use_gt_poly && has_poly) { // printf("Importing area feature %s %s\n", kFeatureCodes[cfcc].cfcc, kFeatureCodes[cfcc].name); // Area feature from area landmark for (vector<CENID_POLYID>::const_iterator i = landIter->second.cenid_polyid.begin(); i != landIter->second.cenid_polyid.end(); ++i) { PolygonInfoMap::const_iterator thePoly = polygons.find(*i); if (thePoly != polygons.end()) { bool wet = thePoly->second.pm_face->data().IsWater(); GISAreaFeature_t feat; feat.mFeatType = land_cfcc->feature_type; if ((wet || !land_cfcc->water_required) && (!wet || land_cfcc->water_ok)) { if (thePoly->second.pm_face->data().mAreaFeature.mFeatType != NO_VALUE) printf("WARNING: double feature, %s and %s\n", FetchTokenString(thePoly->second.pm_face->data().mAreaFeature.mFeatType), FetchTokenString(feat.mFeatType)); thePoly->second.pm_face->data().mAreaFeature = feat; } else ++skip; //printf("Skipped: wet = %d, feat = %s\n", wet, kFeatureCodes[cfcc].name); } } } else if (has_poly) { // printf("Importing point feature for poly %s %s\n", kFeatureCodes[cfcc].cfcc, kFeatureCodes[cfcc].name); // Point feature from area landmark for (vector<CENID_POLYID>::const_iterator i = landIter->second.cenid_polyid.begin(); i != landIter->second.cenid_polyid.end(); ++i) { PolygonInfoMap::const_iterator thePoly = polygons.find(*i); if (thePoly != polygons.end()) { bool wet = thePoly->second.pm_face->data().IsWater(); GISPointFeature_t feat; feat.mFeatType = land_cfcc->feature_type; feat.mInstantiated = false; feat.mLocation = Point_2(thePoly->second.location.x(),thePoly->second.location.y()); if ((wet || !land_cfcc->water_required) && (!wet || land_cfcc->water_ok)) thePoly->second.pm_face->data().mPointFeatures.push_back(feat); else ++skip; //printf("Skipped: wet = %d, feat = %s\n", wet, kFeatureCodes[cfcc].name); } } } else { // printf("Importing point feature for point %s %s\n", kFeatureCodes[cfcc].cfcc, kFeatureCodes[cfcc].name); // Point feature from point landmark Face_handle f; CGAL::Object obj; obj = locator.locate(Point_2(landIter->second.location.x(),landIter->second.location.y())); if(CGAL::assign(f,obj)) { bool wet = f->data().IsWater(); GISPointFeature_t feat; feat.mFeatType = land_cfcc->feature_type; feat.mLocation = Point_2(landIter->second.location.x(),landIter->second.location.y()); if ((wet || !land_cfcc->water_required) && (!wet || land_cfcc->water_ok)) f->data().mPointFeatures.push_back(feat); else ++skip; //printf("Skipped: wet = %d, feat = %s\n", wet, kFeatureCodes[cfcc].name); } else nolo++; } } } #if DEV if (nolo) printf("Could not locate %d point features.\n", nolo); #endif if (skip) printf("Skipped %d landmarks that were/were not in water when they should have been.\n", skip); }
35.301538
149
0.694587
rromanchuk
71ace11bd9a3794030cbc24e219e17bcc454a483
2,361
hpp
C++
host-bmc/host_associations_parser.hpp
vkaverap/pldm-2
01a50d2421202ba385f6cfc66877d8e8c877478f
[ "Apache-2.0" ]
null
null
null
host-bmc/host_associations_parser.hpp
vkaverap/pldm-2
01a50d2421202ba385f6cfc66877d8e8c877478f
[ "Apache-2.0" ]
null
null
null
host-bmc/host_associations_parser.hpp
vkaverap/pldm-2
01a50d2421202ba385f6cfc66877d8e8c877478f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "common/utils.hpp" #include <string> #include <utility> #include <vector> namespace pldm { namespace host_associations { struct entity { uint16_t entity_type; uint16_t entity_instance_num; uint16_t entity_container_id; bool operator==(const entity& e) const { return ((entity_type == e.entity_type) && (entity_instance_num == e.entity_instance_num) && (entity_container_id == e.entity_container_id)); } bool operator<(const entity& e) const { return ((entity_type < e.entity_type) || ((entity_type == e.entity_type) && (entity_instance_num < e.entity_instance_num)) || ((entity_type == e.entity_type) && (entity_instance_num == e.entity_instance_num) && (entity_container_id < e.entity_container_id))); } }; /** @class HostAssociationsParser * * @brief This class parses the Host Effecter json file and monitors for the * D-Bus changes for the effecters. Upon change, calls the corresponding * setStateEffecterStates on the host */ class HostAssociationsParser { public: HostAssociationsParser() = delete; HostAssociationsParser(const HostAssociationsParser&) = delete; HostAssociationsParser& operator=(const HostAssociationsParser&) = delete; HostAssociationsParser(HostAssociationsParser&&) = delete; HostAssociationsParser& operator=(HostAssociationsParser&&) = delete; virtual ~HostAssociationsParser() = default; /** @brief Constructor to create a HostAssociationsParser object. * @param[in] jsonPath - path for the json file */ HostAssociationsParser(const std::string& jsonPath) { try { parseHostAssociations(jsonPath); } catch (const std::exception& e) { std::cerr << "The json file does not exist or malformed, ERROR=" << e.what() << "\n"; } } /* @brief Parses the host effecter json * * @param[in] jsonPath - path for the json file */ void parseHostAssociations(const std::string& jsonPath); std::map<entity, std::vector<std::tuple<entity, std::string, std::string>>> associationsInfoMap; }; } // namespace host_associations } // namespace pldm
28.445783
80
0.638712
vkaverap
71ae05cea3e2ccf469da455a0a40d938f75883ee
1,730
cpp
C++
src/Axios/Instance.cpp
antjowie/Axios-framework
d4fadadcc3b5d1e5f83e212bf10e151734223de3
[ "MIT" ]
null
null
null
src/Axios/Instance.cpp
antjowie/Axios-framework
d4fadadcc3b5d1e5f83e212bf10e151734223de3
[ "MIT" ]
null
null
null
src/Axios/Instance.cpp
antjowie/Axios-framework
d4fadadcc3b5d1e5f83e212bf10e151734223de3
[ "MIT" ]
null
null
null
#include "Axios/Instance.h" #include "Axios/InputHandler.h" #include "Axios/DataManager.h" #include "Axios/Object.h" #include <SFML/System/Clock.hpp> #include <SFML/Window/Event.hpp> ax::Instance::Instance() : m_init(false), m_currentScene(nullptr) { } void ax::Instance::start() { // Check if user called init function if (!m_init) { ax::Logger::log(0, "Init hasn't been called before start, custom configurations will not be applied", "Axios", ax::Logger::ERROR, "Instance"); return; } // These values can't be changed by the user during runtime, that's why they are local to this scope sf::Event event; sf::Clock currentTime; double elapsedTime{0}; double accumulator{0}; // Loop phase while(m_window.isOpen()) { elapsedTime = currentTime.restart().asSeconds(); // If the game has a fps lower than 0, skip the frame if (elapsedTime > 1) { elapsedTime = 0; continue; } // Check if scene has to be swapped if (m_currentScene->m_nextScene != nullptr) { // Keep address of old scene Scene * toDelete = m_currentScene; m_currentScene->onExit(); // Swap scene m_currentScene = m_currentScene->m_nextScene; delete toDelete; m_currentScene->onEnter(); } ax::InputHandler::getInstance()._update(m_window,event); m_currentScene->_update(elapsedTime); m_window.clear(); m_currentScene->_draw(m_window, accumulator); m_window.display(); } // TEMP (until a main menu scene or something has been added) m_currentScene->onExit(); // Deinit phase delete m_currentScene; ax::DataManager::getInstance()._checkConfig(false); ax::DataManager::getInstance()._save("config.json"); }
23.378378
144
0.674566
antjowie
71aefdf53f001f0189208ae64dbae6204fff85ad
1,800
cpp
C++
Compi/Highway Construction.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
Compi/Highway Construction.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
Compi/Highway Construction.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cstring> using namespace std; #define Kmax 1002 #define m 1000000009 int Choose[Kmax][Kmax]; int Stirling[Kmax][Kmax]; int factorial[Kmax]; int modexp(long long int x, long long int y, long long int p) { long long int out = 1; x = x % p; while (y > 0) { // If y is odd, multiply x with result if (y & 1) out = ((out%p)*(x%p)) % p; // y must be even now y = y>>1; // y = y/2 x = ((x%p)*(x%p)) % p; } return out; } int modinv(int a){ //m is prime return modexp(a,m-2,m); } void init1(){ memset(Choose,0,sizeof(Choose)); for(int i=0 ; i<Kmax ; i++) { for (int j = 0; j <= i; ++j) { if (j==0 || j==i) { Choose[i][j] = 1; }else { Choose[i][j] = ((Choose[i-1][j]%m) + (Choose[i-1][j-1]%m))%m; } } } } void init2(){ memset(Stirling,0,sizeof(Stirling)); for(int i=1 ; i<Kmax ; i++) { for (int j = 1; j <= i; ++j) { if (j==1 || j==i) { Stirling[i][j] = 1; }else { Stirling[i][j] = ((Stirling[i-1][j-1]%m) + ((j%m) * (Stirling[i-1][j]%m))%m)%m; } } } } void init3(){ factorial[0] = 1; for (int i = 1; i < Kmax; ++i) { factorial[i] = ((i%m)*(factorial[i-1]%m))%m; } } int solve(long long int n, int k){ long long int sum = 0; long long int c = ((n%m * (n+1)%m)%m * modinv(2))%m; for (int i = 1; i < k+1; ++i) { sum = (sum + (((factorial[i] * Stirling[k][i])%m)*c)%m)%m; c = (((c * (n-i)%m)%m) * modinv(i+2))%m; } return ((sum - 1)%m + m)%m; } int main() { init2(); init3(); int q; cin >> q; while(q--){ int k; long long int n; cin >> n >> k; if(n<3) cout << 0 << endl; else cout << solve(n-1,k) << endl; } }
16.981132
83
0.486667
udayan14
71af2fb8b9c6ddfd21321fc706a60b56824df3d4
9,133
cpp
C++
src/GitCommitInfoPage.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
8
2021-04-16T02:05:54.000Z
2022-03-16T13:56:23.000Z
src/GitCommitInfoPage.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
null
null
null
src/GitCommitInfoPage.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
2
2021-04-17T10:49:58.000Z
2021-07-21T20:39:52.000Z
/* * GitCommitInfoPage.cpp * * Created on: Aug 24, 2015 * Author: lingnan */ #include <bb/cascades/TitleBar> #include <bb/cascades/Header> #include <bb/cascades/Label> #include <bb/cascades/StandardListItem> #include <bb/cascades/SystemDefaults> #include <bb/cascades/NavigationPane> #include <bb/cascades/ListView> #include <bb/cascades/ActionSet> #include <bb/cascades/Shortcut> #include <libqgit2/qgitrepository.h> #include <libqgit2/qgitdifffile.h> #include <libqgit2/qgitpatch.h> #include <GitCommitInfoPage.h> #include <GitRepoPage.h> #include <GitDiffPage.h> #include <Segment.h> #include <Defaults.h> #include <Utility.h> #include <LocaleAwareActionItem.h> using namespace bb::cascades; GitCommitInfoPage::GitCommitInfoPage(GitRepoPage *page): _repoPage(page), _itemProvider(this), _listView(ListView::create() .dataModel(&_dataModel) .listItemProvider(&_itemProvider)), _checkoutAction(NULL) { conn(_listView, SIGNAL(triggered(QVariantList)), this, SLOT(showDiffIndexPath(const QVariantList &))); setTitleBar(TitleBar::create()); setContent(_listView); onTranslatorChanged(); } void GitCommitInfoPage::setCommit(const LibQGit2::Commit &commit) { titleBar()->setTitle(QString("Commit %1").arg(QString(commit.oid().nformat(7)))); QList<Diff> diffs; const LibQGit2::Tree &t = commit.tree(); unsigned int i = 0; for (unsigned int count = commit.parentCount(); i < count; i++) { const LibQGit2::Commit &parent = commit.parent(i); diffs.append(Diff(_repoPage->repo()->diffTrees(parent.tree(), t), QString(parent.oid().nformat(7)))); } if (i == 0) { diffs.append(Diff(_repoPage->repo()->diffTrees(LibQGit2::Tree(), t))); } _dataModel.setCommit(commit, diffs); } void GitCommitInfoPage::resetCommit() { _dataModel.clear(); } void GitCommitInfoPage::showDiffSelection() { showDiffIndexPath(_listView->selected()); } void GitCommitInfoPage::showDiffIndexPath(const QVariantList &ip) { if (ip.size() < 2) return; int index = ip[0].toInt(); if (index < 3) return; const LibQGit2::Patch &p = _dataModel.diffs()[index-3].diff.patch(ip[1].toInt()); if (p.numHunks() == 0) { Utility::toast(tr("No hunk details available")); return; } _repoPage->pushDiffPage(p); } void GitCommitInfoPage::checkout() { _repoPage->checkoutCommit(_dataModel.commit()); pop(); } void GitCommitInfoPage::setActions(Actions actions) { while (actionCount() > 0) removeAction(actionAt(0)); if (actions.testFlag(Checkout)) { if (!_checkoutAction) _checkoutAction = LocaleAwareActionItem::create(QT_TRANSLATE_NOOP("Man", "Checkout")) .reloadTitleOn(this, SIGNAL(translatorChanged())) .imageSource(QUrl("asset:///images/ic_git_checkout.png")) .addShortcut(Shortcut::create().key("c")) .onTriggered(this, SLOT(checkout())); addAction(_checkoutAction, ActionBarPlacement::Signature); } } void GitCommitInfoPage::onTranslatorChanged() { PushablePage::onTranslatorChanged(); _dataModel.refresh(); emit translatorChanged(); } int GitCommitInfoPage::DiffDataModel::childCount(const QVariantList &ip) { switch (ip.size()) { case 0: return 3 + _diffs.size(); case 1: { int index = ip[0].toInt(); if (index < 3) return 1; return _diffs[index-3].diff.numDeltas(); } } return 0; } bool GitCommitInfoPage::DiffDataModel::hasChildren(const QVariantList &ip) { return ip.size() < 2; } QString GitCommitInfoPage::DiffDataModel::itemType(const QVariantList &ip) { switch (ip.size()) { case 1: return "header"; case 2: switch (ip[0].toInt()) { case 0: case 1: return "sigitem"; case 2: return "message"; default: return "diffitem"; } } return QString(); } QVariant GitCommitInfoPage::DiffDataModel::data(const QVariantList &ip) { if (ip.empty()) return QVariant(); int index = ip[0].toInt(); switch (index) { case 0: if (ip.size() < 2) return tr("Author"); return QVariant::fromValue(_commit.author()); case 1: if (ip.size() < 2) return tr("Committer"); return QVariant::fromValue(_commit.committer()); case 2: if (ip.size() < 2) return tr("Message"); return _commit.message(); default: const Diff diff = _diffs[index-3]; if (ip.size() < 2) { if (diff.parentOId.isEmpty()) return tr("Diff"); return tr("Diff with Parent %1").arg(diff.parentOId); } return QVariant::fromValue(diff.diff.delta(ip[1].toInt())); } } void GitCommitInfoPage::DiffDataModel::setCommit(const LibQGit2::Commit &commit, const QList<Diff> &diffs) { _commit = commit; // populating the diffs _diffs = diffs; emit itemsChanged(DataModelChangeType::Init); } void GitCommitInfoPage::DiffDataModel::clear() { _diffs.clear(); _commit = LibQGit2::Commit(); } void GitCommitInfoPage::DiffDataModel::refresh() { emit itemsChanged(DataModelChangeType::Init); } GitCommitInfoPage::LabelSegment::LabelSegment(): label(Label::create().multiline(true) .textStyle(SystemDefaults::TextStyles::primaryText())) { setLeftPadding(Defaults::space()); setRightPadding(Defaults::space()); setTopPadding(Defaults::space()); setBottomPadding(Defaults::space()); add(label); } VisualNode *GitCommitInfoPage::DiffItemProvider::createItem(ListView *, const QString &type) { if (type == "header") return Header::create(); if (type == "message") return new LabelSegment; if (type == "sigitem") return StandardListItem::create(); if (type == "diffitem") return StandardListItem::create() .actionSet(ActionSet::create() .add(LocaleAwareActionItem::create(QT_TRANSLATE_NOOP("Man", "View Diff")) .reloadTitleOn(_page, SIGNAL(translatorChanged())) .imageSource(QUrl("asset:///images/ic_git_diff.png")) .onTriggered(_page, SLOT(showDiffSelection())))); return NULL; } void GitCommitInfoPage::DiffItemProvider::updateItem(ListView *, VisualNode *item, const QString &type, const QVariantList &, const QVariant &data) { if (type == "header") ((Header *) item)->setTitle(data.toString()); else if (type == "message") ((LabelSegment *) item)->label->setText(data.toString()); else if (type == "sigitem") { StandardListItem *li = (StandardListItem *) item; const LibQGit2::Signature &sig = data.value<LibQGit2::Signature>(); li->setTitle(sig.name()); li->setDescription(sig.email()); li->setStatus(sig.when().toString()); } else if (type == "diffitem") { StandardListItem *li = (StandardListItem *) item; const LibQGit2::DiffDelta &delta = data.value<LibQGit2::DiffDelta>(); li->setVisible(true); switch (delta.type()) { case LibQGit2::DiffDelta::Unknown: li->setVisible(false); break; case LibQGit2::DiffDelta::Unmodified: li->setVisible(false); break; case LibQGit2::DiffDelta::Added: li->setTitle(delta.newFile().path()); li->setStatus(tr("Added")); break; case LibQGit2::DiffDelta::Deleted: li->setTitle(delta.oldFile().path()); li->setStatus(tr("Deleted")); break; case LibQGit2::DiffDelta::Modified: li->setTitle(delta.newFile().path()); li->setStatus(tr("Modified")); break; case LibQGit2::DiffDelta::Renamed: li->setTitle(delta.newFile().path()); li->setDescription(tr("was %1").arg(delta.oldFile().path())); li->setStatus(tr("Renamed")); break; case LibQGit2::DiffDelta::Copied: li->setTitle(delta.newFile().path()); li->setStatus(tr("Copied")); break; case LibQGit2::DiffDelta::Ignored: li->setTitle(delta.newFile().path()); li->setStatus(tr("Ignored")); break; case LibQGit2::DiffDelta::Untracked: li->setTitle(delta.newFile().path()); li->setStatus(tr("Untracked")); break; case LibQGit2::DiffDelta::Typechange: li->setTitle(delta.newFile().path()); li->setStatus(tr("Type Changed")); break; } } }
30.959322
106
0.586883
lingnand
71b36706a31fda2f1b47f24d82e09fa75ad1d221
1,023
cc
C++
d3d9/src/dllmain.cc
nomi-san/league-loader
56872920c987a46abc280102d4fc1dbfbf7de6a8
[ "MIT" ]
6
2021-10-10T03:01:40.000Z
2022-03-05T05:43:19.000Z
d3d9/src/dllmain.cc
nomi-san/susan
56872920c987a46abc280102d4fc1dbfbf7de6a8
[ "MIT" ]
null
null
null
d3d9/src/dllmain.cc
nomi-san/susan
56872920c987a46abc280102d4fc1dbfbf7de6a8
[ "MIT" ]
2
2021-11-03T04:03:07.000Z
2022-01-19T06:33:48.000Z
#include "internal.h" using namespace league_loader; void LoadD3D9APIs(); void LoadLibCEFAPIs(); static void Attach() { // Load D3D9. LoadD3D9APIs(); // Get exe path. WCHAR name[1024]; GetModuleFileNameW(NULL, name, 1024); // Determine which process to be hooked. // Browser process. if (wcsstr(name, L"LeagueClientUx.exe") != NULL) { LoadLibCEFAPIs(); HookBrowser(); } else if (wcsstr(name, L"LeagueClientUxRender.exe") != NULL) { LPCWSTR commandLine = GetCommandLineW(); // Renderer process only. if (wcsstr(GetCommandLineW(), L"--type=renderer")) { LoadLibCEFAPIs(); HookRenderer(); } } } BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) { switch (reason) { case DLL_PROCESS_ATTACH: Attach(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
21.765957
68
0.595308
nomi-san
71bd4e551dbef7520badc31de5d8c38984d7ffcb
2,032
cpp
C++
clap/test/with_usage_test.cpp
asap-projects/asap-clap
97823c2a2d88c749ff4147cf4977698b1f98d0b3
[ "BSD-3-Clause" ]
null
null
null
clap/test/with_usage_test.cpp
asap-projects/asap-clap
97823c2a2d88c749ff4147cf4977698b1f98d0b3
[ "BSD-3-Clause" ]
1
2022-03-08T20:45:38.000Z
2022-03-08T20:45:38.000Z
clap/test/with_usage_test.cpp
asap-projects/asap-clap
97823c2a2d88c749ff4147cf4977698b1f98d0b3
[ "BSD-3-Clause" ]
null
null
null
//===----------------------------------------------------------------------===// // Distributed under the 3-Clause BSD License. See accompanying file LICENSE or // copy at https://opensource.org/licenses/BSD-3-Clause). // SPDX-License-Identifier: BSD-3-Clause //===----------------------------------------------------------------------===// #include "clap/command.h" #include "clap/with_usage.h" #include <common/compilers.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <type_traits> // Disable compiler and linter warnings originating from the unit test framework // and for which we cannot do anything. Additionally, every TEST or TEST_X macro // usage must be preceded by a '// NOLINTNEXTLINE'. ASAP_DIAGNOSTIC_PUSH #if defined(__clang__) && ASAP_HAS_WARNING("-Wused-but-marked-unused") #pragma clang diagnostic ignored "-Wused-but-marked-unused" #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wunused-member-function" #endif // NOLINTBEGIN(used-but-marked-unused) using testing::Eq; using testing::IsTrue; namespace asap::clap { namespace { // NOLINTNEXTLINE TEST(WithUsage, AddUsageDetails) { class MyCommand : public Command, asap::mixin::Mixin<MyCommand, WithUsageDetails> { public: MyCommand() : Command(DEFAULT), Mixin("Detailed usage help") { } auto UsageDetails() -> const std::string & { return usage_details; } }; MyCommand cmd; EXPECT_THAT(cmd.UsageDetails(), Eq("Detailed usage help")); } // NOLINTNEXTLINE TEST(WithUsage, AddUsageExamples) { class MyCommand : public Command, asap::mixin::Mixin<MyCommand, WithUsageExamples> { public: MyCommand() : Command(DEFAULT), Mixin("Usage examples") { } auto UsageExamples() -> const std::string & { return usage_examples; } }; MyCommand cmd; EXPECT_THAT(cmd.UsageExamples(), Eq("Usage examples")); } } // namespace } // namespace asap::clap // NOLINTEND(used-but-marked-unused) ASAP_DIAGNOSTIC_POP
29.028571
80
0.655512
asap-projects
71bdff940e32b523606f254fe71095fd34e05184
4,887
cpp
C++
modules/RegularExpression.cpp
tyraindreams/EpicBasic
6dc2d4fb567a8d0fef2db4ff80a17905e23af143
[ "CC0-1.0" ]
null
null
null
modules/RegularExpression.cpp
tyraindreams/EpicBasic
6dc2d4fb567a8d0fef2db4ff80a17905e23af143
[ "CC0-1.0" ]
null
null
null
modules/RegularExpression.cpp
tyraindreams/EpicBasic
6dc2d4fb567a8d0fef2db4ff80a17905e23af143
[ "CC0-1.0" ]
null
null
null
// -------------------------------------------------------------------------------- // // EpicBasic RegularExpression Library // // -------------------------------------------------------------------------------- const char * _pcreErrorString ; int _pcreErrorOffset; struct _RegularExpression { pcre * CompiledExpression ; pcre_extra * Optimizations ; int ExecResult = 0 ; int CurrentGroup = 0 ; int Offset = 0 ; int SubStringVector[3000] ; std::string CurrentQuery ; std::string CurrentMatch ; } ; char * _ebP_CompileRegularExpression(const std::string &RegularExpressionString) { _RegularExpression * RegularExpression = new _RegularExpression ; RegularExpression->CompiledExpression = pcre_compile(RegularExpressionString.c_str(), 0, &_pcreErrorString, &_pcreErrorOffset, NULL) ; if(RegularExpression->CompiledExpression == NULL) { return NULL ; } RegularExpression->Optimizations = pcre_study(RegularExpression->CompiledExpression, PCRE_STUDY_JIT_COMPILE, &_pcreErrorString); if(_pcreErrorString != NULL) { return NULL ; } return reinterpret_cast <char *> (RegularExpression) ; } int _ebP_ExamineRegularExpression(const char * RegularExpression, const std::string &Query) { _RegularExpression * RegularExpressionObject = (_RegularExpression*)RegularExpression ; RegularExpressionObject->CurrentQuery = Query ; RegularExpressionObject->Offset = 0 ; RegularExpressionObject->CurrentGroup = 0 ; RegularExpressionObject->ExecResult = pcre_exec(RegularExpressionObject->CompiledExpression, RegularExpressionObject->Optimizations, RegularExpressionObject->CurrentQuery.c_str(), RegularExpressionObject->CurrentQuery.length(), RegularExpressionObject->Offset, 0, RegularExpressionObject->SubStringVector, 3000) ; if(RegularExpressionObject->ExecResult < 0) { return false ; } return true ; } int _ebP_NextRegularExpressionMatch(const char * RegularExpression) { _RegularExpression * RegularExpressionObject = (_RegularExpression*)RegularExpression ; const char *psubStrMatchStr ; if (RegularExpressionObject->Offset < RegularExpressionObject->CurrentQuery.length() ) { RegularExpressionObject->ExecResult = pcre_exec(RegularExpressionObject->CompiledExpression, RegularExpressionObject->Optimizations, RegularExpressionObject->CurrentQuery.c_str(), RegularExpressionObject->CurrentQuery.length(), RegularExpressionObject->Offset, 0, RegularExpressionObject->SubStringVector, 30000) ; if(RegularExpressionObject->ExecResult < 0) { return false ; } pcre_get_substring(RegularExpressionObject->CurrentQuery.c_str(), RegularExpressionObject->SubStringVector, RegularExpressionObject->ExecResult, RegularExpressionObject->CurrentGroup, &(psubStrMatchStr)); RegularExpressionObject->CurrentMatch = psubStrMatchStr ; pcre_free_substring(psubStrMatchStr) ; RegularExpressionObject->Offset = RegularExpressionObject->SubStringVector[(RegularExpressionObject->CurrentGroup*2)+1] ; return true ; } return false ; } int _ebP_RegularExpressionMatchGroup(const char * RegularExpression) { _RegularExpression * RegularExpressionObject = (_RegularExpression*)RegularExpression ; if (RegularExpressionObject->CurrentGroup < RegularExpressionObject->ExecResult ) { return RegularExpressionObject->ExecResult-1 ; } else { return false ; } } int _ebP_RegularExpressionMatchPosition(const char * RegularExpression) { _RegularExpression * RegularExpressionObject = (_RegularExpression*)RegularExpression ; if (RegularExpressionObject->CurrentGroup < RegularExpressionObject->ExecResult ) { return RegularExpressionObject->SubStringVector[(RegularExpressionObject->CurrentGroup*2)+1]-RegularExpressionObject->CurrentMatch.length()+1 ; // fix this } else { return false ; } } std::string _ebP_RegularExpressionMatchString(const char * RegularExpression) { _RegularExpression * RegularExpressionObject = (_RegularExpression*)RegularExpression ; if (RegularExpressionObject->CurrentGroup < RegularExpressionObject->ExecResult ) { return RegularExpressionObject->CurrentMatch ; } else { return "" ; } } void _ebP_FreeRegularExpression(const char * RegularExpression) { _RegularExpression * RegularExpressionObject = (_RegularExpression*)RegularExpression ; pcre_free(RegularExpressionObject->CompiledExpression) ; if(RegularExpressionObject->Optimizations != NULL) { pcre_free(RegularExpressionObject->Optimizations) ; } delete RegularExpressionObject ; }
32.798658
320
0.702885
tyraindreams
71c123a45e9cdceb86c12dabb0a08956988a7aab
10,078
cc
C++
apps-env/misc/nocTest/nocTest.cc
rouxb/emu-HMpSoC
18fedaf525207301ad5e96e3c58d10045633620e
[ "MIT" ]
4
2017-11-23T11:59:27.000Z
2022-02-02T15:01:03.000Z
apps-env/misc/nocTest/nocTest.cc
rouxb/emu-HMpSoC
18fedaf525207301ad5e96e3c58d10045633620e
[ "MIT" ]
null
null
null
apps-env/misc/nocTest/nocTest.cc
rouxb/emu-HMpSoC
18fedaf525207301ad5e96e3c58d10045633620e
[ "MIT" ]
1
2021-04-07T09:05:11.000Z
2021-04-07T09:05:11.000Z
/* * Copyright (c) 2016 Baptiste Roux. * email: <baptiste.roux AT inria.fr>. */ /* * File: nocTest.cc * Test application for nocIPC, two available modes: * * traffic producer * * traffic consumer */ //NOTE: Don't use memcpy because it generate Byte access on bus #include <iostream> #include <sstream> #include "noc_helper.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> #define DEFAULT_PLENGTH 320 /* #define DISABLE_MEMCALL */ //register getter/setter #define _RNOC(NAME) (((uintptr_t)noc_register+ (RNOC_##NAME))) #define NOC_STATUS (*((volatile uint8_t*)_RNOC(CMD))) using namespace std; using namespace noc; void usage(char * name) { printf("%s -g <@noc> -n|-d|-o|-s -p|-c [-l payload_length]\n", name); printf("\t -g <@noc> base address of noc \n"); printf("\t -s sync packet\n"); printf("\t -o order packet\n"); printf("\t -p produce packet\n"); printf("\t -c consume packet\n"); printf("\t -d discover Noc \n"); printf("\t -n get Noc powerLog \n"); printf("\t -l <payload_length> specify payload length [optional]\n"); return; } long unsigned get_luint(string displayMessage) { string buffer; stringstream ss; long unsigned value; do{ cout <<displayMessage; getline(cin, buffer, '\n'); if("0x" == buffer.substr(0,2)) ss << hex<< buffer.substr(2); else ss << buffer; if(ss >> value) break; else{ ss.str(""); //purge stream; ss.clear(); cout << "Bad value \n"; } }while(1); return value; } int main(int argc, char *argv[]) { int c; unsigned long noc_addr= 0x00; char p_type=0; char p_mode=0; unsigned int p_length= DEFAULT_PLENGTH; /* Parse command line arguments */ while((c = getopt(argc, argv, "dnospcl:h")) != -1) { switch(c) { case 'o': p_type = 'o'; // order packet break; case 's': p_type = 's'; // sync packet break; case 'p': p_mode = 'p'; // producer break; case 'c': p_mode = 'c'; // consumer break; case 'd': p_type = 'd'; // nocDiscover p_mode = 'd'; break; case 'n': p_type = 'n'; // get nocPower p_mode = 'n'; break; case 'l': p_length = strtoul(optarg,NULL, 0); break; case 'h': usage(argv[0]); return EXIT_SUCCESS; default: printf("invalid option: %c\n", (char)c); usage(argv[0]); return EXIT_FAILURE; } } if (p_type == 0) { printf("Specify %s packet type : -d \"discoverNoC\" -s \"sync\" -o \"order\".\n", argv[0]); return EXIT_FAILURE; } if (p_mode == 0) { printf("Specify %s mode : -p \"producer\" -c \"consumer\".\n",argv[0]); return EXIT_FAILURE; } if (noc_addr == 0) { printf("Unset noc address: use the default 0x%lx.\n",DEFAULT_NOC_ADDR); noc_addr = DEFAULT_NOC_ADDR; } /* * Map NocItf in process memory */ #ifndef DISABLE_MEMCALL int noc_fd; void* noc_register; /* Open /dev/mem file */ noc_fd = open ("/dev/mem", O_RDWR); if (noc_fd < 1) { perror(argv[0]); return -1; } noc_register = mmap(NULL,0x70, PROT_READ|PROT_WRITE, MAP_SHARED, noc_fd, noc_addr); #endif stringstream message; if ('p' == p_mode){ //producer if ('o' == p_type){ //order orderHeader order; order.is_sync_header= false; order.data_length = p_length; //TODO allocate targeted memory segment /* * Ask user for order content */ message.str(""); message <<"Order Type available: "; for(auto it : order_helper){ message << it.first << ": " << it.second <<"; ";}; message <<"\n choose: "; do{ long unsigned int readValue = get_luint(message.str()); if((readValue >= order_helper.begin()->first) && (readValue <= prev(order_helper.end())->first)){ order.cmd= (order_t) readValue; break; } else cout <<"Value entered out of range"; }while(1); message.str(""); message <<"job_id (task_id MSB)\n"; order.task_id= get_luint(message.str())<<16; message.str(""); message <<"order_id (task_id LSB)\n"; order.task_id += get_luint(message.str())&0xFFFF; message.str(""); message <<"remote address \n"; order.remote= get_luint(message.str()); if((NOC_MEMGET == order.cmd)||(NOC_MEMRTV ==order.cmd)){ message.str(""); message <<"local address \n"; order.local= get_luint(message.str()); }else if(NOC_ACK == order.cmd){ message.str(""); message <<"Ack Type available: "; for(auto it : ack_helper){ message<< it.first <<": " << it.second <<"; ";}; message <<"\n choose: "; do{ long unsigned int readValue = get_luint(message.str()); if((readValue >= ack_helper.begin()->first) && (readValue <= prev(ack_helper.end())->first)){ order.local= (ack_t) readValue; break; } else cout <<"Value entered out of range"; }while(1); } /*Send data on noc */ #ifndef DISABLE_MEMCALL while(0x00 != NOC_STATUS); // wait Noc rdy *((orderHeader*)_RNOC(RCVDATA)) = order; //set data request NOC_STATUS = CNOC_SORDER; //send cmd #endif cout << "Order sent: \n"; cout << "\t task_id: "<< order.task_id<<" \n"; string rdCmd = order_helper.find(order.cmd)->second; cout << "\t cmd: "<<dec<< rdCmd<<" \n"; cout << "\t @local: 0x"<<hex<< order.local<<" \n"; cout << "\t @remote: 0x"<<hex<< order.remote<<" \n"; cout << "\t @data: "<<dec<<order.data_length<<" \n"; } else{ //sync waitPoint sync; waitStatus wakeState; /* * Ask user for waitPoint content */ message.str(""); message <<"job_id (task_id MSB)\n"; sync.task_id = get_luint(message.str())<<16; message.str(""); message <<"order_id (task_id LSB)\n"; sync.task_id += get_luint(message.str())&0xFFFF; message.str(""); message <<"Ack Type available: "; for(auto it : ack_helper){ message<< it.first <<": " << it.second <<"; ";}; message <<"\n choose: "; do{ long unsigned int readValue = get_luint(message.str()); if((readValue >= ack_helper.begin()->first) && (readValue <= prev(ack_helper.end())->first)){ sync.ack_type= (ack_t) readValue; break; } else cout <<"Value entered out of range"; }while(1); /*Send data on noc */ #ifndef DISABLE_MEMCALL while(0x00 != NOC_STATUS); //wait Noc rdy *((waitPoint*)_RNOC(RCVDATA)) = sync; NOC_STATUS = CNOC_SYNC; //send cmd while(0x00 != NOC_STATUS); // wait Noc rdy wakeState = *((waitStatus*)_RNOC(SENDDATA)); #endif if ( WAITPOINT_SET == wakeState){ cout << "WaitPoint set valid: \n"; cout << "\t task_id: 0x"<<hex<< sync.task_id<<" \n"; string rdAck = ack_helper.find(sync.ack_type)->second; cout << "\t ack_type: 0x"<<hex<< rdAck<<" \n"; }else{ cout << "Invalid WaitPoint: event already occur or irrelevant event\n" << "\t => Instant WakeUp of the asking task \n"; } } } else if ('c' == p_mode){ //consumer if ('o' == p_type){ //order orderHeader order; order.is_sync_header=false; /*Send data on noc */ #ifndef DISABLE_MEMCALL while(0x00 != NOC_STATUS); // wait Noc rdy NOC_STATUS = CNOC_GORDER; //send cmd while(0x00 != NOC_STATUS); // wait Noc rdy order = *((orderHeader*)_RNOC(SENDDATA)); #endif if(order.is_sync_header) cout << "Order vector is empty \n"; else{ cout << "Received order: \n"; cout << "\t task_id: 0x"<< hex<< order.task_id<<" \n"; string rdCmd = order_helper.find(order.cmd)->second; cout << "\t cmd: "<<dec<< rdCmd<<" \n"; cout << "\t @local: 0x"<<hex<< order.local<<" \n"; cout << "\t @remote: 0x"<<hex<< order.remote<<" \n"; cout << "\t @data: "<<dec<< order.data_length<<" \n"; } } else{ //sync waitPoint wakeup; /*Send data on noc */ #ifndef DISABLE_MEMCALL while(0x00 != NOC_STATUS); // wait Noc rdy NOC_STATUS = CNOC_WAKEUP; //send cmd while(0x00 != NOC_STATUS); // wait Noc rdy wakeup = *((waitPoint*)_RNOC(SENDDATA)); #endif if(0 == wakeup.task_id) cout << "wakeup vector is empty \n"; else{ cout<< "WakeUp task: 0x"<<hex<< wakeup.task_id <<"("<< ack_helper.find(wakeup.ack_type)->second << ") \n"; } } }else if ('d' == p_mode){ // NoC discovery uint64_t clNb=0; /*Send data on noc */ #ifndef DISABLE_MEMCALL while(0x00 != NOC_STATUS); // wait Noc rdy NOC_STATUS = CNOC_DISCOVER; //send cmd while(0x00 != NOC_STATUS); // wait Noc rdy clNb = *((uint64_t*)_RNOC(SENDDATA)); uint64_t buffer[clNb+1]; memcpy(buffer,(void*)_RNOC(SENDDATA),(clNb)*sizeof(uint64_t)); #endif cout << "Cluster available are ["<<clNb<<"]:\n"; for( uint i=1; i<=clNb; i++){ cout << buffer[i] << "\t @0x"<<hex<<(buffer[i] >>32)<<": [" <<((buffer[i]&0xFF00)>>8) <<", "<<(buffer[i]&0x00FF)<<"]\n"; } }else if ('n' == p_mode){ // get NoC powerLog uint64_t buffer; uint32_t extractEnj; /*Send data on noc */ #ifndef DISABLE_MEMCALL while(0x00 != NOC_STATUS); // wait Noc rdy NOC_STATUS = CNOC_NOCPOWER; //send cmd while(0x00 != NOC_STATUS); // wait Noc rdy buffer = *((uint64_t*)_RNOC(SENDDATA)); #endif extractEnj = ((buffer>>32) &0xFFFFFFFF); cout << "Noc powerLog value are:\n" <<"\t Energy[J]: "<< (float) *(reinterpret_cast<float*>(&extractEnj)) <<"\n" <<"\t time[ns]: "<<dec<< (uint32_t) (buffer &0xFFFFFFFF)<<"\n"; } #ifndef DISABLE_MEMCALL /* Unmap memory segement and close file descriptor*/ munmap(noc_register, 0x70); close(noc_fd); #endif return 0; }
29.994048
105
0.564398
rouxb
71c2a97c8036fe35b9eaf432e6054cd94501ea10
7,945
cpp
C++
rcgen/cpp/inverse_dynamics.cpp
kmarkus/ublx-ur5_sim
51efa12446a7ef9ab5e3e783ce2a6409a3db390f
[ "BSD-3-Clause" ]
1
2020-11-07T11:39:31.000Z
2020-11-07T11:39:31.000Z
rcgen/cpp/inverse_dynamics.cpp
kmarkus/ublx-ur5_sim
51efa12446a7ef9ab5e3e783ce2a6409a3db390f
[ "BSD-3-Clause" ]
1
2020-11-10T16:03:37.000Z
2020-11-10T16:03:37.000Z
rcgen/cpp/inverse_dynamics.cpp
kmarkus/ublx-ur5_sim
51efa12446a7ef9ab5e3e783ce2a6409a3db390f
[ "BSD-3-Clause" ]
1
2020-11-07T10:57:43.000Z
2020-11-07T10:57:43.000Z
#include <iit/rbd/robcogen_commons.h> #include "inverse_dynamics.h" #include "inertia_properties.h" #ifndef EIGEN_NO_DEBUG #include <iostream> #endif using namespace std; using namespace iit::rbd; using namespace ur5::rcg; // Initialization of static-const data const ur5::rcg::InverseDynamics::ExtForces ur5::rcg::InverseDynamics::zeroExtForces(Force::Zero()); ur5::rcg::InverseDynamics::InverseDynamics(InertiaProperties& inertia, MotionTransforms& transforms) : inertiaProps( & inertia ), xm( & transforms ), shoulder_I(inertiaProps->getTensor_shoulder() ), upper_arm_I(inertiaProps->getTensor_upper_arm() ), forearm_I(inertiaProps->getTensor_forearm() ), wrist_1_I(inertiaProps->getTensor_wrist_1() ), wrist_2_I(inertiaProps->getTensor_wrist_2() ), wrist_3_I(inertiaProps->getTensor_wrist_3() ) { #ifndef EIGEN_NO_DEBUG std::cout << "Robot ur5, InverseDynamics::InverseDynamics()" << std::endl; std::cout << "Compiled with Eigen debug active" << std::endl; #endif shoulder_v.setZero(); upper_arm_v.setZero(); forearm_v.setZero(); wrist_1_v.setZero(); wrist_2_v.setZero(); wrist_3_v.setZero(); vcross.setZero(); } void ur5::rcg::InverseDynamics::id( JointState& jForces, const JointState& qd, const JointState& qdd, const ExtForces& fext) { firstPass(qd, qdd, fext); secondPass(jForces); } void ur5::rcg::InverseDynamics::G_terms(JointState& jForces) { // Link 'shoulder' shoulder_a = (xm->fr_shoulder_X_fr_base).col(iit::rbd::LZ) * ur5::rcg::g; shoulder_f = shoulder_I * shoulder_a; // Link 'upper_arm' upper_arm_a = (xm->fr_upper_arm_X_fr_shoulder) * shoulder_a; upper_arm_f = upper_arm_I * upper_arm_a; // Link 'forearm' forearm_a = (xm->fr_forearm_X_fr_upper_arm) * upper_arm_a; forearm_f = forearm_I * forearm_a; // Link 'wrist_1' wrist_1_a = (xm->fr_wrist_1_X_fr_forearm) * forearm_a; wrist_1_f = wrist_1_I * wrist_1_a; // Link 'wrist_2' wrist_2_a = (xm->fr_wrist_2_X_fr_wrist_1) * wrist_1_a; wrist_2_f = wrist_2_I * wrist_2_a; // Link 'wrist_3' wrist_3_a = (xm->fr_wrist_3_X_fr_wrist_2) * wrist_2_a; wrist_3_f = wrist_3_I * wrist_3_a; secondPass(jForces); } void ur5::rcg::InverseDynamics::C_terms(JointState& jForces, const JointState& qd) { // Link 'shoulder' shoulder_v(iit::rbd::AZ) = qd(SHOULDER_PAN); // shoulder_v = vJ, for the first link of a fixed base robot shoulder_f = vxIv(qd(SHOULDER_PAN), shoulder_I); // Link 'upper_arm' upper_arm_v = ((xm->fr_upper_arm_X_fr_shoulder) * shoulder_v); upper_arm_v(iit::rbd::AZ) += qd(SHOULDER_LIFT); motionCrossProductMx<Scalar>(upper_arm_v, vcross); upper_arm_a = (vcross.col(iit::rbd::AZ) * qd(SHOULDER_LIFT)); upper_arm_f = upper_arm_I * upper_arm_a + vxIv(upper_arm_v, upper_arm_I); // Link 'forearm' forearm_v = ((xm->fr_forearm_X_fr_upper_arm) * upper_arm_v); forearm_v(iit::rbd::AZ) += qd(ELBOW); motionCrossProductMx<Scalar>(forearm_v, vcross); forearm_a = (xm->fr_forearm_X_fr_upper_arm) * upper_arm_a + vcross.col(iit::rbd::AZ) * qd(ELBOW); forearm_f = forearm_I * forearm_a + vxIv(forearm_v, forearm_I); // Link 'wrist_1' wrist_1_v = ((xm->fr_wrist_1_X_fr_forearm) * forearm_v); wrist_1_v(iit::rbd::AZ) += qd(WR1); motionCrossProductMx<Scalar>(wrist_1_v, vcross); wrist_1_a = (xm->fr_wrist_1_X_fr_forearm) * forearm_a + vcross.col(iit::rbd::AZ) * qd(WR1); wrist_1_f = wrist_1_I * wrist_1_a + vxIv(wrist_1_v, wrist_1_I); // Link 'wrist_2' wrist_2_v = ((xm->fr_wrist_2_X_fr_wrist_1) * wrist_1_v); wrist_2_v(iit::rbd::AZ) += qd(WR2); motionCrossProductMx<Scalar>(wrist_2_v, vcross); wrist_2_a = (xm->fr_wrist_2_X_fr_wrist_1) * wrist_1_a + vcross.col(iit::rbd::AZ) * qd(WR2); wrist_2_f = wrist_2_I * wrist_2_a + vxIv(wrist_2_v, wrist_2_I); // Link 'wrist_3' wrist_3_v = ((xm->fr_wrist_3_X_fr_wrist_2) * wrist_2_v); wrist_3_v(iit::rbd::AZ) += qd(WR3); motionCrossProductMx<Scalar>(wrist_3_v, vcross); wrist_3_a = (xm->fr_wrist_3_X_fr_wrist_2) * wrist_2_a + vcross.col(iit::rbd::AZ) * qd(WR3); wrist_3_f = wrist_3_I * wrist_3_a + vxIv(wrist_3_v, wrist_3_I); secondPass(jForces); } void ur5::rcg::InverseDynamics::firstPass(const JointState& qd, const JointState& qdd, const ExtForces& fext) { // First pass, link 'shoulder' shoulder_a = (xm->fr_shoulder_X_fr_base).col(iit::rbd::LZ) * ur5::rcg::g; shoulder_a(iit::rbd::AZ) += qdd(SHOULDER_PAN); shoulder_v(iit::rbd::AZ) = qd(SHOULDER_PAN); // shoulder_v = vJ, for the first link of a fixed base robot shoulder_f = shoulder_I * shoulder_a + vxIv(qd(SHOULDER_PAN), shoulder_I) - fext[SHOULDER]; // First pass, link 'upper_arm' upper_arm_v = ((xm->fr_upper_arm_X_fr_shoulder) * shoulder_v); upper_arm_v(iit::rbd::AZ) += qd(SHOULDER_LIFT); motionCrossProductMx<Scalar>(upper_arm_v, vcross); upper_arm_a = (xm->fr_upper_arm_X_fr_shoulder) * shoulder_a + vcross.col(iit::rbd::AZ) * qd(SHOULDER_LIFT); upper_arm_a(iit::rbd::AZ) += qdd(SHOULDER_LIFT); upper_arm_f = upper_arm_I * upper_arm_a + vxIv(upper_arm_v, upper_arm_I) - fext[UPPER_ARM]; // First pass, link 'forearm' forearm_v = ((xm->fr_forearm_X_fr_upper_arm) * upper_arm_v); forearm_v(iit::rbd::AZ) += qd(ELBOW); motionCrossProductMx<Scalar>(forearm_v, vcross); forearm_a = (xm->fr_forearm_X_fr_upper_arm) * upper_arm_a + vcross.col(iit::rbd::AZ) * qd(ELBOW); forearm_a(iit::rbd::AZ) += qdd(ELBOW); forearm_f = forearm_I * forearm_a + vxIv(forearm_v, forearm_I) - fext[FOREARM]; // First pass, link 'wrist_1' wrist_1_v = ((xm->fr_wrist_1_X_fr_forearm) * forearm_v); wrist_1_v(iit::rbd::AZ) += qd(WR1); motionCrossProductMx<Scalar>(wrist_1_v, vcross); wrist_1_a = (xm->fr_wrist_1_X_fr_forearm) * forearm_a + vcross.col(iit::rbd::AZ) * qd(WR1); wrist_1_a(iit::rbd::AZ) += qdd(WR1); wrist_1_f = wrist_1_I * wrist_1_a + vxIv(wrist_1_v, wrist_1_I) - fext[WRIST_1]; // First pass, link 'wrist_2' wrist_2_v = ((xm->fr_wrist_2_X_fr_wrist_1) * wrist_1_v); wrist_2_v(iit::rbd::AZ) += qd(WR2); motionCrossProductMx<Scalar>(wrist_2_v, vcross); wrist_2_a = (xm->fr_wrist_2_X_fr_wrist_1) * wrist_1_a + vcross.col(iit::rbd::AZ) * qd(WR2); wrist_2_a(iit::rbd::AZ) += qdd(WR2); wrist_2_f = wrist_2_I * wrist_2_a + vxIv(wrist_2_v, wrist_2_I) - fext[WRIST_2]; // First pass, link 'wrist_3' wrist_3_v = ((xm->fr_wrist_3_X_fr_wrist_2) * wrist_2_v); wrist_3_v(iit::rbd::AZ) += qd(WR3); motionCrossProductMx<Scalar>(wrist_3_v, vcross); wrist_3_a = (xm->fr_wrist_3_X_fr_wrist_2) * wrist_2_a + vcross.col(iit::rbd::AZ) * qd(WR3); wrist_3_a(iit::rbd::AZ) += qdd(WR3); wrist_3_f = wrist_3_I * wrist_3_a + vxIv(wrist_3_v, wrist_3_I) - fext[WRIST_3]; } void ur5::rcg::InverseDynamics::secondPass(JointState& jForces) { // Link 'wrist_3' jForces(WR3) = wrist_3_f(iit::rbd::AZ); wrist_2_f += xm->fr_wrist_3_X_fr_wrist_2.transpose() * wrist_3_f; // Link 'wrist_2' jForces(WR2) = wrist_2_f(iit::rbd::AZ); wrist_1_f += xm->fr_wrist_2_X_fr_wrist_1.transpose() * wrist_2_f; // Link 'wrist_1' jForces(WR1) = wrist_1_f(iit::rbd::AZ); forearm_f += xm->fr_wrist_1_X_fr_forearm.transpose() * wrist_1_f; // Link 'forearm' jForces(ELBOW) = forearm_f(iit::rbd::AZ); upper_arm_f += xm->fr_forearm_X_fr_upper_arm.transpose() * forearm_f; // Link 'upper_arm' jForces(SHOULDER_LIFT) = upper_arm_f(iit::rbd::AZ); shoulder_f += xm->fr_upper_arm_X_fr_shoulder.transpose() * upper_arm_f; // Link 'shoulder' jForces(SHOULDER_PAN) = shoulder_f(iit::rbd::AZ); }
35.950226
111
0.670736
kmarkus
71c8b2edc7a73d4a97bb4860e43e1603f4bff6a0
3,043
cpp
C++
Source/SystemQOR/MSWindows/WinQL/Application/Comms/Network/WinQLNetworkHost.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQL/Application/Comms/Network/WinQLNetworkHost.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQL/Application/Comms/Network/WinQLNetworkHost.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//WinQLNetworkHost.cpp // Copyright Querysoft Limited 2013 // // 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 "WinQL/Application/Comms/Network/WinQLNetworkHost.h" #include "WinQAPI/WS2_32.h" //-------------------------------------------------------------------------------- namespace nsWin32 { __QOR_IMPLEMENT_OCLASS_LUID( CNetworkHost ); //-------------------------------------------------------------------------------- CNetworkHost::CNetworkHost() : m_WS32Library( nsWinQAPI::CWS2_32::Instance() ), m_pProtocolInfo( 0 ), m_ulProtocolCount( 0 ) { _WINQ_FCONTEXT( "CNetworkHost::CNetworkHost" ); EnumerateProtocols(); } //-------------------------------------------------------------------------------- CNetworkHost::~CNetworkHost() { _WINQ_FCONTEXT( "CNetworkHost::~CNetworkHost" ); m_ulProtocolCount = 0; delete [] m_pProtocolInfo; } //-------------------------------------------------------------------------------- void CNetworkHost::EnumerateProtocols() { _WINQ_FCONTEXT( "CNetworkHost::EnumerateProtocols" ); unsigned long ulBufferLength = 0; int iResult = m_WS32Library.WSAEnumProtocols( 0, 0, &ulBufferLength ); if( iResult != SOCKET_ERROR ) { m_pProtocolInfo = new nsWin32::WSAProtocolInfo[ ulBufferLength / sizeof( nsWin32::WSAProtocolInfo ) ]; m_ulProtocolCount = m_WS32Library.WSAEnumProtocols( 0, reinterpret_cast<::LPWSAPROTOCOL_INFO>( m_pProtocolInfo ), &ulBufferLength ); } } //-------------------------------------------------------------------------------- WSAProtocolInfo* CNetworkHost::GetProtocols( unsigned long& ulProtocolCount ) { _WINQ_FCONTEXT( "CNetworkHost::GetProtocols" ); ulProtocolCount = m_ulProtocolCount; return m_pProtocolInfo; } }//nsWin32
41.121622
135
0.658232
mfaithfull
71c9843a7801ae4a062c4836970af4235cf6c501
1,212
cpp
C++
pgf+/src/reader/CncFun.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
1
2019-05-03T18:00:39.000Z
2019-05-03T18:00:39.000Z
pgf+/src/reader/CncFun.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
null
null
null
pgf+/src/reader/CncFun.cpp
egladil/mscthesis
d6f0c9b1b1e73b749894405372f2edf01e746920
[ "BSD-2-Clause" ]
null
null
null
// // CncFun.cpp // pgf+ // // Created by Emil Djupfeldt on 2012-06-26. // Copyright (c) 2012 Chalmers University of Technology. All rights reserved. // #include <gf/reader/CncFun.h> namespace gf { namespace reader { CncFun::CncFun(const std::string& name, const std::vector<Sequence*>& sequences) : name(name), sequences(sequences) { } CncFun::~CncFun() { for (std::vector<Sequence*>::iterator it = sequences.begin(); it != sequences.end(); it++) { gf::release(*it); } } const std::string& CncFun::getName() const { return name; } const std::vector<Sequence*>& CncFun::getSequences() const { return sequences; } std::string CncFun::toString() const { std::string ret; ret = "Name: "; ret+= name; ret+= ", indices:"; for (std::vector<Sequence*>::const_iterator it = sequences.begin(); it != sequences.end(); it++) { ret+= " " + (*it)->toString(); } return ret; } } }
26.347826
110
0.476073
egladil
71cfda41c045686f2c34558cdfb67b5483f904c8
1,303
hpp
C++
include/xul/net/http/http_request_parser.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/net/http/http_request_parser.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/net/http/http_request_parser.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include <xul/net/http/http_message_parser.hpp> #include <xul/net/url_request.hpp> //#include <xul/net/url_encoding.hpp> namespace xul { class http_request_parser : public http_message_parser { public: /// http_response_parser ready to parse the request method. explicit http_request_parser(url_request* req) { m_request = req; } const url_request* get_request() const { return m_request.get(); } url_request* get_request() { return m_request.get(); } /// Reset to initial parser state. void reset() { http_message_parser::reset(); m_request->clear(); } protected: virtual url_message& get_message() { return *m_request; } virtual int parse_first_line(const std::string& line) { std::vector<std::string> parts; xul::strings::split_of(parts, line, std::string(" \t")); if (parts.size() != 3) return error_invalid_request_line; int ret = parse_protocol(parts[2]); if (ret < 0) return ret; m_request->set_method(parts[0].c_str()); std::string urlstr = parts[1]; m_request->set_url(urlstr.c_str()); return 0; } private: boost::intrusive_ptr<url_request> m_request; }; }
21.716667
64
0.618573
hindsights
71df93f766722e0c9cfde244b56c6dd7e4437207
418
cpp
C++
codeforces/practices/800/236A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
codeforces/practices/800/236A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
codeforces/practices/800/236A.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Codeforces Round #146 (Div. 2) - A. Boy or Girl https://codeforces.com/problemset/problem/236/A */ #include <bits/stdc++.h> using namespace std; #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) int main() { FAST_INP; string s; cin >> s; unordered_set<char> ss; for(char c:s) ss.insert(c); cout << (ss.size()&1?"IGNORE HIM!":"""CHAT WITH HER!") << "\n"; return 0; }
19.904762
64
0.617225
wingkwong
71edd616e687bde427dd3f8738f38873732805f7
7,388
cpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/ss/bizhawk.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
45
2017-07-24T05:31:06.000Z
2019-03-29T12:23:57.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/ss/bizhawk.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
5
2017-07-24T02:37:24.000Z
2018-12-28T16:51:06.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/ss/bizhawk.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
10
2017-07-24T02:11:43.000Z
2018-12-27T20:49:37.000Z
#include "ss.h" #include <memory> #include "cdrom/cdromif.h" #include "cdb.h" #include "smpc.h" #include "cart.h" #include <ctime> #define EXPORT extern "C" ECL_EXPORT using namespace MDFN_IEN_SS; int32 (*FirmwareSizeCallback)(const char *filename); void (*FirmwareDataCallback)(const char *filename, uint8 *dest); EXPORT void SetFirmwareCallbacks(int32 (*sizecallback)(const char *filename), void (*datacallback)(const char *filename, uint8 *dest)) { FirmwareSizeCallback = sizecallback; FirmwareDataCallback = datacallback; } struct FrontendTOC { int32 FirstTrack; int32 LastTrack; int32 DiskType; struct { int32 Adr; int32 Control; int32 Lba; int32 Valid; } Tracks[101]; }; static void (*ReadTOCCallback)(int disk, FrontendTOC *dest); static void (*ReadSector2448Callback)(int disk, int lba, uint8 *dest); EXPORT void SetCDCallbacks(void (*toccallback)(int disk, FrontendTOC *dest), void (*sectorcallback)(int disk, int lba, uint8 *dest)) { ReadTOCCallback = toccallback; ReadSector2448Callback = sectorcallback; } class MyCDIF : public CDIF { private: int disk; public: MyCDIF(int disk) : disk(disk) { FrontendTOC t; ReadTOCCallback(disk, &t); disc_toc.first_track = t.FirstTrack; disc_toc.last_track = t.LastTrack; disc_toc.disc_type = t.DiskType; for (int i = 0; i < 101; i++) { disc_toc.tracks[i].adr = t.Tracks[i].Adr; disc_toc.tracks[i].control = t.Tracks[i].Control; disc_toc.tracks[i].lba = t.Tracks[i].Lba; disc_toc.tracks[i].valid = t.Tracks[i].Valid; } } virtual void HintReadSector(int32 lba) {} virtual bool ReadRawSector(uint8 *buf, int32 lba) { ReadSector2448Callback(disk, lba, buf); return true; } virtual bool ReadRawSectorPWOnly(uint8 *pwbuf, int32 lba, bool hint_fullread) { uint8 buff[2448]; ReadSector2448Callback(disk, lba, buff); memcpy(pwbuf, buff + 2352, 96); return true; } }; static std::vector<CDIF *> CDInterfaces; static uint32 *FrameBuffer; static uint8 IsResetPushed; // 1 or 0 namespace MDFN_IEN_SS { extern bool LoadCD(std::vector<CDIF *> *CDInterfaces); } EXPORT bool Init(int numDisks, int cartType, int regionDefault, int regionAutodetect) { setting_ss_cart = cartType; setting_ss_region_autodetect = regionAutodetect; setting_ss_region_default = regionDefault; FrameBuffer = (uint32 *)alloc_invisible(1024 * 1024 * sizeof(*FrameBuffer)); for (int i = 0; i < numDisks; i++) CDInterfaces.push_back(new MyCDIF(i)); auto ret = LoadCD(&CDInterfaces); if (ret) SMPC_SetInput(12, nullptr, &IsResetPushed); return ret; } EXPORT void HardReset() { // soft reset is handled as a normal button SS_Reset(true); } EXPORT void SetDisk(int disk, bool open) { CDB_SetDisc(open, disk < 0 ? nullptr : CDInterfaces[disk]); } int setting_ss_slstartp = 0; int setting_ss_slendp = 255; int setting_ss_slstart = 0; int setting_ss_slend = 239; int setting_ss_region_default = SMPC_AREA_JP; int setting_ss_cart = CART_NONE; bool setting_ss_correct_aspect = true; bool setting_ss_h_blend = false; bool setting_ss_h_overscan = true; bool setting_ss_region_autodetect = true; bool setting_ss_input_sport1_multitap = false; bool setting_ss_input_sport0_multitap = false; namespace MDFN_IEN_SS { extern void Emulate(EmulateSpecStruct *espec_arg); } static uint8 ControllerInput[12 * 32]; bool InputLagged; EXPORT void SetControllerData(const uint8_t* controllerData) { memcpy(ControllerInput, controllerData, sizeof(ControllerInput)); } struct MyFrameInfo: public FrameInfo { int32_t ResetPushed; }; EXPORT void FrameAdvance(MyFrameInfo& f) { EmulateSpecStruct e; int32 LineWidths[1024]; memset(LineWidths, 0, sizeof(LineWidths)); e.pixels = FrameBuffer; e.pitch32 = 1024; e.LineWidths = LineWidths; e.SoundBuf = f.SoundBuffer; e.SoundBufMaxSize = 8192; IsResetPushed = f.ResetPushed; InputLagged = true; Emulate(&e); f.Samples = e.SoundBufSize; f.Cycles = e.MasterCycles; f.Lagged = InputLagged; int w = 256; for (int i = 0; i < e.h; i++) w = std::max(w, LineWidths[i]); const uint32 *src = FrameBuffer; uint32 *dst = f.VideoBuffer; const int srcp = 1024; const int dstp = w; src += e.y * srcp + e.x; for (int j = 0; j < e.h; j++, src += srcp, dst += dstp) { memcpy(dst, src, LineWidths[j + e.y] * sizeof(*dst)); } f.Width = w; f.Height = e.h; } static const char *DeviceNames[] = { "none", "gamepad", "3dpad", "mouse", "wheel", "mission", "dmission", "keyboard"}; EXPORT void SetupInput(const int *portdevices, const int *multitaps) { for (int i = 0; i < 2; i++) SMPC_SetMultitap(i, multitaps[i]); for (int i = 0; i < 12; i++) SMPC_SetInput(i, DeviceNames[portdevices[i]], ControllerInput + i * 32); } void (*InputCallback)(); EXPORT void SetInputCallback(void (*callback)()) { InputCallback = callback; } static std::vector<MemoryArea> MemoryAreas; void AddMemoryDomain(const char *name, const void *ptr, int size, int flags) { MemoryArea m; m.Data = (void*)ptr; m.Name = name; m.Size = size; m.Flags = flags; MemoryAreas.push_back(m); } EXPORT void GetMemoryAreas(MemoryArea* m) { memcpy(m, MemoryAreas.data(), MemoryAreas.size() * sizeof(MemoryArea)); } EXPORT void SetRtc(int64 ticks, int language) { time_t time = ticks; const struct tm *tm = gmtime(&time); SMPC_SetRTC(tm, language); } namespace MDFN_IEN_SS { extern bool CorrectAspect; extern bool ShowHOverscan; extern bool DoHBlend; extern int LineVisFirst; extern int LineVisLast; } EXPORT void SetVideoParameters(bool correctAspect, bool hBlend, bool hOverscan, int sls, int sle) { CorrectAspect = correctAspect; ShowHOverscan = hOverscan; DoHBlend = hBlend; LineVisFirst = sls; LineVisLast = sle; } // if (BackupRAM_Dirty)SaveBackupRAM(); // if (CART_GetClearNVDirty())SaveCartNV(); /*static MDFN_COLD void CloseGame(void) { try { SaveBackupRAM(); } catch(std::exception& e) { MDFN_PrintError("%s", e.what()); } try { SaveCartNV(); } catch(std::exception& e) { MDFN_PrintError("%s", e.what()); } try { SaveRTC(); } catch(std::exception& e) { MDFN_PrintError("%s", e.what()); } Cleanup(); }*/ /* static MDFN_COLD void BackupCartNV(void) { const char* ext = nullptr; void* nv_ptr = nullptr; uint64 nv_size = 0; CART_GetNVInfo(&ext, &nv_ptr, &nv_size); if(ext) MDFN_BackupSavFile(10, ext); }*/ /*static MDFN_COLD void LoadCartNV(void) { const char* ext = nullptr; void* nv_ptr = nullptr; uint64 nv_size = 0; CART_GetNVInfo(&ext, &nv_ptr, &nv_size); if(ext) { //FileStream nvs(MDFN_MakeFName(MDFNMKF_SAV, 0, ext), FileStream::MODE_READ); GZFileStream nvs(MDFN_MakeFName(MDFNMKF_SAV, 0, ext), GZFileStream::MODE::READ); nvs.read(nv_ptr, nv_size); } } static MDFN_COLD void SaveCartNV(void) { const char* ext = nullptr; void* nv_ptr = nullptr; uint64 nv_size = 0; CART_GetNVInfo(&ext, &nv_ptr, &nv_size); if(ext) { //FileStream nvs(MDFN_MakeFName(MDFNMKF_SAV, 0, ext), FileStream::MODE_WRITE_INPLACE); GZFileStream nvs(MDFN_MakeFName(MDFNMKF_SAV, 0, ext), GZFileStream::MODE::WRITE); nvs.write(nv_ptr, nv_size); nvs.close(); } }*/ /*static MDFN_COLD void SaveRTC(void) { FileStream sds(MDFN_MakeFName(MDFNMKF_SAV, 0, "smpc"), FileStream::MODE_WRITE_INPLACE); SMPC_SaveNV(&sds); sds.close(); } static MDFN_COLD void LoadRTC(void) { FileStream sds(MDFN_MakeFName(MDFNMKF_SAV, 0, "smpc"), FileStream::MODE_READ); SMPC_LoadNV(&sds); }*/ int main() { return 0; }
22.455927
134
0.714672
redscientistlabs
71ee02ef79ec381ecd6e3db6a7e79280dd498cfa
487
cpp
C++
p551/p551.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
1
2019-10-07T05:00:21.000Z
2019-10-07T05:00:21.000Z
p551/p551.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
p551/p551.cpp
suzyz/leetcode_practice
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
[ "MIT" ]
null
null
null
class Solution { public: bool checkRecord(string s) { int n = s.length(); int countA = 0; for (int i = 0; i < n; ++i) if (s[i] == 'A') { if (countA) return false; ++countA; } else if (s[i] == 'L') { if (i > 1 && s[i-1] == 'L' && s[i-2] == 'L') return false; } return true; } };
24.35
64
0.297741
suzyz
71ef881fafb7f6a972f732662b84f9224cf50779
1,899
cpp
C++
Greedy Algo/HuffmanEncoding.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
22
2021-10-01T20:14:15.000Z
2022-02-22T15:27:20.000Z
Greedy Algo/HuffmanEncoding.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
15
2021-10-01T20:24:55.000Z
2021-10-31T05:55:14.000Z
Greedy Algo/HuffmanEncoding.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
76
2021-10-01T20:01:06.000Z
2022-03-02T16:15:24.000Z
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: struct node { char data; int freq; node *left, *right; node(char d, int f) { data = d; freq = f; left = NULL; right = NULL; } }; struct cmp { bool operator()(node *a, node *b) { return a->freq > b->freq; } }; void print(node *root, vector<string> &result, string str) { if (root == NULL) return; if (root->data != '$') result.push_back(str); print(root->left, result, str + "0"); print(root->right, result, str + "1"); } vector<string> huffmanCodes(string S, vector<int> f, int N) { // Code here priority_queue<node *, vector<node *>, cmp> pq; for (int i = 0; i < N; i++) { pq.push(new node(S[i], f[i])); } node *left, *right, *top; while (pq.size() != 1) { left = pq.top(); pq.pop(); right = pq.top(); pq.pop(); top = new node('$', left->freq + right->freq); top->left = left; top->right = right; pq.push(top); } vector<string> result; print(pq.top(), result, ""); return result; } }; // { Driver Code Starts. int main() { int T; cin >> T; while (T--) { string S; cin >> S; int N = S.length(); vector<int> f(N); for (int i = 0; i < N; i++) { cin >> f[i]; } Solution ob; vector<string> ans = ob.huffmanCodes(S, f, N); for (auto i : ans) cout << i << " "; cout << "\n"; } return 0; } // } Driver Code Ends
22.081395
63
0.415482
Bhannasa
71f16752fe7540998567e65b1bf8f3fc29418438
1,886
cc
C++
src/update_engine/action_unittest.cc
remarkableno/update_engine
cdffd37e3f005b7738bf596b9bc8d4155e4c7e15
[ "BSD-3-Clause" ]
12
2019-06-26T18:32:06.000Z
2022-03-01T17:32:36.000Z
src/update_engine/action_unittest.cc
remarkableno/update_engine
cdffd37e3f005b7738bf596b9bc8d4155e4c7e15
[ "BSD-3-Clause" ]
6
2018-11-22T21:11:34.000Z
2022-02-24T13:36:57.000Z
src/update_engine/action_unittest.cc
remarkableno/update_engine
cdffd37e3f005b7738bf596b9bc8d4155e4c7e15
[ "BSD-3-Clause" ]
5
2018-06-24T13:19:40.000Z
2020-10-15T17:10:56.000Z
// Copyright (c) 2010 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include <gtest/gtest.h> #include "update_engine/action.h" #include "update_engine/action_processor.h" using std::string; namespace chromeos_update_engine { using chromeos_update_engine::ActionPipe; class ActionTestAction; template<> class ActionTraits<ActionTestAction> { public: typedef string OutputObjectType; typedef string InputObjectType; }; // This is a simple Action class for testing. struct ActionTestAction : public Action<ActionTestAction> { typedef string InputObjectType; typedef string OutputObjectType; ActionPipe<string> *in_pipe() { return in_pipe_.get(); } ActionPipe<string> *out_pipe() { return out_pipe_.get(); } ActionProcessor *processor() { return processor_; } void PerformAction() {} void CompleteAction() { ASSERT_TRUE(processor()); processor()->ActionComplete(this, kActionCodeSuccess); } string Type() const { return "ActionTestAction"; } }; class ActionTest : public ::testing::Test { }; // This test creates two simple Actions and sends a message via an ActionPipe // from one to the other. TEST(ActionTest, SimpleTest) { ActionTestAction action; EXPECT_FALSE(action.in_pipe()); EXPECT_FALSE(action.out_pipe()); EXPECT_FALSE(action.processor()); EXPECT_FALSE(action.IsRunning()); ActionProcessor action_processor; action_processor.EnqueueAction(&action); EXPECT_EQ(&action_processor, action.processor()); action_processor.StartProcessing(); EXPECT_TRUE(action.IsRunning()); action.CompleteAction(); EXPECT_FALSE(action.IsRunning()); } } // namespace chromeos_update_engine
24.179487
77
0.706787
remarkableno
71f4230c8dd4de135b614cd365ad3db398c06fe7
414
cpp
C++
ianlmk/cs161b/zybooks/10.10.1.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
null
null
null
ianlmk/cs161b/zybooks/10.10.1.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
1
2022-03-25T18:34:47.000Z
2022-03-25T18:35:23.000Z
ianlmk/cs161b/zybooks/10.10.1.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(); void SwapValues(int &, int &); int main() { int userVal1; int userVal2; cin >> userVal1 >> userVal2; SwapValues(userVal1, userVal2); cout << userVal1 << " " << userVal2 << endl; return 0; } void SwapValues(int &userVal1, int &userVal2) { int num1, num2; num1 = userVal1; num2 = userVal2; userVal1 = num2; userVal2 = num1; }
13.8
47
0.625604
ianlmk
71f69a138d49ac9f66e58c06b0edc0f6d99c94e8
1,331
cpp
C++
Source/GUI/UWP/HtmlView.xaml.cpp
buckmelanoma/MediaInfo
cf38b0e3d0e6ee2565f49276f423a5792ed62962
[ "BSD-2-Clause" ]
743
2015-01-13T23:16:53.000Z
2022-03-31T22:56:27.000Z
Source/GUI/UWP/HtmlView.xaml.cpp
buckmelanoma/MediaInfo
cf38b0e3d0e6ee2565f49276f423a5792ed62962
[ "BSD-2-Clause" ]
317
2015-07-28T17:50:14.000Z
2022-03-08T02:41:19.000Z
Source/GUI/UWP/HtmlView.xaml.cpp
buckmelanoma/MediaInfo
cf38b0e3d0e6ee2565f49276f423a5792ed62962
[ "BSD-2-Clause" ]
134
2015-01-30T05:33:51.000Z
2022-03-21T09:39:38.000Z
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //--------------------------------------------------------------------------- #include "pch.h" #include "HtmlView.xaml.h" //--------------------------------------------------------------------------- using namespace MediaInfo; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; //--------------------------------------------------------------------------- // Constructor/Destructor //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- HtmlView::HtmlView(ReportViewModel^ CurrentReport) : _CurrentReport(CurrentReport) { InitializeComponent(); HtmlControl->NavigateToString(CurrentReport->ReportHtml); }
36.972222
83
0.523666
buckmelanoma
71f6bb713cb9d4775b72a21dc13686a4ec9ff3e6
953
hpp
C++
test/mock/core/crypto/ed25519_provider_mock.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
test/mock/core/crypto/ed25519_provider_mock.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
test/mock/core/crypto/ed25519_provider_mock.hpp
igor-egorov/kagome
b2a77061791aa7c1eea174246ddc02ef5be1b605
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef KAGOME_TEST_MOCK_CORE_CRYPTO_ED25519_PROVIDER_MOCK_HPP #define KAGOME_TEST_MOCK_CORE_CRYPTO_ED25519_PROVIDER_MOCK_HPP #include "crypto/ed25519_provider.hpp" #include <gmock/gmock.h> namespace kagome::crypto { class Ed25519ProviderMock : public Ed25519Provider { public: Ed25519Keypair; Ed25519Keypair; MOCK_CONST_METHOD2(sign, outcome::result<Ed25519Signature>(const Ed25519Keypair &, gsl::span<uint8_t>)); MOCK_CONST_METHOD3( verify, outcome::result<bool>(const Ed25519Signature &signature, gsl::span<uint8_t> message, const Ed25519PublicKey &public_key)); }; } // namespace kagome::crypto #endif // KAGOME_TEST_MOCK_CORE_CRYPTO_ED25519_PROVIDER_MOCK_HPP
29.78125
80
0.656873
igor-egorov
71fbb264bec8f56481ed01fb146cc21e66454b00
5,762
hpp
C++
src/_viennacl/common.hpp
viennacl/pyviennacl-dev
3509318db9eb4cc788f262f4e3924775f0cf3a01
[ "MIT" ]
26
2015-01-03T20:06:05.000Z
2021-09-09T09:23:14.000Z
src/_viennacl/common.hpp
viennacl/pyviennacl-dev
3509318db9eb4cc788f262f4e3924775f0cf3a01
[ "MIT" ]
18
2015-01-12T00:08:42.000Z
2021-01-18T10:31:06.000Z
src/_viennacl/common.hpp
viennacl/pyviennacl-dev
3509318db9eb4cc788f262f4e3924775f0cf3a01
[ "MIT" ]
5
2015-09-17T16:42:58.000Z
2022-03-21T19:21:43.000Z
#ifndef _PYVIENNACL_H #define _PYVIENNACL_H #include <boost/python.hpp> #include <boost/numpy.hpp> #include <viennacl/tools/shared_ptr.hpp> #include <viennacl/matrix.hpp> #include <viennacl/linalg/prod.hpp> #define CONCAT(...) __VA_ARGS__ namespace vcl = viennacl; namespace bp = boost::python; namespace np = boost::numpy; typedef void* NoneT; typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; namespace viennacl { namespace tools { template <typename T> T* get_pointer(vcl::tools::shared_ptr<T> const& p) { return p.get(); } } } namespace boost { namespace python { template <typename T> struct pointee<vcl::tools::shared_ptr<T> > { typedef T type; }; } } // TODO: Use ViennaCL operation tags? enum op_t { op_inner_prod=0, // 0 op_outer_prod, // 1 op_element_pow, // 2 op_norm_1, // 3 op_norm_2, // 4 op_norm_inf, // 5 op_norm_frobenius, // 6 op_index_norm_inf, // 7 op_plane_rotation, // 8 op_prod, // 9 op_solve, // 10 op_solve_precond, // 11 op_inplace_solve, // 12 op_fft_2d, // 13 op_ifft_2d, // 14 op_inplace_fft_2d, // 15 op_inplace_ifft_2d,// 16 op_convolve_2d, // 17 op_convolve_i_2d, // 18 op_fft_3d, // 19 op_inplace_fft_3d, // 20 op_fft_normalize_2d, // 21 op_inplace_qr, // 22 op_inplace_qr_apply_trans_q, // 23 op_recoverq, // 24 op_nmf, // 25 op_svd, // 26 op_diag, // 27 op_row, // 28 op_column // 29 }; // Generic operation dispatch class -- specialised for different ops template <class ReturnT, class Operand1T, class Operand2T, class Operand3T, class Operand4T, op_t op> struct pyvcl_worker { static ReturnT do_op(void* o) {} }; // This class wraps operations in a type-independent way up to 4 operands. // It's mainly used to simplify and consolidate calling conventions in the // main module code. template <class ReturnT, class Operand1T, class Operand2T, class Operand3T, class Operand4T, op_t op> struct pyvcl_op { Operand1T operand1; Operand2T operand2; Operand3T operand3; Operand4T operand4; friend struct pyvcl_worker<ReturnT, Operand1T, Operand2T, Operand3T, Operand4T, op>; pyvcl_op(Operand1T opand1, Operand2T opand2, Operand3T opand3, Operand4T opand4) : operand1(opand1), operand2(opand2), operand3(opand3), operand4(opand4) { } // Should I just use operator(), I wonder.. ReturnT do_op() { return pyvcl_worker<ReturnT, Operand1T, Operand2T, Operand3T, Operand4T, op>::do_op(*this); } }; // Convenient operation dispatch functions. // These functions make setting up and calling the pyvcl_op class much // simpler for the specific 1-, 2-, 3- and 4-operand cases. template <class ReturnT, class Operand1T, op_t op> ReturnT pyvcl_do_1ary_op(Operand1T a) { pyvcl_op<ReturnT, Operand1T, NoneT, NoneT, NoneT, op> o (a, NULL, NULL, NULL); return o.do_op(); } template <class ReturnT, class Operand1T, class Operand2T, op_t op> ReturnT pyvcl_do_2ary_op(Operand1T a, Operand2T b) { pyvcl_op<ReturnT, Operand1T, Operand2T, NoneT, NoneT, op> o (a, b, NULL, NULL); return o.do_op(); } template <class ReturnT, class Operand1T, class Operand2T, class Operand3T, op_t op> ReturnT pyvcl_do_3ary_op(Operand1T a, Operand2T b, Operand3T c) { pyvcl_op<ReturnT, Operand1T, Operand2T, Operand3T, NoneT, op> o (a, b, c, NULL); return o.do_op(); } template <class ReturnT, class Operand1T, class Operand2T, class Operand3T, class Operand4T, op_t op> ReturnT pyvcl_do_4ary_op(Operand1T a, Operand2T b, Operand3T c, Operand4T d) { pyvcl_op<ReturnT, Operand1T, Operand2T, Operand3T, Operand4T, op> o (a, b, c, d); return o.do_op(); } // These macros define specialisations of the pyvcl_worker class // which is used to dispatch viennacl operations. #define OP_TEMPLATE template <class ReturnT, \ class Operand1T, class Operand2T, \ class Operand3T, class Operand4T> #define PYVCL_WORKER_STRUCT(OP) OP_TEMPLATE \ struct pyvcl_worker<ReturnT, \ Operand1T, Operand2T, \ Operand3T, Operand4T, \ OP> #define DO_OP_FUNC(OP) PYVCL_WORKER_STRUCT(OP) { \ static ReturnT do_op(pyvcl_op<ReturnT, \ Operand1T, Operand2T, \ Operand3T, Operand4T, \ OP>& o) \ #define CLOSE_OP_FUNC } DO_OP_FUNC(op_prod) { return vcl::linalg::prod(o.operand1, o.operand2); } CLOSE_OP_FUNC; #define COMMA , #define DISAMBIGUATE_FUNCTION_PTR(RET, OLD_NAME, NEW_NAME, ARGS) \ RET (*NEW_NAME) ARGS = &OLD_NAME; #define DISAMBIGUATE_CLASS_FUNCTION_PTR(CLASS, RET, OLD_NAME, NEW_NAME, ARGS)\ RET (CLASS::*NEW_NAME) ARGS = &CLASS::OLD_NAME; #define ENUM_VALUE(NS, V) .value( #V, NS :: V ) #define PYVCL_SUBMODULE(NAME) void export_##NAME() #define PYTHON_SCOPE_SUBMODULE(NAME) \ bp::object NAME##_submodule \ (bp::handle<>(bp::borrowed(PyImport_AddModule("_viennacl." #NAME)))); \ bp::scope().attr(#NAME) = NAME##_submodule; \ bp::scope NAME##_scope = NAME##_submodule; #endif
26.072398
78
0.615064
viennacl
71fbbb89ba5add52b43bb7c49697a429b7080609
7,302
cpp
C++
src/Screen.cpp
anonidiot/Wizardry8Editor
2e844b8bbab9adbee5796de3190f478a91cc829a
[ "BSD-2-Clause" ]
null
null
null
src/Screen.cpp
anonidiot/Wizardry8Editor
2e844b8bbab9adbee5796de3190f478a91cc829a
[ "BSD-2-Clause" ]
null
null
null
src/Screen.cpp
anonidiot/Wizardry8Editor
2e844b8bbab9adbee5796de3190f478a91cc829a
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2022 Anonymous Idiot * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QResizeEvent> #include "Screen.h" #include "main.h" #include "WButton.h" #include "WCheckBox.h" #include "WDDL.h" #include "WImage.h" #include "WItem.h" #include "WLabel.h" #include "WLineEdit.h" #include "WScrollBar.h" #include "WSpinBox.h" Screen::Screen(QWidget *parent) : QWidget(parent), Wizardry8Scalable(::getAppScale()) { } Screen::~Screen() { } void Screen::resetScreen(void *, void *) { } void Screen::setScale(double scale) { m_scale = scale; QList<QWidget *> widgets = this->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly); for (int k=0; k<widgets.size(); k++) { // No, we can't go straight to this in the findChildren() call above, because // it's a slim 'interface' that doesn't inherit from QObject if (Wizardry8Scalable *w = dynamic_cast<Wizardry8Scalable *>(widgets[k])) { w->setScale( m_scale ); } } this->resize( sizeHint() ); this->update(); } QSize Screen::minimumSizeHint() const { return QSize( ORIGINAL_DIM_X, ORIGINAL_DIM_Y ); } // Many QT components cache the initial response to this call, so // they have a stale copy of it when the scale changes. invalidate()ing // that cache doesn't actually work with widget hierarchies - they continue // to use the cached value anyway, but we direct call this from MainWindow // so _we_ at least will always get the right value QSize Screen::sizeHint() const { return QSize( m_scale * ORIGINAL_DIM_X, m_scale * ORIGINAL_DIM_Y ); } void Screen::resizeEvent(QResizeEvent *event) { double h_scale = (double)event->size().width() / (double)ORIGINAL_DIM_X; double v_scale = (double)event->size().height() / (double)ORIGINAL_DIM_Y; if (h_scale < v_scale) m_scale = h_scale; else m_scale = v_scale; ::setAppScale( m_scale ); QList<QWidget *> widgets = this->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly); for (int k=0; k<widgets.size(); k++) { // We can't go straight to this in the findChildren() call above, because // it's a slim 'interface' that doesn't inherit from QObject if (Wizardry8Scalable *w = dynamic_cast<Wizardry8Scalable *>(widgets[k])) { w->setScale( m_scale ); } } this->update(); } void Screen::setVisible( bool visible ) { QObjectList kids = children(); for (int k=0; k<kids.size(); k++) { if (QWidget *q = qobject_cast<QWidget *>(kids.at(k))) { q->setVisible( visible ); } } QWidget::setVisible( visible ); } // static method QMap<int, QWidget *> Screen::widgetInit( struct layout *widgets, int num_widgets, QWidget *parent ) { QMap<int, QWidget *> widgetsMap; widgetsMap.clear(); for (int k=0; k<num_widgets; k++) { QWidget *w = widgets[k].widget; if (widgets[k].trigger) { if (WLabel *label = qobject_cast<WLabel *>(w)) { connect( label, SIGNAL(clicked(bool)), parent, widgets[k].trigger ); connect( label, SIGNAL(mouseOver(bool)), parent, SLOT(mouseOverLabel(bool)) ); } else if (WLineEdit *le = qobject_cast<WLineEdit *>(w)) { connect( le, SIGNAL(textEdited(const QString&)), parent, widgets[k].trigger ); } else if (WCheckBox *cb = qobject_cast<WCheckBox *>(w)) { connect( cb, SIGNAL(stateChanged(int)), parent, widgets[k].trigger ); } else if (WImage *im = qobject_cast<WImage *>(w)) { connect( im, SIGNAL(clicked(bool)), parent, widgets[k].trigger ); } else if (WItem *im = qobject_cast<WItem *>(w)) { connect( im, SIGNAL(clicked(bool)), parent, widgets[k].trigger ); } else if (WButton *button = qobject_cast<WButton *>(w)) { connect( button, SIGNAL(clicked(bool)), parent, widgets[k].trigger ); } else if (WDDL *ddl = qobject_cast<WDDL *>(w)) { connect( ddl, SIGNAL(valueChanged(int)), parent, widgets[k].trigger ); } else if (WSpinBox *sb = qobject_cast<WSpinBox *>(w)) { connect( sb, SIGNAL(valueChanged(int)), parent, widgets[k].trigger ); } else if (WScrollBar *scroll_bar = qobject_cast<WScrollBar *>(w)) { connect( scroll_bar, SIGNAL(valueChanged(int)), parent, widgets[k].trigger ); } } // Common for all widgets if (w != NULL) { double sc = 0.0; if (Wizardry8Scalable *p = dynamic_cast<Wizardry8Scalable *>(parent)) { sc = p->getScale(); } else { sc = ::getAppScale(); } if (Wizardry8Scalable *s = dynamic_cast<Wizardry8Scalable *>(w)) { s->setBaseRect( widgets[k].pos ); s->setScale( sc ); } else { w->move( widgets[k].pos.topLeft() * sc ); w->resize( widgets[k].pos.size() * sc ); } if (widgets[k].toolTip != -1) { w->setToolTip( ::getStringTable()->getString( widgets[k].toolTip ) ); } if (widgets[k].id != 0) // NO_ID should always be 0 { widgetsMap.insert( widgets[k].id, w ); } } } return widgetsMap; } void Screen::mouseOverLabel(bool on) { if (WLabel *q = qobject_cast<WLabel *>(this->sender())) { if (on) q->setStyleSheet("QLabel {color: #169e16}"); // Green else q->setStyleSheet("QLabel {color: #e0e0c3}"); // Light yellow } }
31.747826
100
0.589565
anonidiot
9f95de78124dbd0c656859e902d87bc881ec78b7
2,637
cc
C++
dcmimgle/libsrc/diovlimg.cc
palmerc/dcmtk
716832be091d138f3e119c47a4e1e243f5b261d3
[ "Apache-2.0" ]
29
2020-02-13T17:40:16.000Z
2022-03-12T14:58:22.000Z
dcmimgle/libsrc/diovlimg.cc
palmerc/dcmtk
716832be091d138f3e119c47a4e1e243f5b261d3
[ "Apache-2.0" ]
20
2020-03-20T18:06:31.000Z
2022-02-25T08:38:08.000Z
dcmimgle/libsrc/diovlimg.cc
palmerc/dcmtk
716832be091d138f3e119c47a4e1e243f5b261d3
[ "Apache-2.0" ]
9
2020-03-20T17:29:55.000Z
2022-02-14T10:15:33.000Z
/* * * Copyright (C) 1996-2016, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmimgle * * Author: Joerg Riesmeier * * Purpose: DicomOverlayImage (Source) * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/dcmdata/dctypes.h" #include "dcmtk/dcmimgle/diovlimg.h" #include "dcmtk/dcmimgle/dimopxt.h" #include "dcmtk/dcmimgle/didocu.h" /*----------------* * constructors * *----------------*/ DiOverlayImage::DiOverlayImage(const DiDocument *docu, const EI_Status status) : DiMono2Image(docu, status, 0) { if (Document != NULL) { Overlays[0] = new DiOverlay(Document); if (Overlays[0] != NULL) { BitsPerSample = 1; unsigned int i; DiOverlayPlane *plane; for (i = 0; i < Overlays[0]->getCount(); ++i) { plane = Overlays[0]->getPlane(i); if (plane != NULL) { plane->show(); if (plane->getNumberOfFrames() > NumberOfFrames) NumberOfFrames = plane->getNumberOfFrames(); if (plane->getRight() > Columns) // determine image's width and height Columns = plane->getRight(); if (plane->getBottom() > Rows) Rows = plane->getBottom(); } } if ((Rows > 0) && (Columns > 0)) { InterData = new DiMonoPixelTemplate<Uint8>(OFstatic_cast(unsigned long, Rows) * OFstatic_cast(unsigned long, Columns) * NumberOfFrames); if (InterData == NULL) { ImageStatus = EIS_MemoryFailure; DCMIMGLE_ERROR("can't allocate memory for inter-representation"); } else if (InterData->getData() == NULL) ImageStatus = EIS_InvalidImage; } else { ImageStatus = EIS_InvalidValue; DCMIMGLE_ERROR("invalid value for 'Rows' (" << Rows << ") and/or 'Columns' (" << Columns << ")"); } } } else { ImageStatus = EIS_InvalidDocument; DCMIMGLE_ERROR("this DICOM document is invalid"); } } /*--------------* * destructor * *--------------*/ DiOverlayImage::~DiOverlayImage() { }
27.757895
113
0.496018
palmerc
9f999fc7522ff693a0337e4cdb616d9e00686e0a
3,114
cpp
C++
tests/vu/lower/random.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
25
2015-04-07T23:13:49.000Z
2021-09-27T08:03:53.000Z
tests/vu/lower/random.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
42
2015-04-27T03:12:48.000Z
2018-05-08T13:53:39.000Z
tests/vu/lower/random.cpp
unknownbrackets/ps2autotests
97469ffbed8631277b94e28d01dabd702aa97ef3
[ "0BSD" ]
8
2015-04-26T06:29:01.000Z
2021-05-27T09:50:03.000Z
#include <common-ee.h> #include "../test_runner.h" static const u32 __attribute__((aligned(16))) C_ZEROONE[4] = {0x3F800000, 0x3FFFFFFF, 0x00000000, 0xFFFFFFFF}; static const u32 __attribute__((aligned(16))) C_GARBAGE[4] = {0x01234567, 0x89ABCDEF, 0xFEDCBA98, 0x76543210}; static u32 *const CVF_ZEROONE = (u32 *)(vu1_mem + 0x0000); static u32 *const CVF_GARBAGE = (u32 *)(vu1_mem + 0x0010); static void setup_vf_constants() { *(vu128 *)CVF_ZEROONE = *(vu128 *)C_ZEROONE; *(vu128 *)CVF_GARBAGE = *(vu128 *)C_GARBAGE; } class RandomTestRunner : public TestRunner { public: RandomTestRunner(int vu) : TestRunner(vu) { } void PerformInit() { using namespace VU; Reset(); WrLoadFloatRegister(DEST_XYZW, VF16, CVF_GARBAGE); Wr(RINIT(FIELD_X, VF16)); Wr(RGET(DEST_XYZW, VF01)); Wr(RINIT(FIELD_Y, VF16)); Wr(RGET(DEST_XYZW, VF02)); Wr(RINIT(FIELD_Z, VF16)); Wr(RGET(DEST_XYZW, VF03)); Wr(RINIT(FIELD_W, VF16)); Wr(RGET(DEST_XYZW, VF04)); Execute(); printf("RINIT: \n"); printf(" "); PrintRegister(VF01, true); printf(" "); PrintRegister(VF02, true); printf(" "); PrintRegister(VF03, true); printf(" "); PrintRegister(VF04, true); } void PerformXor() { using namespace VU; Reset(); WrLoadFloatRegister(DEST_XYZW, VF16, CVF_GARBAGE); Wr(RINIT(FIELD_X, VF00)); Wr(RXOR(FIELD_X, VF16)); Wr(RGET(DEST_XYZW, VF01)); Wr(RXOR(FIELD_Y, VF16)); Wr(RGET(DEST_XYZW, VF02)); Wr(RXOR(FIELD_Z, VF16)); Wr(RGET(DEST_XYZW, VF03)); Wr(RXOR(FIELD_W, VF16)); Wr(RGET(DEST_XYZW, VF04)); Execute(); printf("RXOR: \n"); printf(" "); PrintRegister(VF01, true); printf(" "); PrintRegister(VF02, true); printf(" "); PrintRegister(VF03, true); printf(" "); PrintRegister(VF04, true); } void PerformNext_M(const char *fieldName, VU::Field field, const char *sname, const u32* s) { using namespace VU; printf(" %s[%s]: \n", sname, fieldName); Reset(); WrLoadFloatRegister(DEST_XYZW, VF16, s); Wr(RINIT(field, VF16)); Wr(RNEXT(DEST_XYZW, VF01)); Wr(RNEXT(DEST_XYZW, VF02)); Wr(RNEXT(DEST_XYZW, VF03)); Wr(RNEXT(DEST_XYZW, VF04)); Execute(); printf(" 1: "); PrintRegister(VF01, true); printf(" 2: "); PrintRegister(VF02, true); printf(" 3: "); PrintRegister(VF03, true); printf(" 4: "); PrintRegister(VF04, true); } #define PerformNext_M(field, s) PerformNext_M(#field, field, #s, s) void PerformNext() { printf("RNEXT:\n"); PerformNext_M(VU::FIELD_X, CVF_ZEROONE); PerformNext_M(VU::FIELD_Y, CVF_ZEROONE); PerformNext_M(VU::FIELD_Z, CVF_ZEROONE); PerformNext_M(VU::FIELD_W, CVF_ZEROONE); PerformNext_M(VU::FIELD_X, CVF_GARBAGE); PerformNext_M(VU::FIELD_Y, CVF_GARBAGE); PerformNext_M(VU::FIELD_Z, CVF_GARBAGE); PerformNext_M(VU::FIELD_W, CVF_GARBAGE); } #undef PerformNext_M }; int main(int argc, char *argv[]) { printf("-- TEST BEGIN\n"); setup_vf_constants(); RandomTestRunner runner(1); runner.PerformInit(); runner.PerformXor(); runner.PerformNext(); printf("-- TEST END\n"); return 0; }
24.714286
115
0.65639
unknownbrackets
9f9afd1436096594f828dc272f8e7c4f402d4f2f
1,226
cpp
C++
cpp_regex_email/regex_email_test.cpp
cg011235/tutorials
44d4b4ef520fa67abc1fc2eca2b711d7c26490bf
[ "MIT" ]
null
null
null
cpp_regex_email/regex_email_test.cpp
cg011235/tutorials
44d4b4ef520fa67abc1fc2eca2b711d7c26490bf
[ "MIT" ]
null
null
null
cpp_regex_email/regex_email_test.cpp
cg011235/tutorials
44d4b4ef520fa67abc1fc2eca2b711d7c26490bf
[ "MIT" ]
null
null
null
/** * Match regular expression */ #include <regex> #include <iostream> #include "gtest/gtest.h" /* * The valid email we define as follows. * 1. It ends with .com * 2. It has domain like @gmail */ bool isValidEmail(std::string str) { std::regex e("(\\w+)@(\\w+)(\\.(\\w+))+"); /** * (\\w+) - One or more group of alphanumeric characters * @ - single @ character * (\\.(\\w+))+ - one or more group of character starting with . followed by alpha numeric characters */ return std::regex_match(str, e); } bool isValidEmailImproved(std::string str) { std::regex e("(\\w+)(\\.|_)?(\\w*)@(\\w+)(\\.(\\w+))+"); /** * Also consider if email contains . or underscore */ return std::regex_match(str, e); } TEST(AnyDomain, Positive) { EXPECT_EQ(isValidEmail("cg011235@gmail.com"), true); EXPECT_EQ(isValidEmail("cg011235@hotmail.com"), true); EXPECT_EQ(isValidEmailImproved("chaitanya.g@gmail.com"), true); } TEST(AnyDomain, Negative) { EXPECT_EQ(isValidEmail("abcdefghijk"), false); EXPECT_EQ(isValidEmail("chaitanya.g@gmail.com"), false); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26.652174
105
0.620718
cg011235
9fa3e2269abdf80669538df1eb510f9781bdf12e
7,139
cpp
C++
apps/parallelArray.cpp
bjbanks/Multicore-Term-Project
f74a1ff088aca45384b8fa23eaa129ef527c9930
[ "MIT" ]
null
null
null
apps/parallelArray.cpp
bjbanks/Multicore-Term-Project
f74a1ff088aca45384b8fa23eaa129ef527c9930
[ "MIT" ]
null
null
null
apps/parallelArray.cpp
bjbanks/Multicore-Term-Project
f74a1ff088aca45384b8fa23eaa129ef527c9930
[ "MIT" ]
null
null
null
/* * Copyright 2020 Bryson Banks and David Campbell. All rights reserved. */ #include "parallelArray.h" #include "math.h" #include <iostream> namespace BENCHMARKS { WSDS::Scheduler* parSched; int work_per_subtask; void print_arr(int* arr, int size){ for (int i = 0; i < size; i ++){ std::cout << arr[i] << " "; } std::cout << std::endl; } //if parenttask is NULL default to sheduler spawning. If non-null, the user wants //task to be tracked as a subtask of a pre-existing task void Spawn(WSDS::Task* newTask, WSDS::Task* parentTask){ if (parentTask == NULL){ parSched->spawn(newTask); } else { parentTask->spawn(newTask); } } void Wait(WSDS::Task* parentTask){ if (parentTask == NULL){ parSched->wait(); } else { parentTask->wait(); } } /****************************************************************/ /* Library Init */ /****************************************************************/ void parallelArrayInit(WSDS::Scheduler* sched, int task_work_size){ parSched = sched; work_per_subtask = task_work_size; } /****************************************************************/ /* Parallel Adding */ /****************************************************************/ void parallelAdd(int* vecOut, int* vecA, int* vecB, int size, WSDS::Task* parentTask) { int num_sub_tasks = size / work_per_subtask; int partial_size = size / num_sub_tasks; int i; ParallelAddTaskPartial* tasks[num_sub_tasks]; /*Spawn a bunch of congruent work to divide up array to do vector adds*/ for (i = 0; i < num_sub_tasks; i++){ int offset = i*partial_size; tasks[i] = new ParallelAddTaskPartial(&vecOut[offset], &vecA[offset], &vecB[offset], partial_size); Spawn(tasks[i], parentTask); } /*wait until all child tasks are done*/ Wait(parentTask); /*clean up the sub tasks*/ for (i = 0; i < num_sub_tasks; i++){ delete tasks[i]; } } ParallelAddTaskPartial::ParallelAddTaskPartial(int* vecOut, int* vecA, int* vecB, int size) { this->vecA = vecA; this->vecB = vecB; this->vecOut = vecOut; this->size = size; } void ParallelAddTaskPartial::execute(){ for(int i = 0; i < this->size; i++) { vecOut[i] = vecA[i] + vecB[i]; } } /****************************************************************/ /* Parallel Mutliply */ /****************************************************************/ void parallelMultiply(int* vecOut, int* vecA, int* vecB, int size, WSDS::Task* parentTask) { int i; int num_sub_tasks = size / work_per_subtask; int partial_size = size / num_sub_tasks; ParallelMultiplyTaskPartial* tasks[num_sub_tasks]; /*Spawn a bunch of congruent work to divide up array to do vector adds*/ for (i = 0; i < num_sub_tasks; i++){ int offset = i*partial_size; tasks[i] = new ParallelMultiplyTaskPartial(&vecOut[offset], &vecA[offset], &vecB[offset], partial_size); Spawn(tasks[i], parentTask); } /*wait until all child tasks are done*/ Wait(parentTask); /*clean up the sub tasks*/ for (i = 0; i < num_sub_tasks; i++){ delete tasks[i]; } } ParallelMultiplyTaskPartial::ParallelMultiplyTaskPartial(int* vecOut, int* vecA, int* vecB, int size) { this->vecA = vecA; this->vecB = vecB; this->vecOut = vecOut; this->size = size; } void ParallelMultiplyTaskPartial::execute(){ for(int i = 0; i < this->size; i++) { vecOut[i] = vecA[i] * vecB[i]; } } /****************************************************************/ /* Parallel Copying */ /****************************************************************/ void parallelCopy(int* out, int* in, int size, WSDS::Task* parentTask){ int i; int num_sub_tasks = size / work_per_subtask; int partial_size = size / num_sub_tasks; ParallelCopyTaskPartial* tasks[num_sub_tasks]; /*Spawn a bunch of congruent work to divide up array to do vector adds*/ for (i = 0; i < num_sub_tasks; i++){ int offset = i*partial_size; tasks[i] = new ParallelCopyTaskPartial(&out[offset], &in[offset], partial_size); Spawn(tasks[i], parentTask); } /*wait until all child tasks are done*/ Wait(parentTask); /*clean up the sub tasks*/ for (i = 0; i < num_sub_tasks; i++){ delete tasks[i]; } } ParallelCopyTaskPartial::ParallelCopyTaskPartial(int* vecOut, int* vecIn, int size){ this->vecOut = vecOut; this->vecIn = vecIn; this->size = size; } void ParallelCopyTaskPartial::execute(){ for (int i = 0; i < this->size; i++){ this->vecOut[i] = this->vecIn[i]; } } /****************************************************************/ /* Parallel Reduce */ /****************************************************************/ int parallelReduce(int* in, int size, WSDS::Task* parentTask){ int arrIn[size]; int out[size]; parallelCopy(arrIn, in, size, parentTask); int num_steps = (int)log2((double)size); int num_sub_tasks = size / work_per_subtask; ParallelReduceTaskPartial* tasks[size]; for ( int step = 1; step <= num_steps; step++){ for (int task = 0; task < num_sub_tasks; task++){ tasks[task] = new ParallelReduceTaskPartial(out, arrIn, task*work_per_subtask+1, size, step); Spawn(tasks[task], parentTask); } Wait(parentTask); //need to transport array back to in. This is to workaround not having barriers in our task library parallelCopy(arrIn, out, size, parentTask); } return out[0]; } ParallelReduceTaskPartial::ParallelReduceTaskPartial(int* arrOut, int* arrIn, int start_idx, int size, int step){ this->arrOut = arrOut; this->arrIn = arrIn; this->size = size; this->step = step; this->start_idx = start_idx; } void ParallelReduceTaskPartial::execute(){ if (start_idx > ( size / (1<<step))) { return; //nothing to do } for (int i = start_idx; i <= start_idx + work_per_subtask; i++){ if (i <= ( size / (1<<step) ) ) { //i <= N/2^h arrOut[i-1] = arrIn[2*i-2] + arrIn[2*i-1]; } } } }
26.343173
117
0.485222
bjbanks
9fa6df2d2a3b6e4c4c7d038f355f885529f148bf
1,910
cc
C++
bzip2_test.cc
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
9
2019-09-17T10:33:58.000Z
2021-07-29T10:03:42.000Z
bzip2_test.cc
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
null
null
null
bzip2_test.cc
nurettin/libnuwen
5b3012d9e75552c372a4d09b218b7af04a928e68
[ "BSL-1.0" ]
1
2019-10-05T04:31:22.000Z
2019-10-05T04:31:22.000Z
// Copyright Stephan T. Lavavej, http://nuwen.net . // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://boost.org/LICENSE_1_0.txt . #include "bzip2.hh" #include "clock.hh" #include "file.hh" #include "test.hh" #include "typedef.hh" #include "vector.hh" #include "external_begin.hh" #include <iostream> #include <ostream> #include <string> #include "external_end.hh" using namespace std; using namespace nuwen; using namespace nuwen::chrono; using namespace nuwen::file; bool test_helper(const vuc_t& orig, const vuc_t& correct) { return bzip2(orig) == correct && unbzip2(correct) == orig; } bool test_empty() { return test_helper(vuc_t(), vuc_from_hex("425A683917724538509000000000")); } bool test_basic() { return test_helper(vuc_from_hex("48656C6C6F2C20776F726C6421"), vuc_from_hex("425A68393141592653598E9A770600000195806004004006" "0490802000220346210030B041E4B21F3F1772453850908E9A7706")); } bool test_extended(const string& filename) { const vuc_t orig = read_file(filename); watch w; const vuc_t& compressed = bzip2(orig); const double bzip2_time = w.seconds(); w.reset(); const vuc_t& decompressed = unbzip2(compressed); const double unbzip2_time = w.seconds(); cout << " bzip2 (s): " << bzip2_time << endl; cout << "unbzip2 (s): " << unbzip2_time << endl; cout << " bzip2 (MB/s): " << orig.size() / bzip2_time / 1048576 << endl; cout << "unbzip2 (MB/s): " << orig.size() / unbzip2_time / 1048576 << endl; return decompressed == orig; } int main(int argc, char * argv[]) { if (argc == 2) { NUWEN_TEST("bzip2-1", test_empty()) NUWEN_TEST("bzip2-2", test_basic()) NUWEN_TEST("bzip2-3", test_extended(argv[1])) } else { cout << "USAGE: bzip2_test <filename>" << endl; } }
26.164384
79
0.663874
nurettin
9fab47dadc6c0d778e18a7f7468b517fba2bd2aa
11,613
cpp
C++
src/AltMatrix2D.cpp
dss-bridge/dss
ca58e4eb2750bf6650fcb76b8bc085aaec699283
[ "Apache-2.0" ]
null
null
null
src/AltMatrix2D.cpp
dss-bridge/dss
ca58e4eb2750bf6650fcb76b8bc085aaec699283
[ "Apache-2.0" ]
null
null
null
src/AltMatrix2D.cpp
dss-bridge/dss
ca58e4eb2750bf6650fcb76b8bc085aaec699283
[ "Apache-2.0" ]
null
null
null
/* SDS, a bridge single-suit double-dummy quick-trick solver. Copyright (C) 2015 by Soren Hein. See LICENSE and README. */ #include <iomanip> #include <assert.h> #include "AltMatrix2D.h" using namespace std; AltMatrix2D::AltMatrix2D() { AltMatrix2D::Reset(); } AltMatrix2D::~AltMatrix2D() { } void AltMatrix2D::Reset() { numX = 0; numY = 0; } void AltMatrix2D::SetDimensions( const unsigned x, const unsigned y) { assert(x <= SDS_MAX_ALT); assert(y <= SDS_MAX_ALT); numX = x; numY = y; for (unsigned i = 0; i < numX; i++) activeX[i] = true; for (unsigned j = 0; j < numY; j++) activeY[j] = true; for (unsigned i = 0; i < numX; i++) for (unsigned j = 0; j < numY; j++) matrix[i][j] = SDS_HEADER_SAME; } bool AltMatrix2D::IsPurgedX( const unsigned x) const { return ! activeX[x]; } bool AltMatrix2D::IsPurgedY( const unsigned y) const { return ! activeY[y]; } void AltMatrix2D::SetValue( const unsigned x, const unsigned y, const cmpDetailType c) { assert(x < numX); assert(y < numY); matrix[x][y] = c; } void AltMatrix2D::PurgeX( const unsigned x) { assert(x < numX); assert(activeX[x]); activeX[x] = false; } void AltMatrix2D::PurgeY( const unsigned y) { assert(y < numY); assert(activeY[y]); activeY[y] = false; } void AltMatrix2D::ResetVectors( bool has[SDS_MAX_ALT][SDS_HEADER_CMP_SIZE], const bool active[], const unsigned len, bool hasSum[]) { for (unsigned i = 0; i < len; i++) { if (! active[i]) continue; for (unsigned c = 0; c < SDS_HEADER_CMP_SIZE; c++) has[i][c] = false; } for (unsigned c = 0; c < SDS_HEADER_CMP_SIZE; c++) hasSum[c] = false; } void AltMatrix2D::VerifyVector( const bool has[SDS_MAX_ALT][SDS_HEADER_CMP_SIZE], const bool active[], const unsigned len, bool hasSum[], bool verifyFlag) { for (unsigned i = 0; i < len; i++) { if (! active[i]) continue; // This could be one table look-up, one bit per value. if (has[i][SDS_HEADER_PLAY_OLD_BETTER] || has[i][SDS_HEADER_RANK_OLD_BETTER]) { if (has[i][SDS_HEADER_PLAY_NEW_BETTER] || has[i][SDS_HEADER_RANK_NEW_BETTER] || has[i][SDS_HEADER_SAME]) { if (verifyFlag) { AltMatrix2D::Print(cerr, "Verify error I"); assert(false); } } if (has[i][SDS_HEADER_PLAY_OLD_BETTER]) hasSum[SDS_HEADER_PLAY_OLD_BETTER] = true; if (has[i][SDS_HEADER_RANK_OLD_BETTER]) hasSum[SDS_HEADER_RANK_OLD_BETTER] = true; } else if (has[i][SDS_HEADER_PLAY_NEW_BETTER] || has[i][SDS_HEADER_RANK_NEW_BETTER]) { if (has[i][SDS_HEADER_SAME]) { if (verifyFlag) { AltMatrix2D::Print(cerr, "Verify error II"); assert(false); } } if (has[i][SDS_HEADER_PLAY_NEW_BETTER]) hasSum[SDS_HEADER_PLAY_NEW_BETTER] = true; if (has[i][SDS_HEADER_RANK_NEW_BETTER]) hasSum[SDS_HEADER_RANK_NEW_BETTER] = true; } else if (has[i][SDS_HEADER_SAME]) hasSum[SDS_HEADER_SAME] = true; else { if (has[i][SDS_HEADER_PLAY_DIFFERENT]) hasSum[SDS_HEADER_PLAY_DIFFERENT] = true; if (has[i][SDS_HEADER_RANK_DIFFERENT]) hasSum[SDS_HEADER_RANK_DIFFERENT] = true; } } } void AltMatrix2D::Verify( const bool verifyFlag) { AltMatrix2D::ResetVectors(hasX, activeX, numX, hasXsum); AltMatrix2D::ResetVectors(hasY, activeY, numY, hasYsum); for (unsigned i = 0; i < numX; i++) { if (! activeX[i]) continue; for (unsigned j = 0; j < numY; j++) { if (! activeY[j]) continue; hasX[i][matrix[i][j]] = true; hasY[j][matrix[i][j]] = true; } } AltMatrix2D::VerifyVector(hasX, activeX, numX, hasXsum, verifyFlag); AltMatrix2D::VerifyVector(hasY, activeY, numY, hasYsum, verifyFlag); } cmpDetailType AltMatrix2D::ComparePartial( const cmpDetailType diff, const cmpDetailType winX, const cmpDetailType winY) { if (hasYsum[winX] && hasYsum[winY]) { if (! (hasXsum[winX] && hasXsum[winY])) { cerr << "Error 1: " << static_cast<int>(diff) << " " << static_cast<int>(winX) << " " << static_cast<int>(winY) << "\n"; for (int c = 0; c < SDS_HEADER_CMP_SIZE; c++) cerr << setw(2) << c << setw(5) << hasXsum[c] << setw(5) << hasYsum[c]; AltMatrix2D::Print(cerr, "Error 1"); assert(false); } } if (hasXsum[winX] && hasXsum[winY]) { if (! (hasYsum[winX] && hasYsum[winY])) { cerr << "Error 2: " << static_cast<int>(diff) << " " << static_cast<int>(winX) << " " << static_cast<int>(winY) << "\n"; for (int c = 0; c < SDS_HEADER_CMP_SIZE; c++) cerr << setw(2) << c << setw(5) << hasXsum[c] << setw(5) << hasYsum[c]; AltMatrix2D::Print(cerr, "Error 2"); assert(false); } } if (hasXsum[diff] && hasYsum[diff]) return diff; else if (hasYsum[diff]) return (hasYsum[winX] ? diff : winY); else if (hasXsum[diff]) return (hasXsum[winY] ? diff : winX); else if (hasYsum[winY]) return (hasYsum[winX] ? diff : winY); else if (hasXsum[winX]) return (hasXsum[winY] ? diff : winX); else return SDS_HEADER_SAME; } cmpDetailType AltMatrix2D::ComparePartialDeclarer( const cmpDetailType diff, const cmpDetailType winX, const cmpDetailType winY) { if (hasXsum[diff] && hasYsum[diff]) return diff; else if (hasYsum[diff]) return (hasYsum[winY] ? diff : winX); else if (hasXsum[diff]) return (hasXsum[winX] ? diff : winY); else if (hasYsum[winY]) return (hasYsum[winX] ? diff : winY); else if (hasXsum[winX]) return (hasXsum[winY] ? diff : winX); else return SDS_HEADER_SAME; } cmpDetailType AltMatrix2D::Compare() { AltMatrix2D::Verify(); cmpDetailType c = AltMatrix2D::ComparePartial( SDS_HEADER_PLAY_DIFFERENT, SDS_HEADER_PLAY_OLD_BETTER, SDS_HEADER_PLAY_NEW_BETTER); if (c != SDS_HEADER_SAME) { cval = c; return c; } c = AltMatrix2D::ComparePartial( SDS_HEADER_RANK_DIFFERENT, SDS_HEADER_RANK_OLD_BETTER, SDS_HEADER_RANK_NEW_BETTER); cval = c; return c; } cmpDetailType AltMatrix2D::CompareDeclarer() { AltMatrix2D::Verify(false); bool Xdiff = (hasXsum[SDS_HEADER_PLAY_DIFFERENT] || hasXsum[SDS_HEADER_RANK_DIFFERENT]); bool Ydiff = (hasYsum[SDS_HEADER_PLAY_DIFFERENT] || hasYsum[SDS_HEADER_RANK_DIFFERENT]); bool Xwin = (hasXsum[SDS_HEADER_PLAY_OLD_BETTER] || hasXsum[SDS_HEADER_RANK_OLD_BETTER]); bool Ywin = (hasYsum[SDS_HEADER_PLAY_NEW_BETTER] || hasYsum[SDS_HEADER_RANK_NEW_BETTER]); // Could go deeper with the difference (play or rank). if (Xdiff && Ydiff) return SDS_HEADER_PLAY_DIFFERENT; else if (Ydiff) // return (Ywin || ! Xwin ? return (Ywin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_OLD_BETTER); else if (Xdiff) // return (Xwin || ! Ywin ? return (Xwin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_NEW_BETTER); else if (Ywin) return (Xwin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_NEW_BETTER); else if (Xwin) return (Ywin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_OLD_BETTER); else return SDS_HEADER_SAME; } cmpDetailType AltMatrix2D::CompareHard() { AltMatrix2D::Verify(false); bool Xdiff = (hasXsum[SDS_HEADER_PLAY_DIFFERENT] || hasXsum[SDS_HEADER_RANK_DIFFERENT]); bool Ydiff = (hasYsum[SDS_HEADER_PLAY_DIFFERENT] || hasYsum[SDS_HEADER_RANK_DIFFERENT]); bool Xwin = (hasXsum[SDS_HEADER_PLAY_OLD_BETTER] || hasXsum[SDS_HEADER_RANK_OLD_BETTER]); bool Ywin = (hasYsum[SDS_HEADER_PLAY_NEW_BETTER] || hasYsum[SDS_HEADER_RANK_NEW_BETTER]); // Could go deeper with the difference (play or rank). if (Xdiff && Ydiff) return SDS_HEADER_PLAY_DIFFERENT; else if (Ydiff) return (Xwin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_NEW_BETTER); else if (Xdiff) return (Ywin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_OLD_BETTER); else if (Ywin) return (Xwin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_NEW_BETTER); else if (Xwin) return (Ywin ? SDS_HEADER_PLAY_DIFFERENT : SDS_HEADER_PLAY_OLD_BETTER); else return SDS_HEADER_SAME; } bool AltMatrix2D::CandList( const posType sideToLose, bool use[], cmpDetailType& c) const { c = SDS_HEADER_SAME; if (sideToLose == QT_ACE) { if (cval == SDS_HEADER_PLAY_DIFFERENT || cval == SDS_HEADER_RANK_DIFFERENT) { bool usedFlag = false; for (unsigned a = 0; a < numX; a++) { use[a] = false; if (! activeX[a]) continue; if (hasX[a][SDS_HEADER_SAME] || hasX[a][SDS_HEADER_PLAY_NEW_BETTER] || hasX[a][SDS_HEADER_RANK_NEW_BETTER]) { // We're flipping directions after this. if (hasX[a][SDS_HEADER_PLAY_NEW_BETTER]) c = SDS_HEADER_PLAY_OLD_BETTER; else if (hasX[a][SDS_HEADER_RANK_OLD_BETTER]) c = cmpDetailMatrix[c][SDS_HEADER_RANK_OLD_BETTER]; continue; } usedFlag = true; use[a] = true; } return usedFlag; } else return false; } else if (sideToLose == QT_PARD) { if (cval == SDS_HEADER_PLAY_DIFFERENT || cval == SDS_HEADER_RANK_DIFFERENT) { bool usedFlag = false; for (unsigned a = 0; a < numY; a++) { use[a] = false; if (! activeY[a]) continue; if (hasY[a][SDS_HEADER_SAME] || hasY[a][SDS_HEADER_PLAY_OLD_BETTER] || hasY[a][SDS_HEADER_RANK_OLD_BETTER]) { if (hasY[a][SDS_HEADER_PLAY_OLD_BETTER]) c = SDS_HEADER_PLAY_OLD_BETTER; else if (hasY[a][SDS_HEADER_RANK_OLD_BETTER]) c = cmpDetailMatrix[c][SDS_HEADER_RANK_OLD_BETTER]; continue; } usedFlag = true; use[a] = true; } return usedFlag; } else return false; } else { assert(false); return false; } } void AltMatrix2D::PrintVector( ostream& out, const string text, const bool cvec[SDS_MAX_ALT][SDS_HEADER_CMP_SIZE], const unsigned len) const { if (text != "") out << setw(10) << text; for (unsigned i = 0; i < SDS_HEADER_CMP_SIZE; i++) out << setw(10) << CMP_DETAIL_NAMES[i]; out << "\n"; for (unsigned i = 0; i < len; i++) { out << setw(2) << i << setw(8) << ""; for (unsigned j = 0; j < SDS_HEADER_CMP_SIZE; j++) out << setw(10) << (cvec[i][j] ? "yes" : "-"); out << "\n"; } out << endl; } void AltMatrix2D::Print( ostream& out, const string text) const { if (text != "") out << "AltMatrix2D " << text << "\n"; out << setw(4) << left << "D1" << setw(4) << "D2"; for (unsigned j = 0; j < numY; j++) out << setw(10) << j; out << "\n active "; for (unsigned j = 0; j < numY; j++) out << setw(10) << (activeY[j] ? "yes" : "-"); out << "\n"; out << setw(9) << "+"; for (unsigned j = 0; j < numY; j++) out << "----------"; out << "\n"; for (unsigned i = 0; i < numX; i++) { out << setw(2) << i << setw(6) << i << (activeX[i] ? "yes" : "-") << "|"; for (unsigned j = 0; j < numY; j++) out << setw(10) << CMP_DETAIL_NAMES[matrix[i][j]]; out << "\n"; } out << "\n"; AltMatrix2D::PrintVector(out, "hasX", hasX, numX); AltMatrix2D::PrintVector(out, "hasY", hasY, numY); }
22.637427
75
0.603978
dss-bridge
9fabf9635a43fb498b12469e883145e7da3c8e30
2,354
cc
C++
utils/strings/append.cc
yangzhigang1999/libtextclassifier
4c965f1c12b3c7a37f6126cef737a8fe33f4677c
[ "Apache-2.0" ]
null
null
null
utils/strings/append.cc
yangzhigang1999/libtextclassifier
4c965f1c12b3c7a37f6126cef737a8fe33f4677c
[ "Apache-2.0" ]
null
null
null
utils/strings/append.cc
yangzhigang1999/libtextclassifier
4c965f1c12b3c7a37f6126cef737a8fe33f4677c
[ "Apache-2.0" ]
1
2021-03-20T03:40:21.000Z
2021-03-20T03:40:21.000Z
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma GCC diagnostic ignored "-Wformat-nonliteral" #include "utils/strings/append.h" #include <stdarg.h> #include <cstring> #include <string> #include <vector> namespace libtextclassifier3 { namespace strings { void SStringAppendV(std::string *strp, int bufsize, const char *fmt, va_list arglist) { int capacity = bufsize; if (capacity <= 0) { va_list backup; va_copy(backup, arglist); capacity = vsnprintf(nullptr, 0, fmt, backup); va_end(arglist); } size_t start = strp->size(); strp->resize(strp->size() + capacity + 1); int written = vsnprintf(&(*strp)[start], capacity + 1, fmt, arglist); va_end(arglist); strp->resize(start + std::min(capacity, written)); } void SStringAppendF(std::string *strp, int bufsize, const char *fmt, ...) { va_list arglist; va_start(arglist, fmt); SStringAppendV(strp, bufsize, fmt, arglist); } std::string StringPrintf(const char* fmt, ...) { std::string s; va_list arglist; va_start(arglist, fmt); SStringAppendV(&s, 0, fmt, arglist); return s; } std::string JoinStrings(const char *delim, const std::vector<std::string> &vec) { int delim_len = strlen(delim); // Calc size. int out_len = 0; for (size_t i = 0; i < vec.size(); i++) { out_len += vec[i].size() + delim_len; } // Write out. std::string ret; ret.reserve(out_len); for (size_t i = 0; i < vec.size(); i++) { ret.append(vec[i]); ret.append(delim, delim_len); } // Strip last delimiter. if (!ret.empty()) { // Must be at least delim_len. ret.resize(ret.size() - delim_len); } return ret; } } // namespace strings } // namespace libtextclassifier3
25.868132
75
0.644435
yangzhigang1999
9fada3d1fd5c8c0442bee91dfe52c5c5ca19dd20
2,253
cpp
C++
linked_List.cpp
goyalshubhangi/Practicals_Data_Structure
0358dc9b5ab198d84fd389d68021c2eda08eb8da
[ "MIT" ]
null
null
null
linked_List.cpp
goyalshubhangi/Practicals_Data_Structure
0358dc9b5ab198d84fd389d68021c2eda08eb8da
[ "MIT" ]
null
null
null
linked_List.cpp
goyalshubhangi/Practicals_Data_Structure
0358dc9b5ab198d84fd389d68021c2eda08eb8da
[ "MIT" ]
null
null
null
#include<iostream> #include <stdio.h> #include<stdlib.h> using namespace std; template <class t> struct node { t data; node<t> *next; void createList(t n); void deletion(); void insert_data(t data); void Display(); }; struct node<int> *start; template <class t> void node<t>::createList(t n) { struct node<int> *newNode,*temp; t data,i; start=(struct node*)malloc(sizeof(struct node)); if(start==NULL) { cout<<"\nUnable to allocate memory"; } else { cout<<"\n\tEnter the data of node 1:"; cin>>data; start->data=data; start->next=NULL; temp=start; for(i=2;i<=n;i++) { newNode=(struct node*)malloc(sizeof(struct node)); if(newNode==NULL) { cout<<"\nUnable to allocate memory"; } else { cout<<"\n\tEnter the data at node"<<i<<":"; cin>>data; newNode->data=data; newNode->next==NULL; temp->next=newNode; temp=temp->next; } } cout<<"\n\n\tSINGLY LINKED LIST CREATED"; } } template <class t> void node<t>::Display() { struct node<t> *temp; { }; if(start==NULL) { cout<<"\nLinked List is Empty"; } else{ temp=start; while(temp!=NULL) { cout<<"\nData ="<<temp->data; temp=temp->next; } } } template <class t> void node<t>::insert_data(t data) { struct node<t> *p; p=(struct node*)malloc(sizeof(struct node)); if(p==NULL) { cout<<"\nUnable to allocate memory"; } else { p->data=data; p->next=start; start=p; cout<<"\n\nData Inserted Successfully"; } } template <class t> void node<t>::deletion() { struct node<t> *temp = start; if(start!=NULL) { start=start->next; free(temp); cout<<"\n\nThe List is Modified"; }; } int main() { int n,data,ch; char choice; node<int> n1; cout<<"Enter the number of nodes:"; cin>>n; n1.createList(n); cout<<"\nData in the list:"; n1.Display(); do{ cout<<"\n1.Insert_at_beginning\n2.Delete\n3.Display\n"; cout<<"\nEnter your choice:"; cin>>ch; switch(ch) { case 1: cout<<"\nEnter data to be Inserted:"; cin>>data; n1.insert_data(data); break; case 2: n1.deletion(); break; case 3: n1.Display(); break; case 4: break; default: cout<<"Invalid Choice"; break; } cout<<"\nDo you want to continue?(y/n)"; cin>>choice; }while(choice=='y'||choice=='Y'); }
15.326531
57
0.615624
goyalshubhangi
9faf0de9277cfb18d6a506e99f67782af43040cb
1,798
cpp
C++
source/PinCallback.cpp
xzrunner/shaderlab
c70a05d478a971eb228998b0f8d2f9d6cbd0fedd
[ "MIT" ]
2
2016-11-16T16:32:18.000Z
2017-04-18T13:28:11.000Z
source/PinCallback.cpp
xzrunner/shaderlab
c70a05d478a971eb228998b0f8d2f9d6cbd0fedd
[ "MIT" ]
null
null
null
source/PinCallback.cpp
xzrunner/shaderlab
c70a05d478a971eb228998b0f8d2f9d6cbd0fedd
[ "MIT" ]
1
2016-11-16T16:32:21.000Z
2016-11-16T16:32:21.000Z
#include "shaderlab/PinCallback.h" #include "shaderlab/PinType.h" #include <painting0/Color.h> #include <blueprint/Pin.h> #include <blueprint/Node.h> #include <string> #include <assert.h> namespace { const pt0::Color PIN_COLORS[] = { #define PIN_INFO(type, color, desc) \ pt0::Color##color, #include "shaderlab/pin_cfg.h" #undef PIN_INFO }; const std::string PIN_DESCS[] = { #define PIN_INFO(type, color, desc) \ desc, #include "shaderlab/pin_cfg.h" #undef PIN_INFO }; std::string get_desc_func(const std::string& name, int type) { assert(type >= 0 && type < sizeof(PIN_COLORS) / sizeof(pt0::Color)); return name + " (" + PIN_DESCS[type] + ")"; } const pt0::Color& get_color_func(int type) { assert(type >= 0 && type < sizeof(PIN_COLORS) / sizeof(pt0::Color)); return PIN_COLORS[type]; } bool can_type_cast_func(int type_from, int type_to) { if (type_from == type_to) { return true; } if (type_from == shaderlab::PIN_DYNAMIC || type_to == shaderlab::PIN_DYNAMIC) { return true; } if (type_from >= shaderlab::PIN_BOOL && type_from <= shaderlab::PIN_BOOL4 && type_to >= shaderlab::PIN_BOOL && type_to <= shaderlab::PIN_BOOL4) { return true; } if (type_from >= shaderlab::PIN_INT && type_from <= shaderlab::PIN_INT4 && type_to >= shaderlab::PIN_INT && type_to <= shaderlab::PIN_INT4) { return true; } if (type_from >= shaderlab::PIN_FLOAT && type_from <= shaderlab::PIN_FLOAT4 && type_to >= shaderlab::PIN_FLOAT && type_to <= shaderlab::PIN_FLOAT4) { return true; } return false; } } namespace shaderlab { void InitPinCallback() { bp::Pin::SetExtendFuncs({ get_desc_func, get_color_func, can_type_cast_func }); } }
22.197531
82
0.6396
xzrunner
9fb00f1f5c6f3de8edf361fece8b8292d8c040bf
3,002
hpp
C++
math/formal_power_series/falling_factorial_polynomial_multiplication.hpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
7
2021-07-20T15:25:00.000Z
2022-03-13T11:58:25.000Z
math/formal_power_series/falling_factorial_polynomial_multiplication.hpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
10
2021-03-11T16:08:22.000Z
2022-03-13T08:40:36.000Z
math/formal_power_series/falling_factorial_polynomial_multiplication.hpp
hly1204/library
b62c47a8f20623c1f1edd892b980714e8587f40e
[ "Unlicense" ]
null
null
null
#ifndef FALLING_FACTORIAL_POLYNOMIAL_MULTIPLICATION_HEADER_HPP #define FALLING_FACTORIAL_POLYNOMIAL_MULTIPLICATION_HEADER_HPP /** * @brief falling factorial polynomial multiplication * @docs docs/math/formal_power_series/falling_factorial_polynomial_multiplication.md */ #include <algorithm> #include <cassert> #include <vector> #include "prime_binomial.hpp" namespace lib { /** * @brief 样本点转换为下降幂多项式 * * @tparam mod_t 素数模数且点数不能超过模数! * @tparam ConvolveFuncType * @param pts f(0), f(1), …, f(n-1) * @param f 卷积函数 * @return std::vector<mod_t> 下降幂多项式系数 */ template <typename mod_t, typename ConvolveFuncType> std::vector<mod_t> sample_points_to_FFP(const std::vector<mod_t> &pts, ConvolveFuncType &&f) { int n = pts.size(); assert(n <= mod_t::get_mod()); PrimeBinomial<mod_t> bi(n); std::vector<mod_t> emx(n), pts_egf(n); for (int i = 0; i < n; ++i) { pts_egf[i] = pts[i] * (emx[i] = bi.ifac_unsafe(i)); if (i & 1) emx[i] = -emx[i]; } pts_egf = f(emx, pts_egf); pts_egf.resize(n); return pts_egf; } /** * @brief 下降幂多项式转换为样本点 * * @tparam mod_t 素数模数且多项式度数小于模数! * @tparam ConvolveFuncType * @param n * @param ffp 下降幂多项式 * @param f 卷积函数 * @return std::vector<mod_t> f(0), f(1), …, f(n-1) */ template <typename mod_t, typename ConvolveFuncType> std::vector<mod_t> FFP_to_sample_points(int n, const std::vector<mod_t> &ffp, ConvolveFuncType &&f) { assert(ffp.size() <= mod_t::get_mod()); PrimeBinomial<mod_t> bi(n); std::vector<mod_t> ex(n); for (int i = 0; i < n; ++i) ex[i] = bi.ifac_unsafe(i); if (ffp.size() > n) ex = f(ex, std::vector<mod_t>(ffp.begin(), ffp.begin() + n)); else ex = f(ex, ffp); for (int i = 0; i < n; ++i) ex[i] *= bi.fac_unsafe(i); ex.resize(n); return ex; } /** * @brief 下降幂多项式乘法 */ template <typename mod_t, typename ConvolveFuncType> std::vector<mod_t> convolve_FFP(const std::vector<mod_t> &lhs, const std::vector<mod_t> &rhs, ConvolveFuncType &&f) { int d = lhs.size() + rhs.size() - 1; std::vector<mod_t> lhs_pts(FFP_to_sample_points(d, lhs, f)), rhs_pts(FFP_to_sample_points(d, rhs, f)); for (int i = 0; i < d; ++i) lhs_pts[i] *= rhs_pts[i]; return sample_points_to_FFP(lhs_pts, f); } /** * @brief 下降幂多项式平移 */ template <typename mod_t, typename ConvolveFuncType> std::vector<mod_t> shift_FFP(const std::vector<mod_t> &ffp, mod_t c, ConvolveFuncType &&f) { assert(ffp.size() <= mod_t::get_mod()); int n = ffp.size(); PrimeBinomial<mod_t> bi(n); std::vector<mod_t> A(ffp), B(n); mod_t c_i(1); for (int i = 0; i < n; ++i) A[i] *= bi.fac_unsafe(i), B[i] = c_i * bi.ifac_unsafe(i), c_i *= c - mod_t(i); std::reverse(A.begin(), A.end()); A = f(A, B); A.resize(n); std::reverse(A.begin(), A.end()); for (int i = 0; i < n; ++i) A[i] *= bi.ifac_unsafe(i); return A; } } // namespace lib #endif
29.722772
95
0.612258
hly1204
9fb4b52fe41fea12e78ec17fea6c5ff746b67abf
5,287
cpp
C++
Game/BattleLogic/TW_EffectMgr.cpp
TaoReiches/Tao
bf54cdf5284d3a6fd7b2e8aec0bc26fa96442a01
[ "Apache-2.0" ]
2
2020-09-30T15:17:32.000Z
2021-02-22T14:19:54.000Z
Game/BattleLogic/TW_EffectMgr.cpp
TaoReiches/Tao
bf54cdf5284d3a6fd7b2e8aec0bc26fa96442a01
[ "Apache-2.0" ]
null
null
null
Game/BattleLogic/TW_EffectMgr.cpp
TaoReiches/Tao
bf54cdf5284d3a6fd7b2e8aec0bc26fa96442a01
[ "Apache-2.0" ]
null
null
null
/********************************************** * Author: Tao Wang Copyright reserved * Contact: tao.reiches@gmail.com **********************************************/ #include "TW_EffectMgr.h" #include "TW_Effect.h" #include <TW_TriggerMgr.h> #include "TW_TriggerEvent.h" #include "TW_Main.h" #include "TW_MemoryObject.h" BeEffectMgr::BeEffectMgr(void) { m_uiDecPureID = 0xFFFFFFFE; m_iIncPureID = std::numeric_limits<int>::min(); m_iFontEffectID = 0; } BeEffectMgr::~BeEffectMgr(void) { Clear(); } bool BeEffectMgr::Initialize(void) { Clear(); //return TwEntityMgr::Initialize(); return true; } void BeEffectMgr::Update(int iDeltaTime) { //BeEntityMgr::Update(iDeltaTime); for (auto itr = m_kID2Effect.begin(); itr != m_kID2Effect.end();) { std::shared_ptr<BeEffect>& pEffect = itr->second; if (!pEffect) { ++itr; continue; } if (!pEffect->HasFlag(BEF_REMOVE)) { pEffect->Update(iDeltaTime); } if (pEffect->HasFlag(BEF_REMOVE) && !pEffect->IsNewEffect()) { TwPtParam kParam; kParam.SetParam(TwTrgParamID::BTP_pkEffect, pEffect.get()); gTrgMgr.FireTrigger(TwTriggerEvent::BTE_EFFECT_DEL, kParam); SafeDeleteEffect(pEffect); itr = m_kID2Effect.erase(itr); } else { ++itr; } if (pEffect) { pEffect->SetNewEffect(false); } } for (auto itr = m_kID2PureEffect.begin(); itr != m_kID2PureEffect.end();) { std::shared_ptr<BeEffect>& pEffect = itr->second; if (!pEffect) { ++itr; continue; } pEffect->Update(iDeltaTime); if (pEffect->HasFlag(BEF_REMOVE) && !pEffect->IsNewEffect()) { SafeDeleteEffect(pEffect); m_kID2PureEffect.erase(itr++); } else { ++itr; } if (pEffect) { pEffect->SetNewEffect(false); } } } void BeEffectMgr::Finialize(void) { Clear(); //TwEntityMgr::Finialize(); } void BeEffectMgr::Clear() { for (auto itr = m_kID2Effect.begin(); itr != m_kID2Effect.end(); ++itr) { auto& pkEffect = itr->second; SafeDeleteEffect(pkEffect); } for (auto itr = m_kID2PureEffect.begin(); itr != m_kID2PureEffect.end(); ++itr) { auto& pkEffect = itr->second; SafeDeleteEffect(pkEffect); } m_uiDecPureID = 0xFFFFFFFE; m_iIncPureID = SHRT_MIN; m_iFontEffectID = 0; m_kID2Effect.clear(); m_kID2PureEffect.clear(); } std::shared_ptr<BeEffect> BeEffectMgr::NewEffect(int iID) { auto pkEffect = std::shared_ptr<BeEffect>(mpEffect.alloc(iID)); pkEffect->AttachMain(pkAttachMain); pkEffect->SetCreateTime(gTime); return pkEffect; } void BeEffectMgr::SafeDeleteEffect(std::shared_ptr<BeEffect>& pkEffect) { if (pkEffect->GetModelFile() > 0) { m_aiPureDelEffect.push_back(pkEffect->GetID()); } mpEffect.free(pkEffect.get()); pkEffect.reset(); } std::shared_ptr<BeEffect> BeEffectMgr::AddEffect(BeEffectRace iTypeID) { int iID = gMain->GenerateID(BeGenIDType::GIT_EFFECT); auto pkEffect = NewEffect(iID); if (pkEffect->Initialize(iTypeID)) { m_kID2Effect[iID] = pkEffect; //gMain->AddEntityPointer(GIT_EFFECT, iID, pkEffect.get()); return pkEffect; } else { SafeDeleteEffect(pkEffect); return NULL; } } void BeEffectMgr::DelEffect(int iID) { auto itr = m_kID2Effect.find(iID); if (itr != m_kID2Effect.end()) { auto pkEffect = itr->second; if (pkEffect.get()) { PushNeedRemoveEffect(iID); pkEffect->OnRemove(); } } } std::shared_ptr<BeEffect> BeEffectMgr::GetEffectByID(int iID) { if (iID == 0) { return NULL; } auto itr = m_kID2Effect.find(iID); if (itr != m_kID2Effect.end()) { return itr->second; } return NULL; } std::unordered_map<int, std::shared_ptr<BeEffect>>& BeEffectMgr::GetID2Effect() { return m_kID2Effect; } std::shared_ptr<BeEffect> BeEffectMgr::GetClientEffectByID(int iEffectID) { auto itr = m_kID2PureEffect.find(iEffectID); if (itr != m_kID2PureEffect.end()) { return itr->second; } return NULL; } void BeEffectMgr::DelClientEffect(int iEffectID) { auto itr = m_kID2PureEffect.find(iEffectID); if (itr != m_kID2PureEffect.end()) { auto pkEffect = itr->second; if (pkEffect) { PushNeedRemoveEffect(pkEffect->GetID()); } } } void BeEffectMgr::DelUnitClientEffects(int iUnitID) { auto iter = m_kID2PureEffect.begin(); while (iter != m_kID2PureEffect.end()) { int iEffectID = iter->first; auto pkEffect = iter->second; if (pkEffect && pkEffect->GetTargetID() == iUnitID) { PushNeedRemoveEffect(pkEffect->GetID()); } iter++; } } int BeEffectMgr::GeneratePureID(void) { m_uiDecPureID--; return (int)m_uiDecPureID; } int BeEffectMgr::GenerateIncPureID() { m_iIncPureID++; return m_iIncPureID; } void BeEffectMgr::ClrAllPureEffectData() { m_aiPureDelEffect.clear(); } std::unordered_map<int, std::shared_ptr<BeEffect>>& BeEffectMgr::GetID2ClientEffect() { return m_kID2PureEffect; } void BeEffectMgr::PushNeedRemoveEffect(int iEffectID) { bool bFind = false; if (iEffectID > 0) { auto pkEffect = gEffectMgr.GetEffectByID(iEffectID); if (pkEffect) { pkEffect->SetFlag(BEF_REMOVE); } } else { auto pkClientEffect = gEffectMgr.GetClientEffectByID(iEffectID); if (pkClientEffect) { pkClientEffect->SetFlag(BEF_REMOVE); } } } int BeEffectMgr::GenFontEffectID(void) { return ++m_iFontEffectID; } std::vector<int>& BeEffectMgr::PureGetDelEffect() { return m_aiPureDelEffect; }
18.421603
85
0.682618
TaoReiches
9fb6febff1b0f94a2e4fae47a6cf76c4d1dc91ba
912
cpp
C++
src/sadthreadexecutablefunction.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
src/sadthreadexecutablefunction.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
src/sadthreadexecutablefunction.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include <sadthreadexecutablefunction.h> sad::AbstractThreadExecutableFunction::~AbstractThreadExecutableFunction() { } sad::AbstractThreadExecutableFunction * sad::util::EmptyThreadExecutableFunction::clone() const { return new sad::util::EmptyThreadExecutableFunction(); } int sad::util::EmptyThreadExecutableFunction::execute() { return 0; } int sad::util::FreeZeroArgVoidExecutableFunction::execute() { m_f(); return 0; } sad::AbstractThreadExecutableFunction * sad::util::FreeZeroArgVoidExecutableFunction::clone() const { return new sad::util::FreeZeroArgVoidExecutableFunction(*this); } int sad::util::FreeZeroArgIntExecutableFunction::execute() { return m_f(); } sad::AbstractThreadExecutableFunction * sad::util::FreeZeroArgIntExecutableFunction::clone() const { return new sad::util::FreeZeroArgIntExecutableFunction(*this); }
23.384615
100
0.737939
mamontov-cpp
9fb98b1f314f5b839ded2c331b4f1265dd27753a
1,835
hpp
C++
core/inc/ga/avcodec.hpp
A-F-Kazakov/gaminganywhere
e9a74d3c7cd01f494b6d5c19619071dfeadd343b
[ "BSD-3-Clause" ]
4
2021-04-28T19:08:34.000Z
2022-02-08T08:56:28.000Z
core/inc/ga/avcodec.hpp
GamingAnywhere/gaminganywhere
e9a74d3c7cd01f494b6d5c19619071dfeadd343b
[ "BSD-3-Clause" ]
null
null
null
core/inc/ga/avcodec.hpp
GamingAnywhere/gaminganywhere
e9a74d3c7cd01f494b6d5c19619071dfeadd343b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2013 Chun-Ying Huang * * This file is part of GamingAnywhere (GA). * * GA is free software; you can redistribute it and/or modify it * under the terms of the 3-clause BSD License as published by the * Free Software Foundation: http://directory.fsf.org/wiki/License:BSD_3Clause * * GA 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. * * You should have received a copy of the 3-clause BSD License along with GA; * if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef GA_AVCODEC_HPP #define GA_AVCODEC_HPP #include <ga/common.hpp> extern "C" { #include <libswscale/swscale.h> #include <libswresample/swresample.h> #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libavutil/base64.h> } #ifndef SWR_CH_MAX #define SWR_CH_MAX 32 #endif #include <map> #include <string> #include <vector> EXPORT AVFormatContext* ga_format_init(const char *filename); EXPORT AVFormatContext* ga_rtp_init(const char *url); EXPORT AVStream* ga_avformat_new_stream(AVFormatContext *ctx, int id, AVCodec *codec); EXPORT AVCodec* ga_avcodec_find_encoder(const char **names, enum AVCodecID cid = AV_CODEC_ID_NONE); EXPORT AVCodec* ga_avcodec_find_decoder(const char **names, enum AVCodecID cid = AV_CODEC_ID_NONE); EXPORT AVCodecContext* ga_avcodec_vencoder_init(AVCodecContext *ctx, AVCodec *codec, int width, int height, int fps, std::vector<std::string> *vso = NULL); EXPORT AVCodecContext* ga_avcodec_aencoder_init(AVCodecContext *ctx, AVCodec *codec, int bitrate, int samplerate, int channels, AVSampleFormat format, uint64_t chlayout); EXPORT void ga_avcodec_close(AVCodecContext *ctx); #endif
36.7
170
0.773842
A-F-Kazakov
9fc6eb8a49ab9dcabb4ade19ed9e92bc6423a311
1,068
cpp
C++
01 January Leetcode Challenge 2021/30 minDeviationArray.cpp
FazeelUsmani/Leetcode
aff4c119178f132c28a39506ffaa75606e0a861b
[ "MIT" ]
7
2020-12-01T14:27:57.000Z
2022-02-12T09:17:22.000Z
01 January Leetcode Challenge 2021/30 minDeviationArray.cpp
FazeelUsmani/Leetcode
aff4c119178f132c28a39506ffaa75606e0a861b
[ "MIT" ]
4
2020-11-12T17:49:22.000Z
2021-09-06T07:46:37.000Z
01 January Leetcode Challenge 2021/30 minDeviationArray.cpp
FazeelUsmani/Leetcode
aff4c119178f132c28a39506ffaa75606e0a861b
[ "MIT" ]
6
2021-05-21T03:49:22.000Z
2022-01-20T20:36:53.000Z
class Solution { public: int minimumDeviation(vector<int>& nums) { // Step 1 :- increase all elements to as maximum as it can and track the minn number and also the result int N = nums.size(); int maxx = INT_MIN, minn = INT_MAX; for(int i = 0; i < N; i++){ if((nums[i])%2 != 0){ nums[i] *= 2; } maxx = max(maxx, nums[i]); minn = min(minn, nums[i]); } int min_deviation = maxx - minn; // Step 2 :- Insert into max_heap and try to decrease the maxx as much as u can priority_queue<int>pq; for(int i = 0; i < N; i++){ pq.push(nums[i]); } while((pq.top())%2 == 0){ int top = pq.top(); pq.pop(); min_deviation = min(min_deviation, top - minn); top /= 2; minn = min(minn, top); pq.push(top); } min_deviation = min(min_deviation, pq.top() - minn); // Step 3 :- return maxx - minn; return min_deviation ; } };
29.666667
109
0.48221
FazeelUsmani
9fc7af414978dfe7d51b79ad3bb9573006175498
1,401
cpp
C++
Triger/src/Triger/Renderer/OrthographicCamera.cpp
AzadKshitij/Triger
969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb
[ "MIT" ]
2
2020-10-25T15:51:46.000Z
2020-11-10T15:06:22.000Z
Triger/src/Triger/Renderer/OrthographicCamera.cpp
AzadKshitij/Triger
969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb
[ "MIT" ]
3
2020-11-11T16:54:49.000Z
2020-11-29T14:35:31.000Z
Triger/src/Triger/Renderer/OrthographicCamera.cpp
AzadKshitij/Triger
969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb
[ "MIT" ]
null
null
null
/*------------ Copyright © 2020 Azad Kshitij. All rights reserved. ------------ // // Project : Triger // License : https://opensource.org/licenses/MIT // File : OrthographicCamera.cpp // Created On : 10/11/2020 // Updated On : 10/11/2020 // Created By : Azad Kshitij @AzadKshitij //--------------------------------------------------------------------------*/ #include "trpch.h" #include "Triger/Renderer/OrthographicCamera.h" #include <glm/gtc/matrix_transform.hpp> namespace Triger { OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top) : m_ProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), m_ViewMatrix(1.0f) { TR_PROFILE_FUNCTION(); m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix; } void OrthographicCamera::SetProjection(float left, float right, float bottom, float top) { TR_PROFILE_FUNCTION(); m_ProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f); m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix; } void OrthographicCamera::RecalculateViewMatrix() { TR_PROFILE_FUNCTION(); glm::mat4 transform = glm::translate(glm::mat4(1.0f), m_Position) * glm::rotate(glm::mat4(1.0f), glm::radians(m_Rotation), glm::vec3(0, 0, 1)); m_ViewMatrix = glm::inverse(transform); m_ViewProjectionMatrix = m_ProjectionMatrix * m_ViewMatrix; } }
31.840909
93
0.660956
AzadKshitij
9fcb4b4e42156e48d39e832fccd5cad1d864464b
707
hpp
C++
kernel/Cpu/Tss.hpp
Mrokkk/kernel
e3d6ab19800d1e6c81be20cc5d27696c90ba3146
[ "MIT" ]
null
null
null
kernel/Cpu/Tss.hpp
Mrokkk/kernel
e3d6ab19800d1e6c81be20cc5d27696c90ba3146
[ "MIT" ]
null
null
null
kernel/Cpu/Tss.hpp
Mrokkk/kernel
e3d6ab19800d1e6c81be20cc5d27696c90ba3146
[ "MIT" ]
null
null
null
#pragma once #include "Segment.hpp" namespace cpu { struct Tss final { Tss(); void load() const; uint32_t prevTss; uint32_t esp0; uint32_t ss0; uint32_t esp1; uint32_t ss1; uint32_t esp2; uint32_t ss2; uint32_t cr3; uint32_t eip; uint32_t eflags; uint32_t eax; uint32_t ecx; uint32_t edx; uint32_t ebx; uint32_t esp; uint32_t ebp; uint32_t esi; uint32_t edi; uint32_t es; uint32_t cs; uint32_t ss; uint32_t ds; uint32_t fs; uint32_t gs; uint32_t ldt; uint16_t trap; uint16_t iomapOffset; uint8_t ioBitmap[128]; } PACKED; void contextSwitch(Tss& prev, Tss& next); } // namespace cpu
15.711111
41
0.630835
Mrokkk
9fcd40033bfb0d7488806a9c7944872bfca30a5c
10,482
hpp
C++
include/Bit/System/Matrix4x4.hpp
jimmiebergmann/Bit-Engine
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
[ "Zlib" ]
null
null
null
include/Bit/System/Matrix4x4.hpp
jimmiebergmann/Bit-Engine
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
[ "Zlib" ]
null
null
null
include/Bit/System/Matrix4x4.hpp
jimmiebergmann/Bit-Engine
39324a9e7fb5ab4b1cf3738f871470e0a9ef7575
[ "Zlib" ]
null
null
null
// /////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com // // This software is provided 'as-is', without any express or // implied warranty. In no event will the authors be held // liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute // it freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but // is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any // source distribution. // /////////////////////////////////////////////////////////////////////////// #ifndef BIT_SYSTEM_MATRXI4X4_HPP #define BIT_SYSTEM_MATRXI4X4_HPP #include <Bit/Build.hpp> #include <Bit/System/Math.hpp> #include <Bit/System/Vector3.hpp> #include <Bit/System/Vector4.hpp> #include <Bit/System/Angle.hpp> #include <float.h> #if defined( BIT_PLATFORM_WIN32 ) #define bitIsNan _isnan #elif defined( BIT_PLATFORM_LINUX ) #define bitIsNan isnan #endif namespace Bit { //////////////////////////////////////////////////////////////// /// \ingroup System /// \brief Matrix class /// //////////////////////////////////////////////////////////////// template <typename T> class Matrix4x4 { public: //////////////////////////////////////////////////////////////// /// \brief Default constructor. /// //////////////////////////////////////////////////////////////// Matrix4x4( ); //////////////////////////////////////////////////////////////// /// \brief Constructor. /// /// Fill all the matrix's components with one single value. /// /// \param p_Val Input value /// //////////////////////////////////////////////////////////////// Matrix4x4( const T p_Val ); //////////////////////////////////////////////////////////////// /// \brief Constructor. /// //////////////////////////////////////////////////////////////// Matrix4x4( const T X_x, const T Y_x, const T Z_x, const T P_x, const T X_y, const T Y_y, const T Z_y, const T P_y, const T X_z, const T Y_z, const T Z_z, const T P_z, const T X_a, const T Y_a, const T Z_a, const T P_a ); //////////////////////////////////////////////////////////////// /// \brief Turning the matrix into an identity matrix. /// //////////////////////////////////////////////////////////////// void Identity( ); //////////////////////////////////////////////////////////////// /// \brief Turning the matrix into a fixed camera matrix. /// /// \param p_Eye The position of the camera(The eye). /// \param p_Center The center position of where the camera is pointing. /// \param p_Up The up vector of the camera(Used for orientation). /// //////////////////////////////////////////////////////////////// void LookAt( Vector3<T> p_Eye, Vector3<T> p_Center, Vector3<T> p_Up ); //////////////////////////////////////////////////////////////// /// \brief Turning the matrix into an orthographic matrix. /// /// \param p_Left The left value. /// \param p_Right The right value. /// \param p_Bottom The bottom value. /// \param p_Top The top value. /// \param p_ZNear The nearest depth value. /// \param p_ZFar The farthest depth value. /// //////////////////////////////////////////////////////////////// void Orthographic( const T p_Left, const T p_Right, const T p_Bottom, const T p_Top, const T p_ZNear, const T p_ZFar ); //////////////////////////////////////////////////////////////// /// \brief Turning the matrix into a perspective matrix. /// /// \param p_Fov Field of view value. /// \param p_Aspect Aspect ratio value. /// \param p_ZNear The nearest depth value. /// \param p_ZFar The farthest depth value. /// //////////////////////////////////////////////////////////////// void Perspective( const T p_Fov, const T p_Aspect, const T p_ZNear, const T p_ZFar ); //////////////////////////////////////////////////////////////// /// \brief Turning the matrix into a position matrix. /// //////////////////////////////////////////////////////////////// void Position( const Vector3<T> & p_Postion ); //////////////////////////////////////////////////////////////// /// \brief Rotate the matrix using euler angles /// /// \param p_Angles The angles to rotate the matrix. /// //////////////////////////////////////////////////////////////// void RotateEuler(const Vector3<Angle> & p_Angles); //////////////////////////////////////////////////////////////// /// \brief Rotate the matrix using a quaterinion /// /// \param p_Angles The angles to rotate the matrix. /// //////////////////////////////////////////////////////////////// void RotateQuaternion(const Vector4f32 & p_Quaterinion); //////////////////////////////////////////////////////////////// /// \brief Rotate the matrix about the x-axis. /// /// \param p_Angle The angle in degrees to rotate the matrix. /// //////////////////////////////////////////////////////////////// void RotateX(const T p_Angle); //////////////////////////////////////////////////////////////// /// \brief Rotate the matrix about the y-axis. /// /// \param p_Angle The angle in degrees to rotate the matrix. /// //////////////////////////////////////////////////////////////// void RotateY( const T p_Angle ); //////////////////////////////////////////////////////////////// /// \brief Rotate the matrix about the z-axis. /// /// \param p_Angle The angle in degrees to rotate the matrix. /// //////////////////////////////////////////////////////////////// void RotateZ( const T p_Angle ); //////////////////////////////////////////////////////////////// /// \brief Scale the matrix. /// /// \param p_X Amount of scale by the x-axis. /// \param p_Y Amount of scale by the y-axis. /// \param p_Z Amount of scale by the z-axis. /// //////////////////////////////////////////////////////////////// void Scale( const T p_X, const T p_Y, const T p_Z ); //////////////////////////////////////////////////////////////// /// \brief Translate the matrix. /// /// \param p_X Amount of translation by the x-axis. /// \param p_Y Amount of translation by the y-axis. /// \param p_Z Amount of translation by the z-axis. /// //////////////////////////////////////////////////////////////// void Translate(const T p_X, const T p_Y, const T p_Z); //////////////////////////////////////////////////////////////// /// \brief Inverse the matrix. /// /// \return the determinant of the matrix. 0 if failed. /// //////////////////////////////////////////////////////////////// Float32 Inverse(); //////////////////////////////////////////////////////////////// /// \brief Get determinant of the matrix. /// //////////////////////////////////////////////////////////////// Float32 GetDeterminant() const; //////////////////////////////////////////////////////////////// /// \brief Unproject screen postion. /// //////////////////////////////////////////////////////////////// static Bool UnProject( const Vector3f32 p_WindowPosition, const Matrix4x4<T> & p_Matrix, const Int32 p_Viewport[4], Vector3f32 & p_Position); //////////////////////////////////////////////////////////////// /// \brief Project world prosition. /// //////////////////////////////////////////////////////////////// static Vector3f32 Project( const Vector3f32 p_WorldPosition, const Matrix4x4<T> & p_Matrix); //////////////////////////////////////////////////////////////// // Operators. //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// /// \brief Copy operator. /// //////////////////////////////////////////////////////////////// Matrix4x4<T> & operator = ( const Matrix4x4<T> & p_Mat ); //////////////////////////////////////////////////////////////// /// \brief Addition operator. /// //////////////////////////////////////////////////////////////// Matrix4x4<T> operator + ( const Matrix4x4<T> & p_Mat ) const; //////////////////////////////////////////////////////////////// /// \brief Subtraction operator. /// //////////////////////////////////////////////////////////////// Matrix4x4<T> operator - ( const Matrix4x4<T> & p_Mat ) const; //////////////////////////////////////////////////////////////// /// \brief Multiplication operator. /// //////////////////////////////////////////////////////////////// Matrix4x4<T> operator * ( const Matrix4x4<T> & p_Mat ) const; //////////////////////////////////////////////////////////////// /// \brief Multiplication operator. /// //////////////////////////////////////////////////////////////// Vector4<T> operator * ( const Vector4<T> & p_Vector ) const; //////////////////////////////////////////////////////////////// /// \brief Equal to operator. /// //////////////////////////////////////////////////////////////// Bool operator == ( const Matrix4x4<T> & p_Mat ) const; //////////////////////////////////////////////////////////////// /// \brief Not equal to operator. /// //////////////////////////////////////////////////////////////// Bool operator != ( const Matrix4x4<T> & p_Mat ) const; //////////////////////////////////////////////////////////////// // Public variables. //////////////////////////////////////////////////////////////// T m[ 16 ]; ///< The matrix components }; //////////////////////////////////////////////////////////////// // Include the inline file. //////////////////////////////////////////////////////////////// #include <Bit/System/Matrix4x4.inl> //////////////////////////////////////////////////////////////// // Predefined matrix4x4 types. //////////////////////////////////////////////////////////////// typedef Matrix4x4< Float32 > Matrix4x4f32; typedef Matrix4x4< Float64 > Matrix4x4f64; } #endif
36.778947
78
0.394867
jimmiebergmann
9fd43818263e52f10508fab17863902379c39a96
4,188
cc
C++
client/squad_eval_dataset.cc
pcastonguay/speechsquad
87779a852188e257610a3beae1e825b83841648f
[ "Apache-2.0" ]
56
2020-10-05T17:38:14.000Z
2022-02-23T07:17:27.000Z
client/squad_eval_dataset.cc
pcastonguay/speechsquad
87779a852188e257610a3beae1e825b83841648f
[ "Apache-2.0" ]
2
2021-12-05T22:16:15.000Z
2021-12-07T00:32:45.000Z
client/squad_eval_dataset.cc
pcastonguay/speechsquad
87779a852188e257610a3beae1e825b83841648f
[ "Apache-2.0" ]
9
2020-10-05T20:04:41.000Z
2021-11-17T04:40:45.000Z
/* * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "squad_eval_dataset.h" #include <fstream> #include <iostream> #include "status.h" namespace speech_squad { Status SquadEvalDataset::LoadFromJson(const std::string &json_filepath) { std::ifstream json_stream; json_stream.open(json_filepath, std::ifstream::in); if (!json_stream.is_open()) { return Status(Status::Code::NOT_FOUND, "Could not open file " + json_filepath); } std::string line; std::getline(json_stream, line, '\n'); rapidjson::Document doc; doc.Parse(line.c_str()); contexts_.reserve(15000); // int question_count = 0; // std::ofstream myfile; // myfile.open("squad_questions.json"); const auto &data_array = doc["data"]; assert(data_array.IsArray()); // attributes is an array // Loop over the themes for (auto itr = data_array.Begin(); itr != data_array.End(); ++itr) { auto &data = *itr; assert(data.IsObject()); // each attribute is an object const auto &paragraph_array = data["paragraphs"]; assert(paragraph_array.IsArray()); // attributes is an array for (auto itr2 = paragraph_array.Begin(); itr2 != paragraph_array.End(); ++itr2) { auto &paragraph = *itr2; assert(paragraph.IsObject()); // each attribute is an object std::string context = paragraph["context"].GetString(); const auto &qas_array = paragraph["qas"]; // std::cout << "context=" << context << std::endl; contexts_.push_back(std::make_shared<std::string>(context)); for (auto itr3 = qas_array.Begin(); itr3 != qas_array.End(); ++itr3) { auto &qa = *itr3; assert(qa.IsObject()); // each attribute is an object std::string question = qa["question"].GetString(); std::string question_id = qa["id"].GetString(); questions_[question_id] = question; question_contexts_[question_id] = contexts_.back(); const auto &answers_array = qa["answers"]; assert(answers_array.IsArray()); // attributes is an array for (auto itr4 = answers_array.Begin(); itr4 != answers_array.End(); ++itr4) { auto &answer = *itr4; assert(answer.IsObject()); // each attribute is an object } // myfile << "{\"audio_filepath\": // \"/work/test_files/speech_squad/speech_squad" << // std::to_string(question_count) << ".wav\",\"id\":\"" << question_id // << "\" }" << std::endl; // question_count++; // std::cout << "question=" << question << std::endl; // std::cout << "id=" << question_id << std::endl;a } } } // myfile.close(); if (!doc.IsObject()) { std::cout << "Problem parsing line: " << line << std::endl; return Status(Status::Code::INTERNAL, "Cannot parse Squad json file"); } json_stream.close(); return Status::Success; } Status SquadEvalDataset::GetQuestion(const std::string &id, std::string *question) { if (questions_.find(id) == questions_.end()) { return Status(Status::Code::UNKNOWN, "Question id " + id + " not found"); } else { *question = questions_[id]; return Status::Success; } } Status SquadEvalDataset::GetQuestionContext(const std::string &id, std::string *context) { if (question_contexts_.find(id) == question_contexts_.end()) { return Status(Status::Code::UNKNOWN, "Question id " + id + " not found"); } else { *context = *(question_contexts_[id]); return Status::Success; } } } // namespace speech_squad
33.504
78
0.627507
pcastonguay
9fd8493c8af469551e3af9570633023dffd27284
1,981
cpp
C++
libs/sge_engine/src/sge_engine/materials/Material.cpp
Alekssasho/sge_source
2db4ae08f7b3434d32dd9767fe1136234cb70b83
[ "MIT" ]
null
null
null
libs/sge_engine/src/sge_engine/materials/Material.cpp
Alekssasho/sge_source
2db4ae08f7b3434d32dd9767fe1136234cb70b83
[ "MIT" ]
null
null
null
libs/sge_engine/src/sge_engine/materials/Material.cpp
Alekssasho/sge_source
2db4ae08f7b3434d32dd9767fe1136234cb70b83
[ "MIT" ]
null
null
null
#include "Material.h" #include "sge_core/Geometry.h" namespace sge { // clang-format off DefineTypeId(OMaterial, 20'10'14'0001); DefineTypeId(MDiffuseMaterial, 20'10'14'0002); ReflBlock() { ReflAddObject(OMaterial); ReflAddObject(MDiffuseMaterial).inherits<MDiffuseMaterial, OMaterial>() ReflMember(MDiffuseMaterial, diffuseColor).addMemberFlag(MFF_Vec3fAsColor) ReflMember(MDiffuseMaterial, textureShift).uiRange(0.f, 0.f, 0.01f) ReflMember(MDiffuseMaterial, textureTiling) ReflMember(MDiffuseMaterial, textureRotation).addMemberFlag(MFF_FloatAsDegrees) ReflMember(MDiffuseMaterial, metalness).uiRange(0.f, 1.f, 0.01f) ReflMember(MDiffuseMaterial, roughness).uiRange(0.f, 1.f, 0.01f) ReflMember(MDiffuseMaterial, diffuseTexture) ReflMember(MDiffuseMaterial, normalTexture) ReflMember(MDiffuseMaterial, metalnessTexture) ReflMember(MDiffuseMaterial, roughnessTexture) ; } // clang-format on Material MDiffuseMaterial::getMaterial() { Material result; result.uvwTransform = mat4f::getTRS(vec3f(textureShift, 0.f), quatf::getAxisAngle(vec3f(0.f, 0.f, 1.f), textureRotation), vec3f(textureTiling, 1.f)); diffuseTexture.update(); normalTexture.update(); metalnessTexture.update(); roughnessTexture.update(); if (GpuHandle<Texture>* pTex = diffuseTexture.getAssetTexture(); pTex && pTex->IsResourceValid()) { result.diffuseTexture = pTex->GetPtr(); } if (GpuHandle<Texture>* pTex = normalTexture.getAssetTexture(); pTex && pTex->IsResourceValid()) { result.texNormalMap = pTex->GetPtr(); } if (GpuHandle<Texture>* pTex = metalnessTexture.getAssetTexture(); pTex && pTex->IsResourceValid()) { result.texMetalness = pTex->GetPtr(); } if (GpuHandle<Texture>* pTex = roughnessTexture.getAssetTexture(); pTex && pTex->IsResourceValid()) { result.texRoughness = pTex->GetPtr(); } result.diffuseColor = vec4f(diffuseColor, 1.f); result.metalness = metalness; result.roughness = roughness; return result; } } // namespace sge
31.444444
132
0.757193
Alekssasho
9fe29b1dbb3d25300f9633732abc262f8b18ba38
49,449
cpp
C++
src/rcv/binex.cpp
akstuki/rtklibcpp
241753fba4d92fb09f3337e6c82b1ed9283675be
[ "BSD-2-Clause" ]
1
2020-06-05T15:16:36.000Z
2020-06-05T15:16:36.000Z
src/rcv/binex.cpp
akstuki/rtklibcpp
241753fba4d92fb09f3337e6c82b1ed9283675be
[ "BSD-2-Clause" ]
1
2020-06-14T07:04:29.000Z
2020-06-14T07:04:29.000Z
src/rcv/binex.cpp
akstuki/rtklibcpp
241753fba4d92fb09f3337e6c82b1ed9283675be
[ "BSD-2-Clause" ]
2
2021-09-26T09:00:02.000Z
2021-09-26T10:07:52.000Z
/*------------------------------------------------------------------------------ * binex.c : binex dependent functions * * Copyright (C) 2013-2019 by T.TAKASU, All rights reserved. * * reference : * [1] UNAVCO, BINEX: Binary exchange format * (http://binex.unavco.org/binex.html) * * version : $Revision:$ $Date:$ * history : 2013/02/20 1.0 new * 2013/04/15 1.1 support 0x01-05 beidou-2/compass ephemeris * 2013/05/18 1.2 fix bug on decoding obsflags in message 0x7f-05 * 2014/04/27 1.3 fix bug on decoding iode for message 0x01-02 * 2015/12/05 1.4 fix bug on decoding tgd for message 0x01-05 * 2016/07/29 1.5 crc16() -> rtk_crc16() * 2017/04/11 1.6 (char *) -> (signed char *) * fix bug on unchange-test of beidou ephemeris * 2018/10/10 1.7 fix problem of sisa handling in galileo ephemeris * add receiver option -GALINAV, -GALFNAV * 2018/12/06 1.8 fix bug on decoding galileo ephemeirs iode (0x01-04) * 2019/05/10 1.9 save galileo E5b data to obs index 2 * 2019/07/25 1.10 support upgraded galileo ephemeris (0x01-14) *-----------------------------------------------------------------------------*/ #include "rtklib.h" #define BNXSYNC1 0xC2 /* binex sync (little-endian,regular-crc) */ #define BNXSYNC2 0xE2 /* binex sync (big-endian ,regular-crc) */ #define BNXSYNC3 0xC8 /* binex sync (little-endian,enhanced-crc) */ #define BNXSYNC4 0xE8 /* binex sync (big-endian ,enhanced-crc) */ #define BNXSYNC1R 0xD2 /* binex sync (little-endian,regular-crc,rev) */ #define BNXSYNC2R 0xF2 /* binex sync (big-endian ,regular-crc,rev) */ #define BNXSYNC3R 0xD8 /* binex sync (little-endian,enhanced-crc,rev) */ #define BNXSYNC4R 0xF8 /* binex sync (big-endian ,enhanced-crc,rev) */ #define MIN(x,y) ((x)<(y)?(x):(y)) /* ura table -----------------------------------------------------------------*/ static const double ura_eph[]={ 2.4,3.4,4.85,6.85,9.65,13.65,24.0,48.0,96.0,192.0,384.0,768.0,1536.0, 3072.0,6144.0,0.0 }; /* get fields (big-endian) ---------------------------------------------------*/ #define U1(p) (*((unsigned char *)(p))) #define I1(p) (*((signed char *)(p))) static unsigned short U2(unsigned char *p) { unsigned short value; unsigned char *q=(unsigned char *)&value+1; int i; for (i=0;i<2;i++) *q--=*p++; return value; } static unsigned int U4(unsigned char *p) { unsigned int value; unsigned char *q=(unsigned char *)&value+3; int i; for (i=0;i<4;i++) *q--=*p++; return value; } static int I4(unsigned char *p) { return (int)U4(p); } static float R4(unsigned char *p) { float value; unsigned char *q=(unsigned char *)&value+3; int i; for (i=0;i<4;i++) *q--=*p++; return value; } static double R8(unsigned char *p) { double value; unsigned char *q=(unsigned char *)&value+7; int i; for (i=0;i<8;i++) *q--=*p++; return value; } /* get binex 1-4 byte unsigned integer (big endian) --------------------------*/ static int getbnxi(unsigned char *p, unsigned int *val) { int i; for (*val=0,i=0;i<3;i++) { *val=(*val<<7)+(p[i]&0x7F); if (!(p[i]&0x80)) return i+1; } *val=(*val<<8)+p[i]; return 4; } /* checksum 8 parity ---------------------------------------------------------*/ static unsigned char csum8(const unsigned char *buff, int len) { unsigned char cs=0; int i; for (i=0;i<len;i++) { cs^=buff[i]; } return cs; } /* adjust weekly rollover of gps time ----------------------------------------*/ static gtime_t adjweek(gtime_t time, double tow) { double tow_p; int week; tow_p=time2gpst(time,&week); if (tow<tow_p-302400.0) tow+=604800.0; else if (tow>tow_p+302400.0) tow-=604800.0; return gpst2time(week,tow); } /* adjust daily rollover of time ---------------------------------------------*/ static gtime_t adjday(gtime_t time, double tod) { double ep[6],tod_p; time2epoch(time,ep); tod_p=ep[3]*3600.0+ep[4]*60.0+ep[5]; if (tod<tod_p-43200.0) tod+=86400.0; else if (tod>tod_p+43200.0) tod-=86400.0; ep[3]=ep[4]=ep[5]=0.0; return timeadd(epoch2time(ep),tod); } /* ura value (m) to ura index ------------------------------------------------*/ static int uraindex(double value) { int i; for (i=0;i<15;i++) if (ura_eph[i]>=value) break; return i; } /* galileo sisa value (m) to sisa index --------------------------------------*/ static int sisaindex(double value) { if (value< 0.5) return (int)((value )/0.01); if (value< 1.0) return (int)((value-0.5)/0.02)+ 50; if (value< 2.0) return (int)((value-1.0)/0.04)+ 75; if (value<=6.0) return (int)((value-2.0)/0.16)+100; return 255; /* NAPA */ } /* decode binex mesaage 0x00-00: comment -------------------------------------*/ static int decode_bnx_00_00(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-00: not supported message\n"); return 0; } /* decode binex mesaage 0x00-01: program or software package -----------------*/ static int decode_bnx_00_01(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-01: not supported message\n"); return 0; } /* decode binex mesaage 0x00-02: program operator ----------------------------*/ static int decode_bnx_00_02(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-02: not supported message\n"); return 0; } /* decode binex mesaage 0x00-03: reserved ------------------------------------*/ static int decode_bnx_00_03(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-03: not supported message\n"); return 0; } /* decode binex mesaage 0x00-04: site name/description -----------------------*/ static int decode_bnx_00_04(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-04: not supported message\n"); return 0; } /* decode binex mesaage 0x00-05: site number ---------------------------------*/ static int decode_bnx_00_05(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-05: not supported message\n"); return 0; } /* decode binex mesaage 0x00-06: monumnent name ------------------------------*/ static int decode_bnx_00_06(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-06: not supported message\n"); return 0; } /* decode binex mesaage 0x00-07: monumnent number ----------------------------*/ static int decode_bnx_00_07(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-07: not supported message\n"); return 0; } /* decode binex mesaage 0x00-08: marker name ---------------------------------*/ static int decode_bnx_00_08(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-08: not supported message\n"); return 0; } /* decode binex mesaage 0x00-09: marker number -------------------------------*/ static int decode_bnx_00_09(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-09: not supported message\n"); return 0; } /* decode binex mesaage 0x00-0a: reference point name ------------------------*/ static int decode_bnx_00_0a(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-0a: not supported message\n"); return 0; } /* decode binex mesaage 0x00-0b: reference point number ----------------------*/ static int decode_bnx_00_0b(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-0b: not supported message\n"); return 0; } /* decode binex mesaage 0x00-0c: date esttablished ---------------------------*/ static int decode_bnx_00_0c(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-0c: not supported message\n"); return 0; } /* decode binex mesaage 0x00-0d: reserved ------------------------------------*/ static int decode_bnx_00_0d(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-0d: not supported message\n"); return 0; } /* decode binex mesaage 0x00-0e: reserved ------------------------------------*/ static int decode_bnx_00_0e(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-0e: not supported message\n"); return 0; } /* decode binex mesaage 0x00-0f: 4-character id ------------------------------*/ static int decode_bnx_00_0f(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-0f: not supported message\n"); return 0; } /* decode binex mesaage 0x00-10: project name --------------------------------*/ static int decode_bnx_00_10(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-10: not supported message\n"); return 0; } /* decode binex mesaage 0x00-11: principal investigator for this project -----*/ static int decode_bnx_00_11(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-11: not supported message\n"); return 0; } /* decode binex mesaage 0x00-12: pi's agency/institution ---------------------*/ static int decode_bnx_00_12(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-12: not supported message\n"); return 0; } /* decode binex mesaage 0x00-13: pi's contact information --------------------*/ static int decode_bnx_00_13(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-13: not supported message\n"); return 0; } /* decode binex mesaage 0x00-14: site operator -------------------------------*/ static int decode_bnx_00_14(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-14: not supported message\n"); return 0; } /* decode binex mesaage 0x00-15: site operator's agency/institution ----------*/ static int decode_bnx_00_15(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-15: not supported message\n"); return 0; } /* decode binex mesaage 0x00-16: site operator's contact information ---------*/ static int decode_bnx_00_16(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-16: not supported message\n"); return 0; } /* decode binex mesaage 0x00-17: antenna type --------------------------------*/ static int decode_bnx_00_17(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-17: not supported message\n"); return 0; } /* decode binex mesaage 0x00-18: antenna number ------------------------------*/ static int decode_bnx_00_18(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-18: not supported message\n"); return 0; } /* decode binex mesaage 0x00-19: receiver type -------------------------------*/ static int decode_bnx_00_19(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-19: not supported message\n"); return 0; } /* decode binex mesaage 0x00-1a: receiver number -----------------------------*/ static int decode_bnx_00_1a(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-1a: not supported message\n"); return 0; } /* decode binex mesaage 0x00-1b: receiver firmware version -------------------*/ static int decode_bnx_00_1b(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-1b: not supported message\n"); return 0; } /* decode binex mesaage 0x00-1c: antenna mount description -------------------*/ static int decode_bnx_00_1c(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-1c: not supported message\n"); return 0; } /* decode binex mesaage 0x00-1d: antenna xyz position ------------------------*/ static int decode_bnx_00_1d(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-1d: not supported message\n"); return 0; } /* decode binex mesaage 0x00-1e: antenna geographic position -----------------*/ static int decode_bnx_00_1e(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-1e: not supported message\n"); return 0; } /* decode binex mesaage 0x00-1f: antenna offset from reference point ---------*/ static int decode_bnx_00_1f(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-1f: not supported message\n"); return 0; } /* decode binex mesaage 0x00-20: antenna radome type -------------------------*/ static int decode_bnx_00_20(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-20: not supported message\n"); return 0; } /* decode binex mesaage 0x00-21: antenna radome number -----------------------*/ static int decode_bnx_00_21(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-21: not supported message\n"); return 0; } /* decode binex mesaage 0x00-22: geocode -------------------------------------*/ static int decode_bnx_00_22(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-22: not supported message\n"); return 0; } /* decode binex mesaage 0x00-7f: notes/additional information ----------------*/ static int decode_bnx_00_7f(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x00-7f: not supported message\n"); return 0; } /* decode binex mesaage 0x00: site/monument/marker/ref point/setup metadata --*/ static int decode_bnx_00(raw_t *raw, unsigned char *buff, int len) { const static double gpst0[]={1980,1,6,0,0,0}; char *msg; unsigned char *p=buff; unsigned int min,qsec,src,fid; int n=6; min =U4(p); p+=4; qsec=U1(p); p+=1; src =U1(p); p+=1; n+=getbnxi(p,&fid); raw->time=timeadd(epoch2time(gpst0),min*60.0+qsec*0.25); if (raw->outtype) { msg=raw->msgtype+strlen(raw->msgtype); sprintf(msg," fid=%02X time=%s src=%d",fid,time_str(raw->time,0),src); } switch (fid) { case 0x00: return decode_bnx_00_00(raw,buff+n,len-n); case 0x01: return decode_bnx_00_01(raw,buff+n,len-n); case 0x02: return decode_bnx_00_02(raw,buff+n,len-n); case 0x03: return decode_bnx_00_03(raw,buff+n,len-n); case 0x04: return decode_bnx_00_04(raw,buff+n,len-n); case 0x05: return decode_bnx_00_05(raw,buff+n,len-n); case 0x06: return decode_bnx_00_06(raw,buff+n,len-n); case 0x07: return decode_bnx_00_07(raw,buff+n,len-n); case 0x08: return decode_bnx_00_08(raw,buff+n,len-n); case 0x09: return decode_bnx_00_09(raw,buff+n,len-n); case 0x0A: return decode_bnx_00_0a(raw,buff+n,len-n); case 0x0B: return decode_bnx_00_0b(raw,buff+n,len-n); case 0x0C: return decode_bnx_00_0c(raw,buff+n,len-n); case 0x0D: return decode_bnx_00_0d(raw,buff+n,len-n); case 0x0E: return decode_bnx_00_0e(raw,buff+n,len-n); case 0x0F: return decode_bnx_00_0f(raw,buff+n,len-n); case 0x10: return decode_bnx_00_10(raw,buff+n,len-n); case 0x11: return decode_bnx_00_11(raw,buff+n,len-n); case 0x12: return decode_bnx_00_12(raw,buff+n,len-n); case 0x13: return decode_bnx_00_13(raw,buff+n,len-n); case 0x14: return decode_bnx_00_14(raw,buff+n,len-n); case 0x15: return decode_bnx_00_15(raw,buff+n,len-n); case 0x16: return decode_bnx_00_16(raw,buff+n,len-n); case 0x17: return decode_bnx_00_17(raw,buff+n,len-n); case 0x18: return decode_bnx_00_18(raw,buff+n,len-n); case 0x19: return decode_bnx_00_19(raw,buff+n,len-n); case 0x1A: return decode_bnx_00_1a(raw,buff+n,len-n); case 0x1B: return decode_bnx_00_1b(raw,buff+n,len-n); case 0x1C: return decode_bnx_00_1c(raw,buff+n,len-n); case 0x1D: return decode_bnx_00_1d(raw,buff+n,len-n); case 0x1E: return decode_bnx_00_1e(raw,buff+n,len-n); case 0x1F: return decode_bnx_00_1f(raw,buff+n,len-n); case 0x20: return decode_bnx_00_20(raw,buff+n,len-n); case 0x21: return decode_bnx_00_21(raw,buff+n,len-n); case 0x22: return decode_bnx_00_22(raw,buff+n,len-n); case 0x7F: return decode_bnx_00_7f(raw,buff+n,len-n); } return 0; } /* decode binex mesaage 0x01-00: coded (raw bytes) gnss ephemeris ------------*/ static int decode_bnx_01_00(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x01-00: not supported message\n"); return 0; } /* decode binex mesaage 0x01-01: decoded gps ephmemeris ----------------------*/ static int decode_bnx_01_01(raw_t *raw, unsigned char *buff, int len) { eph_t eph={0}; unsigned char *p=buff; double tow,ura,sqrtA; int prn,flag; trace(4,"binex 0x01-01: len=%d\n",len); if (len>=127) { prn =U1(p)+1; p+=1; eph.week =U2(p); p+=2; tow =I4(p); p+=4; eph.toes =I4(p); p+=4; eph.tgd[0]=R4(p); p+=4; eph.iodc =I4(p); p+=4; eph.f2 =R4(p); p+=4; eph.f1 =R4(p); p+=4; eph.f0 =R4(p); p+=4; eph.iode =I4(p); p+=4; eph.deln =R4(p)*SC2RAD; p+=4; eph.M0 =R8(p); p+=8; eph.e =R8(p); p+=8; sqrtA =R8(p); p+=8; eph.cic =R4(p); p+=4; eph.crc =R4(p); p+=4; eph.cis =R4(p); p+=4; eph.crs =R4(p); p+=4; eph.cuc =R4(p); p+=4; eph.cus =R4(p); p+=4; eph.OMG0 =R8(p); p+=8; eph.omg =R8(p); p+=8; eph.i0 =R8(p); p+=8; eph.OMGd =R4(p)*SC2RAD; p+=4; eph.idot =R4(p)*SC2RAD; p+=4; ura =R4(p)*0.1; p+=4; eph.svh =U2(p); p+=2; flag =U2(p); } else { trace(2,"binex 0x01-01: length error len=%d\n",len); return -1; } if (!(eph.sat=satno(SYS_GPS,prn))) { trace(2,"binex 0x01-01: satellite error prn=%d\n",prn); return -1; } eph.A=sqrtA*sqrtA; eph.toe=gpst2time(eph.week,eph.toes); eph.toc=gpst2time(eph.week,eph.toes); eph.ttr=adjweek(eph.toe,tow); eph.fit=flag&0xFF; eph.flag=(flag>>8)&0x01; eph.code=(flag>>9)&0x03; eph.sva=uraindex(ura); if (!strstr(raw->opt,"-EPHALL")) { if (raw->nav.eph[eph.sat-1].iode==eph.iode&& raw->nav.eph[eph.sat-1].iodc==eph.iodc) return 0; /* unchanged */ } raw->nav.eph[eph.sat-1]=eph; raw->ephsat=eph.sat; return 2; } /* decode binex mesaage 0x01-02: decoded glonass ephmemeris ------------------*/ static int decode_bnx_01_02(raw_t *raw, unsigned char *buff, int len) { geph_t geph={0}; unsigned char *p=buff; double tod,tof,tau_gps; int prn,day,leap; trace(4,"binex 0x01-02: len=%d\n",len); if (len>=119) { prn =U1(p)+1; p+=1; day =U2(p); p+=2; tod =U4(p); p+=4; geph.taun =-R8(p); p+=8; geph.gamn =R8(p); p+=8; tof =U4(p); p+=4; geph.pos[0]=R8(p)*1E3; p+=8; geph.vel[0]=R8(p)*1E3; p+=8; geph.acc[0]=R8(p)*1E3; p+=8; geph.pos[1]=R8(p)*1E3; p+=8; geph.vel[1]=R8(p)*1E3; p+=8; geph.acc[1]=R8(p)*1E3; p+=8; geph.pos[2]=R8(p)*1E3; p+=8; geph.vel[2]=R8(p)*1E3; p+=8; geph.acc[2]=R8(p)*1E3; p+=8; geph.svh =U1(p)&0x1; p+=1; geph.frq =I1(p); p+=1; geph.age =U1(p); p+=1; leap =U1(p); p+=1; tau_gps =R8(p); p+=8; geph.dtaun =R8(p); } else { trace(2,"binex 0x01-02: length error len=%d\n",len); return -1; } if (!(geph.sat=satno(SYS_GLO,prn))) { trace(2,"binex 0x01-02: satellite error prn=%d\n",prn); return -1; } if (raw->time.time==0) return 0; geph.toe=utc2gpst(adjday(raw->time,tod-10800.0)); geph.tof=utc2gpst(adjday(raw->time,tof-10800.0)); geph.iode=(int)(fmod(tod,86400.0)/900.0+0.5); if (!strstr(raw->opt,"-EPHALL")) { if (fabs(timediff(geph.toe,raw->nav.geph[prn-MINPRNGLO].toe))<1.0&& geph.svh==raw->nav.geph[prn-MINPRNGLO].svh) return 0; /* unchanged */ } raw->nav.geph[prn-1]=geph; raw->ephsat=geph.sat; return 2; } /* decode binex mesaage 0x01-03: decoded sbas ephmemeris ---------------------*/ static int decode_bnx_01_03(raw_t *raw, unsigned char *buff, int len) { seph_t seph={0}; unsigned char *p=buff; double tow,tod,tof; int prn,week,iodn; trace(4,"binex 0x01-03: len=%d\n",len); if (len>=98) { prn =U1(p); p+=1; week =U2(p); p+=2; tow =U4(p); p+=4; seph.af0 =R8(p); p+=8; tod =R4(p); p+=4; tof =U4(p); p+=4; seph.pos[0]=R8(p)*1E3; p+=8; seph.vel[0]=R8(p)*1E3; p+=8; seph.acc[0]=R8(p)*1E3; p+=8; seph.pos[1]=R8(p)*1E3; p+=8; seph.vel[1]=R8(p)*1E3; p+=8; seph.acc[1]=R8(p)*1E3; p+=8; seph.pos[2]=R8(p)*1E3; p+=8; seph.vel[2]=R8(p)*1E3; p+=8; seph.acc[2]=R8(p)*1E3; p+=8; seph.svh =U1(p); p+=1; seph.sva =U1(p); p+=1; iodn =U1(p); } else { trace(2,"binex 0x01-03 length error: len=%d\n",len); return -1; } if (!(seph.sat=satno(SYS_SBS,prn))) { trace(2,"binex 0x01-03 satellite error: prn=%d\n",prn); return -1; } seph.t0=gpst2time(week,tow); seph.tof=adjweek(seph.t0,tof); if (!strstr(raw->opt,"-EPHALL")) { if (fabs(timediff(seph.t0,raw->nav.seph[prn-MINPRNSBS].t0))<1.0&& seph.sva==raw->nav.seph[prn-MINPRNSBS].sva) return 0; /* unchanged */ } raw->nav.seph[prn-MINPRNSBS]=seph; raw->ephsat=seph.sat; return 2; } /* decode binex mesaage 0x01-04: decoded galileo ephmemeris ------------------*/ static int decode_bnx_01_04(raw_t *raw, unsigned char *buff, int len) { eph_t eph={0}; unsigned char *p=buff; double tow,ura,sqrtA; int prn,eph_sel=0; trace(4,"binex 0x01-04: len=%d\n",len); if (strstr(raw->opt,"-GALINAV")) eph_sel=1; if (strstr(raw->opt,"-GALFNAV")) eph_sel=2; if (len>=127) { prn =U1(p)+1; p+=1; eph.week =U2(p); p+=2; /* gal-week = gps-week */ tow =I4(p); p+=4; eph.toes =I4(p); p+=4; eph.tgd[0]=R4(p); p+=4; /* BGD E5a/E1 */ eph.tgd[1]=R4(p); p+=4; /* BGD E5b/E1 */ eph.iode =I4(p); p+=4; /* IODnav */ eph.f2 =R4(p); p+=4; eph.f1 =R4(p); p+=4; eph.f0 =R4(p); p+=4; eph.deln =R4(p)*SC2RAD; p+=4; eph.M0 =R8(p); p+=8; eph.e =R8(p); p+=8; sqrtA =R8(p); p+=8; eph.cic =R4(p); p+=4; eph.crc =R4(p); p+=4; eph.cis =R4(p); p+=4; eph.crs =R4(p); p+=4; eph.cuc =R4(p); p+=4; eph.cus =R4(p); p+=4; eph.OMG0 =R8(p); p+=8; eph.omg =R8(p); p+=8; eph.i0 =R8(p); p+=8; eph.OMGd =R4(p)*SC2RAD; p+=4; eph.idot =R4(p)*SC2RAD; p+=4; ura =R4(p); p+=4; eph.svh =U2(p); p+=2; eph.code =U2(p); /* data source defined as rinex 3.03 */ } else { trace(2,"binex 0x01-04: length error len=%d\n",len); return -1; } if (!(eph.sat=satno(SYS_GAL,prn))) { trace(2,"binex 0x01-04: satellite error prn=%d\n",prn); return -1; } if (eph_sel==1&&!(eph.code&(1<<9))) return 0; /* only I/NAV */ if (eph_sel==2&&!(eph.code&(1<<8))) return 0; /* only F/NAV */ eph.A=sqrtA*sqrtA; eph.iodc=eph.iode; eph.toe=gpst2time(eph.week,eph.toes); eph.toc=gpst2time(eph.week,eph.toes); eph.ttr=adjweek(eph.toe,tow); eph.sva=ura<0.0?(int)(-ura)-1:sisaindex(ura); /* sisa index */ if (!strstr(raw->opt,"-EPHALL")) { if (raw->nav.eph[eph.sat-1].iode==eph.iode&& raw->nav.eph[eph.sat-1].iodc==eph.iodc) return 0; /* unchanged */ } raw->nav.eph[eph.sat-1]=eph; raw->ephsat=eph.sat; return 2; } /* beidou signed 10 bit tgd -> sec -------------------------------------------*/ static double bds_tgd(int tgd) { tgd&=0x3FF; return (tgd&0x200)?-1E-10*((~tgd)&0x1FF):1E-10*(tgd&0x1FF); } /* decode binex mesaage 0x01-05: decoded beidou-2/compass ephmemeris ---------*/ static int decode_bnx_01_05(raw_t *raw, unsigned char *buff, int len) { eph_t eph={0}; unsigned char *p=buff; double tow,toc,sqrtA; int prn,flag1,flag2; trace(4,"binex 0x01-05: len=%d\n",len); if (len>=117) { prn =U1(p); p+=1; eph.week =U2(p); p+=2; tow =I4(p); p+=4; toc =I4(p); p+=4; eph.toes =I4(p); p+=4; eph.f2 =R4(p); p+=4; eph.f1 =R4(p); p+=4; eph.f0 =R4(p); p+=4; eph.deln =R4(p)*SC2RAD; p+=4; eph.M0 =R8(p); p+=8; eph.e =R8(p); p+=8; sqrtA =R8(p); p+=8; eph.cic =R4(p); p+=4; eph.crc =R4(p); p+=4; eph.cis =R4(p); p+=4; eph.crs =R4(p); p+=4; eph.cuc =R4(p); p+=4; eph.cus =R4(p); p+=4; eph.OMG0 =R8(p); p+=8; eph.omg =R8(p); p+=8; eph.i0 =R8(p); p+=8; eph.OMGd =R4(p)*SC2RAD; p+=4; eph.idot =R4(p)*SC2RAD; p+=4; flag1 =U2(p); p+=2; flag2 =U4(p); } else { trace(2,"binex 0x01-05: length error len=%d\n",len); return -1; } if (!(eph.sat=satno(SYS_CMP,prn))) { trace(2,"binex 0x01-05: satellite error prn=%d\n",prn); return 0; } eph.A=sqrtA*sqrtA; eph.toe=gpst2time(eph.week+1356,eph.toes+14.0); /* bdt -> gpst */ eph.toc=gpst2time(eph.week+1356,eph.toes+14.0); /* bdt -> gpst */ eph.ttr=adjweek(eph.toe,tow+14.0); /* bdt -> gpst */ eph.iodc=(flag1>>1)&0x1F; eph.iode=(flag1>>6)&0x1F; eph.svh=flag1&0x01; eph.sva=flag2&0x0F; /* ura index */ eph.tgd[0]=bds_tgd(flag2>> 4); /* TGD1 (s) */ eph.tgd[1]=bds_tgd(flag2>>14); /* TGD2 (s) */ eph.flag=(flag1>>11)&0x07; /* nav type (0:unknown,1:IGSO/MEO,2:GEO) */ eph.code=(flag2>>25)&0x7F; /* message source (0:unknown,1:B1I,2:B1Q,3:B2I,4:B2Q,5:B3I,6:B3Q)*/ if (!strstr(raw->opt,"-EPHALL")) { if (timediff(raw->nav.eph[eph.sat-1].toe,eph.toe)==0.0&& raw->nav.eph[eph.sat-1].iode==eph.iode&& raw->nav.eph[eph.sat-1].iodc==eph.iodc) return 0; /* unchanged */ } raw->nav.eph[eph.sat-1]=eph; raw->ephsat=eph.sat; return 2; } /* decode binex mesaage 0x01-06: decoded qzss ephmemeris ---------------------*/ static int decode_bnx_01_06(raw_t *raw, unsigned char *buff, int len) { eph_t eph={0}; unsigned char *p=buff; double tow,ura,sqrtA; int prn,flag; trace(4,"binex 0x01-06: len=%d\n",len); if (len>=127) { prn =U1(p); p+=1; eph.week =U2(p); p+=2; tow =I4(p); p+=4; eph.toes =I4(p); p+=4; eph.tgd[0]=R4(p); p+=4; eph.iodc =I4(p); p+=4; eph.f2 =R4(p); p+=4; eph.f1 =R4(p); p+=4; eph.f0 =R4(p); p+=4; eph.iode =I4(p); p+=4; eph.deln =R4(p)*SC2RAD; p+=4; eph.M0 =R8(p); p+=8; eph.e =R8(p); p+=8; sqrtA =R8(p); p+=8; eph.cic =R4(p); p+=4; eph.crc =R4(p); p+=4; eph.cis =R4(p); p+=4; eph.crs =R4(p); p+=4; eph.cuc =R4(p); p+=4; eph.cus =R4(p); p+=4; eph.OMG0 =R8(p); p+=8; eph.omg =R8(p); p+=8; eph.i0 =R8(p); p+=8; eph.OMGd =R4(p)*SC2RAD; p+=4; eph.idot =R4(p)*SC2RAD; p+=4; ura =R4(p)*0.1; p+=4; eph.svh =U2(p); p+=2; flag =U2(p); } else { trace(2,"binex 0x01-06: length error len=%d\n",len); return -1; } if (!(eph.sat=satno(SYS_QZS,prn))) { trace(2,"binex 0x01-06: satellite error prn=%d\n",prn); return 0; } eph.A=sqrtA*sqrtA; eph.toe=gpst2time(eph.week,eph.toes); eph.toc=gpst2time(eph.week,eph.toes); eph.ttr=adjweek(eph.toe,tow); eph.fit=(flag&0x01)?0.0:2.0; /* 0:2hr,1:>2hr */ eph.sva=uraindex(ura); eph.code=2; /* codes on L2 channel */ if (!strstr(raw->opt,"-EPHALL")) { if (raw->nav.eph[eph.sat-1].iode==eph.iode&& raw->nav.eph[eph.sat-1].iodc==eph.iodc) return 0; /* unchanged */ } raw->nav.eph[eph.sat-1]=eph; raw->ephsat=eph.sat; return 2; } /* decode binex mesaage 0x01-14: upgraded decoded galileo ephmemeris ---------*/ static int decode_bnx_01_14(raw_t *raw, unsigned char *buff, int len) { eph_t eph={0}; unsigned char *p=buff; double tow,ura,sqrtA; int prn,tocs,eph_sel=0; trace(4,"binex 0x01-14: len=%d\n",len); if (strstr(raw->opt,"-GALINAV")) eph_sel=1; if (strstr(raw->opt,"-GALFNAV")) eph_sel=2; if (len>=135) { prn =U1(p)+1; p+=1; eph.week =U2(p); p+=2; /* gal-week = gps-week */ tow =I4(p); p+=4; tocs =I4(p); p+=4; eph.toes =I4(p); p+=4; eph.tgd[0]=R4(p); p+=4; /* BGD E5a/E1 */ eph.tgd[1]=R4(p); p+=4; /* BGD E5b/E1 */ eph.iode =I4(p); p+=4; /* IODnav */ eph.f2 =R4(p); p+=4; eph.f1 =R4(p); p+=4; eph.f0 =R8(p); p+=8; eph.deln =R4(p)*SC2RAD; p+=4; eph.M0 =R8(p); p+=8; eph.e =R8(p); p+=8; sqrtA =R8(p); p+=8; eph.cic =R4(p); p+=4; eph.crc =R4(p); p+=4; eph.cis =R4(p); p+=4; eph.crs =R4(p); p+=4; eph.cuc =R4(p); p+=4; eph.cus =R4(p); p+=4; eph.OMG0 =R8(p); p+=8; eph.omg =R8(p); p+=8; eph.i0 =R8(p); p+=8; eph.OMGd =R4(p)*SC2RAD; p+=4; eph.idot =R4(p)*SC2RAD; p+=4; ura =R4(p); p+=4; eph.svh =U2(p); p+=2; eph.code =U2(p); /* data source defined as rinex 3.03 */ } else { trace(2,"binex 0x01-14: length error len=%d\n",len); return -1; } if (!(eph.sat=satno(SYS_GAL,prn))) { trace(2,"binex 0x01-14: satellite error prn=%d\n",prn); return -1; } if (eph_sel==1&&!(eph.code&(1<<9))) return 0; /* only I/NAV */ if (eph_sel==2&&!(eph.code&(1<<8))) return 0; /* only F/NAV */ eph.A=sqrtA*sqrtA; eph.iodc=eph.iode; eph.toe=gpst2time(eph.week,eph.toes); eph.toc=gpst2time(eph.week,tocs); eph.ttr=adjweek(eph.toe,tow); eph.sva=ura<0.0?(int)(-ura)-1:sisaindex(ura); /* sisa index */ if (!strstr(raw->opt,"-EPHALL")) { if (raw->nav.eph[eph.sat-1].iode==eph.iode&& raw->nav.eph[eph.sat-1].iodc==eph.iodc) return 0; /* unchanged */ } raw->nav.eph[eph.sat-1]=eph; raw->ephsat=eph.sat; return 2; } /* decode binex mesaage 0x01: gnss navigaion informtion ----------------------*/ static int decode_bnx_01(raw_t *raw, unsigned char *buff, int len) { char *msg; int srec=U1(buff),prn=U1(buff+1); if (raw->outtype) { msg=raw->msgtype+strlen(raw->msgtype); prn=srec==0x01||srec==0x02||srec==0x04?prn+1:(srec==0x00?0:prn); sprintf(msg," subrec=%02X prn=%d",srec,prn); } switch (srec) { case 0x00: return decode_bnx_01_00(raw,buff+1,len-1); case 0x01: return decode_bnx_01_01(raw,buff+1,len-1); case 0x02: return decode_bnx_01_02(raw,buff+1,len-1); case 0x03: return decode_bnx_01_03(raw,buff+1,len-1); case 0x04: return decode_bnx_01_04(raw,buff+1,len-1); case 0x05: return decode_bnx_01_05(raw,buff+1,len-1); case 0x06: return decode_bnx_01_06(raw,buff+1,len-1); case 0x14: return decode_bnx_01_14(raw,buff+1,len-1); } return 0; } /* decode binex mesaage 0x02: generalized gnss data --------------------------*/ static int decode_bnx_02(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x02: not supported message\n"); return 0; } /* decode binex mesaage 0x03: generalized ancillary site data ----------------*/ static int decode_bnx_03(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x03: not supported message\n"); return 0; } /* decode binex mesaage 0x7d: receiver internal state prototyping ------------*/ static int decode_bnx_7d(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7d: not supported message\n"); return 0; } /* decode binex mesaage 0x7e: ancillary site data prototyping ----------------*/ static int decode_bnx_7e(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7e: not supported message\n"); return 0; } /* decode binex mesaage 0x7f-00: jpl fiducial site ---------------------------*/ static int decode_bnx_7f_00(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7f-00: not supported message\n"); return 0; } /* decode binex mesaage 0x7f-01: ucar cosmic ---------------------------------*/ static int decode_bnx_7f_01(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7f-01: not supported message\n"); return 0; } /* decode binex mesaage 0x7f-02: trimble 4700 --------------------------------*/ static int decode_bnx_7f_02(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7f-02: not supported message\n"); return 0; } /* decode binex mesaage 0x7f-03: trimble netrs -------------------------------*/ static int decode_bnx_7f_03(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7f-03: not supported message\n"); return 0; } /* decode binex mesaage 0x7f-04: trimble netrs -------------------------------*/ static int decode_bnx_7f_04(raw_t *raw, unsigned char *buff, int len) { trace(2,"binex 0x7f-04: not supported message\n"); return 0; } /* decode binex mesaage 0x7f-05: trimble netr8 obs data ----------------------*/ static unsigned char *decode_bnx_7f_05_obs(raw_t *raw, unsigned char *buff, int sat, int nobs, obsd_t *data) { const unsigned char codes_gps[32]={ CODE_L1C ,CODE_L1C ,CODE_L1P ,CODE_L1W ,CODE_L1Y ,CODE_L1M , /* 0- 5 */ CODE_L1X ,CODE_L1N ,CODE_NONE,CODE_NONE,CODE_L2W ,CODE_L2C , /* 6-11 */ CODE_L2D ,CODE_L2S ,CODE_L2L ,CODE_L2X ,CODE_L2P ,CODE_L2W , /* 12-17 */ CODE_L2Y ,CODE_L2M ,CODE_L2N ,CODE_NONE,CODE_NONE,CODE_L5X , /* 18-23 */ CODE_L5I ,CODE_L5Q ,CODE_L5X /* 24-26 */ }; const unsigned char codes_glo[32]={ CODE_L1C ,CODE_L1C ,CODE_L1P ,CODE_NONE,CODE_NONE,CODE_NONE, /* 0- 5 */ CODE_NONE,CODE_NONE,CODE_NONE,CODE_NONE,CODE_L2C ,CODE_L2C , /* 6-11 */ CODE_L2P ,CODE_L3X ,CODE_L3I ,CODE_L3Q ,CODE_L3X /* 12-16 */ }; const unsigned char codes_gal[32]={ CODE_L1C ,CODE_L1A ,CODE_L1B ,CODE_L1C ,CODE_L1X ,CODE_L1Z , /* 0- 5 */ CODE_L5X ,CODE_L5I ,CODE_L5Q ,CODE_L5X ,CODE_L7X ,CODE_L7I , /* 6-11 */ CODE_L7Q ,CODE_L7X ,CODE_L8X ,CODE_L8I ,CODE_L8Q ,CODE_L8X , /* 12-17 */ CODE_L6X ,CODE_L6A ,CODE_L6B ,CODE_L6C ,CODE_L6X ,CODE_L6Z , /* 18-23 */ }; const unsigned char codes_sbs[32]={ CODE_L1C ,CODE_L1C ,CODE_NONE,CODE_NONE,CODE_NONE,CODE_NONE, /* 0- 5 */ CODE_L5X ,CODE_L5I ,CODE_L5Q ,CODE_L5X /* 6- 9 */ }; const unsigned char codes_cmp[32]={ CODE_L1X ,CODE_L1I ,CODE_L1Q ,CODE_L1X ,CODE_L7X ,CODE_L7I , /* 0- 5 */ CODE_L7Q ,CODE_L7X ,CODE_L6X ,CODE_L6I ,CODE_L6Q ,CODE_L6X , /* 6-11 */ CODE_L1X ,CODE_L1S ,CODE_L1L ,CODE_L1X /* 12-15 */ }; const unsigned char codes_qzs[32]={ CODE_L1C ,CODE_L1C ,CODE_L1S ,CODE_L1L ,CODE_L1X ,CODE_NONE, /* 0- 5 */ CODE_NONE,CODE_L2X ,CODE_L2S ,CODE_L2L ,CODE_L2X ,CODE_NONE, /* 6-11 */ CODE_NONE,CODE_L5X ,CODE_L5I ,CODE_L5Q ,CODE_L5X ,CODE_NONE, /* 12-17 */ CODE_NONE,CODE_L6X ,CODE_L6S ,CODE_L6L ,CODE_L6X ,CODE_NONE, /* 18-23 */ CODE_NONE,CODE_NONE,CODE_NONE,CODE_NONE,CODE_NONE,CODE_NONE, /* 24-29 */ CODE_L1Z /* 30-30 */ }; const unsigned char *codes=NULL; double range[8],phase[8],cnr[8],dopp[8]={0},acc,wl; unsigned char *p=buff; unsigned char flag,flags[4]; int i,j,k,sys,fcn=-10,code[8],slip[8],pri[8],freq[8],slipcnt[8]={0},mask[8]={0}; trace(5,"decode_bnx_7f_05_obs: sat=%2d nobs=%2d\n",sat,nobs); sys=satsys(sat,NULL); switch (sys) { case SYS_GPS: codes=codes_gps; break; case SYS_GLO: codes=codes_glo; break; case SYS_GAL: codes=codes_gal; break; case SYS_QZS: codes=codes_qzs; break; case SYS_SBS: codes=codes_sbs; break; case SYS_CMP: codes=codes_cmp; break; } for (i=0;i<nobs;i++) { flag =getbitu(p,0,1); slip[i]=getbitu(p,2,1); code[i]=getbitu(p,3,5); p++; for (j=0;j<4;j++) flags[j]=0; for (j=0;flag&&j<4;j++) { flag=U1(p++); flags[flag&0x03]=flag&0x7F; flag&=0x80; } if (flags[2]) { fcn=getbits(flags+2,2,4); } acc=(flags[0]&0x20)?0.0001:0.00002; /* phase accuracy */ cnr[i]=U1(p++)*0.4; if (i==0) { cnr[i]+=getbits(p,0,2)*0.1; range[i]=getbitu(p,2,32)*0.064+getbitu(p,34,6)*0.001; p+=5; } else if (flags[0]&0x40) { cnr[i]+=getbits(p,0,2)*0.1; range[i]=range[0]+getbits(p,4,20)*0.001; p+=3; } else { range[i]=range[0]+getbits(p,0,16)*0.001; p+=2; } if (flags[0]&0x40) { phase[i]=range[i]+getbits(p,0,24)*acc; p+=3; } else { cnr[i]+=getbits(p,0,2)*0.1; phase[i]=range[i]+getbits(p,2,22)*acc; p+=3; } if (flags[0]&0x04) { dopp[i]=getbits(p,0,24)/256.0; p+=3; } if (flags[0]&0x08) { if (flags[0]&0x10) { slipcnt[i]=U2(p); p+=2; } else { slipcnt[i]=U1(p); p+=1; } } trace(5,"(%d) CODE=%2d S=%d F=%02X %02X %02X %02X\n",i+1, code[i],slip[i],flags[0],flags[1],flags[2],flags[3]); trace(5,"(%d) P=%13.3f L=%13.3f D=%7.1f SNR=%4.1f SCNT=%2d\n", i+1,range[i],phase[i],dopp[i],cnr[i],slipcnt[i]); } if (!codes) { data->sat=0; return p; } data->time=raw->time; data->sat=sat; /* get code priority */ for (i=0;i<nobs;i++) { code2obs(codes[code[i]&0x3F],freq+i); pri[i]=getcodepri(sys,codes[code[i]&0x3F],raw->opt); /* frequency index for beidou */ if (sys==SYS_CMP) { if (freq[i]==5) freq[i]=2; /* B2 */ else if (freq[i]==4) freq[i]=3; /* B3 */ } else if (sys==SYS_GAL) { if (freq[i]==5) freq[i]=2; /* E5b */ } } for (i=0;i<NFREQ;i++) { for (j=0,k=-1;j<nobs;j++) { if (freq[j]==i+1&&(k<0||pri[j]>pri[k])) k=j; } if (k<0) { data->P[i]=data->L[i]=0.0; data->D[i]=0.0f; data->SNR[i]=data->LLI[i]=0; data->code[i]=CODE_NONE; } else { wl=satwavelen(sat,i,&raw->nav); if (sys==SYS_GLO&&fcn>=-7&&freq[k]<=2) { wl=CLIGHT/(freq[k]==1?FREQ1_GLO+DFRQ1_GLO*fcn: FREQ2_GLO+DFRQ2_GLO*fcn); } data->P[i]=range[k]; data->L[i]=wl<=0.0?0.0:phase[k]/wl; data->D[i]=dopp[k]; data->SNR[i]=(unsigned char)(cnr[k]/0.25+0.5); data->code[i]=codes[code[k]&0x3F]; data->LLI[i]=slip[k]?1:0; mask[k]=1; } } for (;i<NFREQ+NEXOBS;i++) { for (k=0;k<nobs;k++) { if (!mask[k]) break; } if (k>=nobs) { data->P[i]=data->L[i]=0.0; data->D[i]=0.0f; data->SNR[i]=data->LLI[i]=0; data->code[i]=CODE_NONE; } else { wl=satwavelen(sat,freq[k]-1,&raw->nav); if (sys==SYS_GLO&&fcn>=-7&&freq[k]<=2) { wl=CLIGHT/(freq[k]==1?FREQ1_GLO+DFRQ1_GLO*fcn: FREQ2_GLO+DFRQ2_GLO*fcn); } data->P[i]=range[k]; data->L[i]=wl<=0.0?0.0:phase[k]/wl; data->D[i]=dopp[k]; data->SNR[i]=(unsigned char)(cnr[k]/0.25+0.5); data->code[i]=codes[code[k]&0x3F]; data->LLI[i]=slip[k]?1:0; mask[k]=1; } } return p; } /* decode binex mesaage 0x7f-05: trimble netr8 -------------------------------*/ static int decode_bnx_7f_05(raw_t *raw, unsigned char *buff, int len) { obsd_t data={{0}}; double clkoff=0.0,toff[16]={0}; char *msg; unsigned char *p=buff; unsigned int flag; int i,nsat,nobs,prn,sys,sat,clkrst=0,rsys=0,nsys=0,tsys[16]={0}; trace(4,"decode_bnx_7f_05\n"); raw->obs.n=0; flag=U1(p++); nsat=(int)(flag&0x3F)+1; if (flag&0x80) { /* rxclkoff */ clkrst=getbitu(p,0, 2); clkoff=getbits(p,2,22)*1E-9; p+=3; } if (flag&0x40) { /* systime */ nsys=getbitu(p,0,4); rsys=getbitu(p,4,4); p++; for (i=0;i<nsys;i++) { toff[i]=getbits(p,0,24)*1E-9; tsys[i]=getbitu(p,28,4); p+=4; } } for (i=0;i<nsat;i++) { prn =U1(p++); nobs=getbitu(p,1,3); sys =getbitu(p,4,4); p++; trace(5,"binex 0x7F-05 PRN=%3d SYS=%d NOBS=%d\n",prn,sys,nobs); switch (sys) { case 0: sat=satno(SYS_GPS,prn); break; case 1: sat=satno(SYS_GLO,prn); break; case 2: sat=satno(SYS_SBS,prn); break; case 3: sat=satno(SYS_GAL,prn); break; case 4: sat=satno(SYS_CMP,prn); break; case 5: sat=satno(SYS_QZS,prn); break; default: sat=0; break; } /* decode binex mesaage 0x7F-05 obs data */ if (!(p=decode_bnx_7f_05_obs(raw,p,sat,nobs,&data))) return -1; if ((int)(p-buff)>len) { trace(2,"binex 0x7F-05 length error: nsat=%2d len=%d\n",nsat,len); return -1; } /* save obs data to obs buffer */ if (data.sat&&raw->obs.n<MAXOBS) { raw->obs.data[raw->obs.n++]=data; } } if (raw->outtype) { msg=raw->msgtype+strlen(raw->msgtype); sprintf(msg," nsat=%2d",nsat); } return raw->obs.n>0?1:0; } /* decode binex mesaage 0x7f: gnss data prototyping --------------------------*/ static int decode_bnx_7f(raw_t *raw, unsigned char *buff, int len) { const static double gpst0[]={1980,1,6,0,0,0}; char *msg; unsigned char *p=buff; unsigned int srec,min,msec; srec=U1(p); p+=1; /* subrecord id */ min =U4(p); p+=4; msec=U2(p); p+=2; raw->time=timeadd(epoch2time(gpst0),min*60.0+msec*0.001); if (raw->outtype) { msg=raw->msgtype+strlen(raw->msgtype); sprintf(msg," subrec=%02X time%s",srec,time_str(raw->time,3)); } switch (srec) { case 0x00: return decode_bnx_7f_00(raw,buff+7,len-7); case 0x01: return decode_bnx_7f_01(raw,buff+7,len-7); case 0x02: return decode_bnx_7f_02(raw,buff+7,len-7); case 0x03: return decode_bnx_7f_03(raw,buff+7,len-7); case 0x04: return decode_bnx_7f_04(raw,buff+7,len-7); case 0x05: return decode_bnx_7f_05(raw,buff+7,len-7); } return 0; } /* decode binex mesaage ------------------------------------------------------*/ static int decode_bnx(raw_t *raw) { unsigned int len,cs1,cs2; int rec,len_h; rec=raw->buff[1]; /* record id */ /* record and header length */ len_h=getbnxi(raw->buff+2,&len); trace(5,"decode_bnx: rec=%02x len=%d\n",rec,len); /* check parity */ if (raw->len-1<128) { cs1=U1(raw->buff+raw->len); cs2=csum8(raw->buff+1,raw->len-1); } else { cs1=U2(raw->buff+raw->len); cs2=rtk_crc16(raw->buff+1,raw->len-1); } if (cs1!=cs2) { trace(2,"binex 0x%02X parity error CS=%X %X\n",rec,cs1,cs2); return -1; } if (raw->outtype) { sprintf(raw->msgtype,"BINEX 0x%02X (%4d)",rec,raw->len); } /* decode binex message record */ switch (rec) { case 0x00: return decode_bnx_00(raw,raw->buff+2+len_h,len); case 0x01: return decode_bnx_01(raw,raw->buff+2+len_h,len); case 0x02: return decode_bnx_02(raw,raw->buff+2+len_h,len); case 0x03: return decode_bnx_03(raw,raw->buff+2+len_h,len); case 0x7d: return decode_bnx_7d(raw,raw->buff+2+len_h,len); case 0x7e: return decode_bnx_7e(raw,raw->buff+2+len_h,len); case 0x7f: return decode_bnx_7f(raw,raw->buff+2+len_h,len); } return 0; } /* synchronize binex message -------------------------------------------------*/ static int sync_bnx(unsigned char *buff, unsigned char data) { buff[0]=buff[1]; buff[1]=data; return buff[0]==BNXSYNC2&& (buff[1]==0x00||buff[1]==0x01||buff[1]==0x02||buff[1]==0x03|| buff[1]==0x7D||buff[1]==0x7E||buff[1]==0x7F); } /* input binex message from stream --------------------------------------------- * fetch next binex data and input a message from stream * args : raw_t *raw IO receiver raw data control struct * unsigned char data I stream data (1 byte) * return : status (-1: error message, 0: no message, 1: input observation data, * 2: input ephemeris) * notes : support only the following message (ref [1]) * * - big-endian, regular CRC, forward record (sync=0xE2) * - record-subrecord: * 0x01-01: decoded gps ephemeris * 0x01-02: decoded glonass ephemeris * 0x01-03: decoded sbas ephemeris * 0x01-04: decoded galileo ephemeris * 0x01-05: decoded beidou-2/compass ephemeris * 0x01-06: decoded qzss ephemeris * 0x7f-05: gnss data prototyping - trimble netr8 * * to specify input options, set rtcm->opt to the following option * strings separated by spaces. * * -EPHALL : input all ephemerides * -GLss : select signal ss for GPS (ss=1C,1P,...) * -RLss : select signal ss for GLO (ss=1C,1P,...) * -ELss : select signal ss for GAL (ss=1C,1B,...) * -JLss : select signal ss for QZS (ss=1C,2C,...) * -CLss : select signal ss for BDS (ss=2I,2X,...) * -GALINAV : input only I/NAV for galileo ephemeris * -GALFNAV : input only F/NAV for galileo ephemeris *-----------------------------------------------------------------------------*/ extern int input_bnx(raw_t *raw, unsigned char data) { unsigned int len; int len_h,len_c; trace(5,"input_bnx: data=%02x\n",data); /* synchronize binex message */ if (raw->nbyte==0) { if (!sync_bnx(raw->buff,data)) return 0; raw->nbyte=2; return 0; } raw->buff[raw->nbyte++]=data; if (raw->nbyte<4) return 0; len_h=getbnxi(raw->buff+2,&len); raw->len=len+len_h+2; /* length without crc */ if (raw->len-1>4096) { trace(2,"binex length error: len=%d\n",raw->len-1); raw->nbyte=0; return -1; } len_c=raw->len-1<128?1:2; if (raw->nbyte<(int)(raw->len+len_c)) return 0; raw->nbyte=0; /* decode binex message */ return decode_bnx(raw); } /* input binex message from file ----------------------------------------------- * fetch next binex data and input a message from file * args : raw_t *raw IO receiver raw data control struct * FILE *fp I file pointer * return : status(-2: end of file, -1...9: same as above) *-----------------------------------------------------------------------------*/ extern int input_bnxf(raw_t *raw, FILE *fp) { unsigned int len; int i,data,len_h,len_c; trace(4,"input_bnxf\n"); if (raw->nbyte==0) { for (i=0;;i++) { if ((data=fgetc(fp))==EOF) return -2; if (sync_bnx(raw->buff,(unsigned char)data)) break; if (i>=4096) return 0; } } if (fread(raw->buff+2,1,4,fp)<4) return -2; len_h=getbnxi(raw->buff+2,&len); raw->len=len+len_h+2; if (raw->len-1>4096) { trace(2,"binex length error: len=%d\n",raw->len-1); raw->nbyte=0; return -1; } len_c=raw->len-1<128?1:2; if (fread(raw->buff+6,1,raw->len+len_c-6,fp)<(size_t)(raw->len+len_c-6)) { return -2; } raw->nbyte=0; /* decode binex message */ return decode_bnx(raw); }
36.041545
84
0.527695
akstuki
9fec843460ec66bcbb72c3cbe0ed45e049a4ebfc
13,318
cpp
C++
examples/esp32_devkit_v1_tx/src/smartport.cpp
nkruzan/hx_espnow_rc
448f8c42bff36f8182665a865fcfe391560b01f0
[ "MIT" ]
10
2021-07-11T22:24:11.000Z
2022-02-05T06:13:17.000Z
examples/esp32_devkit_v1_tx/src/smartport.cpp
nkruzan/hx_espnow_rc
448f8c42bff36f8182665a865fcfe391560b01f0
[ "MIT" ]
1
2021-11-22T23:09:58.000Z
2021-11-22T23:35:39.000Z
examples/esp32_devkit_v1_tx/src/smartport.cpp
nkruzan/hx_espnow_rc
448f8c42bff36f8182665a865fcfe391560b01f0
[ "MIT" ]
1
2021-11-16T02:41:25.000Z
2021-11-16T02:41:25.000Z
#include "smartport.h" #include "smartport.h" #include "tx_config.h" //https://github.com/yaapu/FrskyTelemetryScript/wiki/FrSky-SPort-protocol-specs //include for HXRCLOG usage #include "HX_ESPNOW_RC_Common.h" #define FRSKY_START_STOP 0x7e #define FRSKY_BYTESTUFF 0x7d #define FRSKY_STUFF_MASK 0x20 // FrSky data IDs (2 bytes) //https://github.com/yaapu/FrskyTelemetryScript/wiki/FrSky-SPort-protocol-specs //https://github.com/Clooney82/MavLink_FrSkySPort/wiki/1.2.-FrSky-Taranis-Telemetry //https://github.com/opentx/opentx/blob/d67d1aa0c09d2f485c3ef7ca8c4fb1e9214a2ee7/radio/src/telemetry/frsky.h //opentx units and precision: //https://github.com/opentx/opentx/blob/d67d1aa0c09d2f485c3ef7ca8c4fb1e9214a2ee7/radio/src/telemetry/frsky_sport.cpp //https://github.com/iNavFlight/inav/blob/master/src/main/telemetry/smartport.c #define FRSKY_SPORT_ALT_ID 0x0100 #define FRSKY_SPORT_VARIO_ID 0x0110 #define FRSKY_SPORT_CURR_ID 0x0200 #define FRSKY_SPORT_VFAS_ID 0x0210 //Battery or cell voltage #define FRSKY_SPORT_CELLS_FIRST_ID 0x0300 #define FRSKY_SPORT_CELLS_LAST_ID 0x030F #define FRSKY_SPORT_T1_ID 0x0400 //tempterature or flight mode #define FRSKY_SPORT_T2_ID 0x0410 //temperature or GPS state #define FRSKY_SPORT_HOME_DIST 0x0420 #define FRSKY_SPORT_PITCH 0x0430 #define FRSKY_SPORT_ROLL 0x0440 #define FRSKY_SPORT_FPV 0x0450 #define FRSKY_SPORT_RPM_ID 0x0500 #define FRSKY_SPORT_RPM1 0x050E #define FRSKY_SPORT_RPM2 0x050F #define FRSKY_SPORT_FUEL_ID 0x0600 //battery percentage or mAh #define FRSKY_SPORT_ACCX_ID 0x0700 #define FRSKY_SPORT_ACCY_ID 0x0710 #define FRSKY_SPORT_ACCZ_ID 0x0720 #define FRSKY_SPORT_GPS_LONG_LATI_ID 0x0800 #define FRSKY_SPORT_GPS_ALT_ID 0x0820 #define FRSKY_SPORT_GPS_SPEED_ID 0x0830 #define FRSKY_SPORT_GPS_COURS_ID 0x0840 #define FRSKY_SPORT_GPS_TIME_DATE_ID 0x0850 #define FRSKY_SPORT_ASPD 0x0A00 //pitot sensor speed #define FRSKY_SPORT_A3 0x0900 #define FRSKY_SPORT_A4 0x0910 //average battery voltage #define FRSKY_SPORT_DIY_FIRST_ID 0x5000 #define FRSKY_SPORT_DIY_LAST_ID 0x52ff //0x5000 status text //0x5001 AP status //0x5002 GPS Status //0x5003 Battery 1 status //0x5004 Home //0x5005 Vel and Yaw //0x5007 parameters //0x5008 Battery 2 status //0x500A rpm sensors 1 and 2 //0x500B terrain data //0x500C terrain data #define FRSKY_SPORT_DIY_NOISE_FLOOR_ID 0x5250 #define FRSKY_SPORT_DIY_SNR_ID 0x5251 #define FRSKY_SPORT_DIY_RX_RSSI_ID 0x5252 #define FRSKY_SPORT_DIY_RX_RSSI_DBM_ID 0x5253 #define FRSKY_SPORT_DIY_RX_NOISE_FLOOR_ID 0x5254 #define FRSKY_SPORT_DIY_RX_SNR_ID 0x5255 #define FRSKY_SPORT_DIY_PROFILE_ID 0x5256 #define FRSKY_SPORT_DIY_DEBUG_1_ID 0x5260 #define FRSKY_SPORT_DIY_DEBUG_2_ID 0x5261 #define FRSKY_SPORT_DIY_DEBUG_3_ID 0x5262 #define FRSKY_SPORT_VALID_FRAME_RATE_ID 0xF010 //UNIT_PERCENT displayed as 100-data in OpenTX #define FRSKY_SPORT_RSSI_ID 0xf101 //low byte - rssi in dbm, 0x64 = 100dbm #define FRSKY_SPORT_ADC1_ID 0xf102 // A1 Volts Ratio 13.2 Precision 1 #define FRSKY_SPORT_ADC2_ID 0xf103 // A2 Volts Ratio 13.2 Precision 1 #define FRSKY_SPORT_BATT_ID 0xf104 //Volts, Ratio 13.2 Precision 2 #define FRSKY_SPORT_SWR_ID 0xf105 #define FRSKY_SPORT_R9_PWR_ID 0xF107 //sent in dbm, displayed in mW, dbm=>mw = {{0, 1}, {5, 3}, {10, 10}, {13, 20}, {14, 25}, {20, 100}, {23, 200}, {27, 500}, {30, 1000}}; #define FRSKY_SPORT_SP2UART_A_ID 0xFD00 #define FRSKY_SPORT_SP2UART_B_ID 0xFD01 #define FRSKY_SPORT_RX_LQI_ID 0xFFFC #define FRSKY_SPORT_TX_LQI_ID 0xFFFD #define FRSKY_SPORT_TX_RSSI_ID 0xFFFE // FrSky sensor IDs (this also happens to be the order in which they're broadcast from an X8R) #define FRSKY_SPORT_DEVICE_1 0xa1 #define FRSKY_SPORT_DEVICE_2 0x22 #define FRSKY_SPORT_DEVICE_3 0x83 #define FRSKY_SPORT_DEVICE_4 0xe4 #define FRSKY_SPORT_DEVICE_5 0x45 #define FRSKY_SPORT_DEVICE_6 0xc6 #define FRSKY_SPORT_DEVICE_7 0x67 #define FRSKY_SPORT_DEVICE_8 0x48 #define FRSKY_SPORT_DEVICE_9 0xe9 #define FRSKY_SPORT_DEVICE_10 0x6a #define FRSKY_SPORT_DEVICE_11 0xcb #define FRSKY_SPORT_DEVICE_12 0xac #define FRSKY_SPORT_DEVICE_13 0xd #define FRSKY_SPORT_DEVICE_14 0x8e #define FRSKY_SPORT_DEVICE_15 0x2f #define FRSKY_SPORT_DEVICE_16 0xd0 #define FRSKY_SPORT_DEVICE_17 0x71 #define FRSKY_SPORT_DEVICE_18 0xf2 #define FRSKY_SPORT_DEVICE_19 0x53 #define FRSKY_SPORT_DEVICE_20 0x34 #define FRSKY_SPORT_DEVICE_21 0x95 #define FRSKY_SPORT_DEVICE_22 0x16 #define FRSKY_SPORT_DEVICE_23 0xb7 #define FRSKY_SPORT_DEVICE_24 0x98 #define FRSKY_SPORT_DEVICE_25 0x39 #define FRSKY_SPORT_DEVICE_26 0xba #define FRSKY_SPORT_DEVICE_27 0x1b #define FRSKY_SPORT_A2_MAX 124 // A2 voltage is represented by a value in the range 0-255. A value of 16 results in 1.6V, 124 is 12.4V, etc //===================================================================== //===================================================================== Smartport::Smartport(HardwareSerial* serial) { this->setValues = 0; this->serial = serial; } //===================================================================== //===================================================================== void Smartport::init() { this->serial->begin(57600, SERIAL_8N1, -1, SPORT_PIN, true ); pinMode(SPORT_PIN, OUTPUT); //call after serial->begin() this->lastSend = millis(); this->lastSensor = 0; } //===================================================================== //===================================================================== void Smartport::sendByte(uint8_t byte) { // CRC update this->crc += byte;//0-1FF this->crc += this->crc >> 8;//0-100 this->crc &= 0x00ff; this->crc += this->crc >> 8;//0-0FF this->crc &= 0x00ff; if ( (byte == FRSKY_START_STOP) || (byte == FRSKY_BYTESTUFF) ) { this->serial->write(FRSKY_BYTESTUFF); byte &= ~FRSKY_STUFF_MASK; } this->serial->write(byte); } //===================================================================== //===================================================================== void Smartport::sendCrc() { this->sendByte(0xFF - this->crc); } //===================================================================== //===================================================================== void Smartport::sendValue(uint16_t id, uint32_t value) { this->crc = 0; // Reset CRC this->sendByte(0x10);// DATA_FRAME uint8_t *bytes = (uint8_t*)&id; this->sendByte(bytes[0]); this->sendByte(bytes[1]); bytes = (uint8_t*)&value; this->sendByte(bytes[0]); this->sendByte(bytes[1]); this->sendByte(bytes[2]); this->sendByte(bytes[3]); this->sendCrc(); } //===================================================================== //===================================================================== void Smartport::sendDeviceValue(uint8_t deviceId, uint16_t sensorId, uint32_t value) { this->serial->write( FRSKY_START_STOP ); //0x7e this->serial->write( deviceId); //0x98 //low byte - rssi in dbm, 0x64 = 100dbm this->sendValue(sensorId, value); } //===================================================================== //===================================================================== bool Smartport::findNextValue() { uint8_t count = SVI_COUNT; while ( true ) { this->lastSensor++; if ( this->lastSensor == SVI_COUNT ) this->lastSensor = 0; uint32_t sensorMask = (1<<this->lastSensor); if ( this->setValues & sensorMask ) { this->setValues &= ~sensorMask; break; } count--; if ( count == 0 ) return false; } return true; } //===================================================================== //===================================================================== void Smartport::loop() { unsigned long t = millis(); unsigned long deltaT = t - this->lastSend; if ( deltaT > 11 ) { this->lastSend = t; if ( !this->findNextValue() ) return; switch (this->lastSensor) { case SVI_RSSI: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_RSSI_ID, this->values[this->lastSensor]); break; case SVI_RSSI_DBM: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_TX_RSSI_ID, this->values[this->lastSensor]); break; case SVI_NOISE_FLOOR: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_NOISE_FLOOR_ID, this->values[this->lastSensor]); break; case SVI_SNR: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_SNR_ID, this->values[this->lastSensor]); break; case SVI_RX_RSSI: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_RX_RSSI_ID, this->values[this->lastSensor]); break; case SVI_RX_RSSI_DBM: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_RX_RSSI_DBM_ID, this->values[this->lastSensor]); break; case SVI_RX_NOISE_FLOOR: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_RX_NOISE_FLOOR_ID, this->values[this->lastSensor]); break; case SVI_RX_SNR: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_RX_SNR_ID, this->values[this->lastSensor]); break; case SVI_R9_PWR_ID: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_R9_PWR_ID, this->values[this->lastSensor]); break; case SVI_VALID_FRAME_RATE: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_VALID_FRAME_RATE_ID, this->values[this->lastSensor]); break; case SVI_PROFILE_ID: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_PROFILE_ID, this->values[this->lastSensor]); break; case SVI_DEBUG_1: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_DEBUG_1_ID, this->values[this->lastSensor]); break; case SVI_DEBUG_2: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_DEBUG_2_ID, this->values[this->lastSensor]); break; case SVI_DEBUG_3: this->sendDeviceValue(FRSKY_SPORT_DEVICE_24, FRSKY_SPORT_DIY_DEBUG_3_ID, this->values[this->lastSensor]); break; case SVI_A1: this->sendDeviceValue(FRSKY_SPORT_DEVICE_4, FRSKY_SPORT_ADC1_ID, this->values[this->lastSensor]); break; case SVI_A2: this->sendDeviceValue(FRSKY_SPORT_DEVICE_4, FRSKY_SPORT_ADC2_ID, this->values[this->lastSensor]); break; case SVI_VFAS: this->sendDeviceValue(FRSKY_SPORT_DEVICE_4, FRSKY_SPORT_VFAS_ID, this->values[this->lastSensor]); break; case SVI_ALTITUDE: this->sendDeviceValue(FRSKY_SPORT_DEVICE_11, FRSKY_SPORT_ALT_ID, this->values[this->lastSensor]); break; } } } /* this->serial->write( 0x7e ); this->serial->write( 0x98 ); this->serial->write( 0x10 ); this->serial->write( 0x01 ); this->serial->write( 0xf1 ); this->serial->write( 0x64 ); this->serial->write( 0xcd ); this->serial->write( 0x00 ); this->serial->write( 0x5e ); this->serial->write( 0x6c ); */ /* case 3: this->serial->write( FRSKY_START_STOP ); //0x7e this->serial->write( FRSKY_SPORT_DEVICE_10); this->sendDIYValue(FRSKY_SPORT_ACCX_ID, 0); break; case 4: this->serial->write( FRSKY_START_STOP ); //0x7e this->serial->write( FRSKY_SPORT_DEVICE_10); this->sendDIYValue(FRSKY_SPORT_ACCY_ID, 1); break; case 5: this->serial->write( FRSKY_START_STOP ); //0x7e this->serial->write( FRSKY_SPORT_DEVICE_10); this->sendDIYValue(FRSKY_SPORT_ACCZ_ID, 2); break; */ /* case FRSKY_SPORT_DEVICE_8: FrSkySport_sendACCX(); break; case FRSKY_SPORT_DEVICE_9: FrSkySport_sendACCY(); break; case FRSKY_SPORT_DEVICE_10: FrSkySport_sendACCZ(); break; case FRSKY_SPORT_DEVICE_11: FrSkySport_sendAltitude(); break; case FRSKY_SPORT_DEVICE_12: FrSkySport_sendAltVario(); break; case FRSKY_SPORT_DEVICE_13: this->sendValue(FRSKY_SPORT_GPS_COURS_ID, (uint32_t)(10 + 360) % 360 * 100); // 1 deg = 100, 0 - 359000 break; case FRSKY_SPORT_DEVICE_14: FrSkySport_sendGPSSpeed(); break; case FRSKY_SPORT_DEVICE_15: FrSkySport_sendGPSAltitude(); break; case FRSKY_SPORT_DEVICE_16: FrSkySport_sendGPSCoordinate(); break; */
35.047368
181
0.614732
nkruzan
9fefa7c60ad27d61f2f4727ddc7e6e4434464592
3,147
cc
C++
framework/JPetUnpacker/Unpacker2/Unpacker_TRB2.cc
wictus/oldScopeAnalysis
e8a15f11c504c1a1a880d4a5096cdbfac0edf2de
[ "MIT" ]
null
null
null
framework/JPetUnpacker/Unpacker2/Unpacker_TRB2.cc
wictus/oldScopeAnalysis
e8a15f11c504c1a1a880d4a5096cdbfac0edf2de
[ "MIT" ]
null
null
null
framework/JPetUnpacker/Unpacker2/Unpacker_TRB2.cc
wictus/oldScopeAnalysis
e8a15f11c504c1a1a880d4a5096cdbfac0edf2de
[ "MIT" ]
null
null
null
#include "Unpacker_TRB2.h" #include <iostream> using namespace std; ClassImp(Unpacker_TRB2); Unpacker_TRB2::Unpacker_TRB2(string bT, string bA, string hA, int cN, int o, int r, string mR, bool dec, bool dbg) : UnpackingModule(bT, bA, hA, cN, o, r, mR, dec, dbg) { cerr<<"TRB2: Creating Unpacker_TRB2 for board type: "<<bT<<" board address "<<bA<<" hub address "<<hA<<endl; } void Unpacker_TRB2::ProcessEvent(UInt_t* data, Event* evt) { event = evt; // clear internal unpackers map<std::string, UnpackingModule*>::iterator iter; for(iter = GetInternalUnpackersIterBegin(); iter != GetInternalUnpackersIterEnd(); iter++) { iter->second->Clear(); } UInt_t data_i = 0; if(GetInvertBytes() == true) { data_i = ReverseHex((*data)); } else { data_i = (*data); } // get the size of the data in the event size_t dataSize = data_i & 0xffff; data += 2; // skip to the first data word dataSize -= 2; UInt_t tdcNumber = 0; if(debugMode == true) cerr<<"Unpacker_TRB2.cc: Receiving "<<dataSize<<" words to analyze"<<endl; if (dataSize > 10000) { cerr<<"WARNING: event size too large, skipping event"<<endl; // cerr<<" Dumping first data bytes:"<<endl; // // int ctr = 50; // while(ctr > 0) { // printf("%04X\n", (*data)); // data++; // ctr--; // } } else { // iterate through all the 32b words of the current event while(dataSize > 0) { if(GetInvertBytes() == true) { data_i = ReverseHex((*data)); } else { data_i = (*data); } // read out the address and redirect data to the correct internal unpacker tdcNumber = (data_i >> 24) & 0xf; GetUnpacker(UIntToString(tdcNumber))->ProcessEvent(data); data++; dataSize--; } } } void Unpacker_TRB2::GetADCHits() { } void Unpacker_TRB2::GetTDCHits() { map<std::string, UnpackingModule*>::iterator iter; for(iter = GetInternalUnpackersIterBegin(); iter != GetInternalUnpackersIterEnd(); iter++) { if(iter->second->GetMeasurementType() == "TDC") { for(int i = 0; i < iter->second->GetChannelNumber(); i++) { if (iter->second->GetLeadMult(i) > 0 || iter->second->GetTrailMult(i) > 0 ) { TDCHit* hit = event->AddTDCHit(iter->second->GetChannelOffset() + i); if(iter->second->GetLeadMult(i) > 0) { if(iter->second->GetChannelOffset() + i == referenceChannel) { event->SetTDCReferenceTime(iter->second->GetLeadTime(i, 0)); if(debugMode == true) cerr<<"Unpacker_TRB2.cc: Adding referenceTime"<<endl; } for(UInt_t j = 0; j < iter->second->GetLeadMult(i); j++) hit->AddLeadTime(iter->second->GetLeadTime(i, j)); } if(iter->second->GetTrailMult(i) > 0) { for(UInt_t j = 0; j < iter->second->GetTrailMult(i); j++) hit->AddTrailTime(iter->second->GetTrailTime(i, j)); } if(iter->second->GetFirstLeadCorrect(i) == true && iter->second->GetTrailMult(i) > 0) hit->AddTot(iter->second->GetTrailTime(i, 0) - iter->second->GetLeadTime(i, 0)); } } } } }
27.849558
170
0.600254
wictus
9ff29ce12e58e47c0b7ab7cf27f380ca2646def2
2,400
hpp
C++
src/main/cpp/inverted_penguin/io/FileInputBuffer.hpp
tomault/inverted_penguin
0cd939de38d860d32194203048d0a70a34fcca75
[ "Apache-2.0" ]
null
null
null
src/main/cpp/inverted_penguin/io/FileInputBuffer.hpp
tomault/inverted_penguin
0cd939de38d860d32194203048d0a70a34fcca75
[ "Apache-2.0" ]
null
null
null
src/main/cpp/inverted_penguin/io/FileInputBuffer.hpp
tomault/inverted_penguin
0cd939de38d860d32194203048d0a70a34fcca75
[ "Apache-2.0" ]
null
null
null
#ifndef __INVERTED_PENGUIN__IO__FILEINPUTBUFFER_HPP__ #define __INVERTED_PENGUIN__IO__FILEINPUTBUFFER_HPP__ #include <pistis/filesystem/File.hpp> #include <memory> #include <string.h> namespace inverted_penguin { namespace io { class FileInputBuffer { public: static constexpr const size_t DEFAULT_BUFFER_SIZE = 65536; public: FileInputBuffer(pistis::filesystem::File&& file, size_t defaultBufferSize = DEFAULT_BUFFER_SIZE): file_(std::move(file)), buffer_(), end_(buffer_.get()), bufferSize_(defaultBufferSize) { } FileInputBuffer(const std::string& name, size_t defaultBufferSize = DEFAULT_BUFFER_SIZE): FileInputBuffer( pistis::filesystem::File::open( name, pistis::filesystem::FileAccessMode::READ_ONLY ), defaultBufferSize ) { } FileInputBuffer(const FileInputBuffer&) = delete; FileInputBuffer(FileInputBuffer&&) = default; size_t size() const { return bufferSize_; } size_t occupied() const { return end_ - buffer_.get(); } const char* begin() { fill_(); return buffer_.get(); } const char* end() { fill_(); return end_; } size_t fill(size_t numToSave = 0) { if (numToSave) { ::memmove(buffer_.get(), end_ - numToSave, numToSave); } end_ = buffer_.get() + numToSave; return fill_(); } size_t resize(size_t requested) { if (requested > (end_ - buffer_.get())) { std::unique_ptr<char[]> newBuffer_(new char[requested]); if (end_ > buffer_.get()) { ::memcpy(newBuffer_.get(), buffer_.get(), end_ - buffer_.get()); } end_ = newBuffer_.get() + (end_ - buffer_.get()); buffer_ = std::move(newBuffer); bufferSize_ = requested; fill_(); } return bufferSize_; } FileInputBuffer& operator=(const FileInputBuffer&) = delete; FileInputBuffer& operator=(FileInputBuffer&&) = default; private: pistis::filesystem::File file_; std::unique_ptr<char[]> buffer_; char* end_; size_t bufferSize_; size_t fill_() { if (!buffer_) { buffer_.reset(new char[bufferSize_]); end_ = buffer_.get(); } char* const bufferEnd_ = buffer_.get() + bufferSize_; assert(end_ <= bufferEnd_); if (end_ < bufferEnd_) { size_t n = file_.read(end_, bufferEnd_ - end); end_ += n; } return occupied(); } }; } } #endif
24.489796
69
0.641667
tomault
9ff2f15d760b0c3ae960beee703b0d2664e72063
1,125
cpp
C++
common/source/common/toolkit/UiTk.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
common/source/common/toolkit/UiTk.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
common/source/common/toolkit/UiTk.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
#include "UiTk.h" #include <boost/algorithm/string.hpp> bool uitk::userYNQuestion(const std::string& question, boost::optional<bool> defaultAnswer, std::istream& input) { while (true) { std::cout << question << " [" << (defaultAnswer.value_or(false) ? 'Y' : 'y') << "/" << (defaultAnswer.value_or(true) ? 'n' : 'N') << "] ? " << std::flush; // read answer from input stream const auto answer = [&input] () { std::string answer; std::getline(input, answer); boost::to_upper(answer); boost::trim(answer); return answer; }(); if (answer.empty()) { if (defaultAnswer.is_initialized()) { return defaultAnswer.get(); } else { std::cin.clear(); std::cout << std::endl; } } if ("Y" == answer || "YES" == answer) return true; if ("N" == answer || "NO" == answer) return false; } }
23.93617
62
0.439111
TomatoYoung
9ff6f1bad392dba29818eaf746d6e7af0d384b7f
9,710
cpp
C++
Raymarcher/src/Fractal/Folds/Folds.cpp
conholo/Raymarcher
880a268a1ca11161df52462a2b2908a402408227
[ "Apache-2.0" ]
null
null
null
Raymarcher/src/Fractal/Folds/Folds.cpp
conholo/Raymarcher
880a268a1ca11161df52462a2b2908a402408227
[ "Apache-2.0" ]
null
null
null
Raymarcher/src/Fractal/Folds/Folds.cpp
conholo/Raymarcher
880a268a1ca11161df52462a2b2908a402408227
[ "Apache-2.0" ]
null
null
null
#include "rmpch.h" #include "Fractal/Folds/Folds.h" #include "Fractal/FractalUtility.h" #include <glm/gtx/string_cast.hpp> namespace RM { Fold::Fold() :IGLSLConvertable(ColorType::None, AttributeType::Fold) { } std::string FoldScaleTranslate::TransformationToGLSL() const { std::stringstream ss; if (m_Scale != 1.0) { if (m_Scale >= 0) { ss << "\tposition *= " << std::to_string(m_Scale) << ";\n"; } else { ss << "\tposition.xyz *= " << std::to_string(m_Scale) << ";\n"; ss << "\tposition.w *= abs(" << std::to_string(m_Scale) << ");\n"; } } if(m_Translation != glm::vec3(0.0f)) { ss << "\tposition.xyz += " << glm::to_string(m_Translation) << ";\n"; } return ss.str(); } std::string FoldPlane::TransformationToGLSL() const { switch (m_Direction) { case FoldDirection::Right: return "\tposition.x = abs(position.x - " + std::to_string(m_Factor) + ") + " + std::to_string(m_Factor) + ";\n"; case FoldDirection::Up: return "\tposition.y = abs(position.y - " + std::to_string(m_Factor) + ") + " + std::to_string(m_Factor) + ";\n"; case FoldDirection::Forward: return "\tposition.z = abs(position.z - " + std::to_string(m_Factor) + ") + " + std::to_string(m_Factor) + ";\n"; case FoldDirection::Left: return "\tposition.x = -abs(position.x + " + std::to_string(m_Factor) + ") - " + std::to_string(m_Factor) + ";\n"; case FoldDirection::Down: return "\tposition.y = -abs(position.y + " + std::to_string(m_Factor) + ") - " + std::to_string(m_Factor) + ";\n"; case FoldDirection::Back: return "\tposition.z = -abs(position.z + " + std::to_string(m_Factor) + ") - " + std::to_string(m_Factor) + ";\n"; case FoldDirection::None: return ""; } return ""; } std::string FoldMenger::TransformationToGLSL() const { return "\tMengerFold(position);\n"; } std::string FoldSierpinski::TransformationToGLSL() const { return "\SierpinskiFold(position);\n"; } std::string FoldBox::TransformationToGLSL() const { return "\tBoxFold(position, " + glm::to_string(m_Range) + ");\n"; } std::string FoldSphere::TransformationToGLSL() const { return "\tSphereFold(position, " + std::to_string(m_MinRadius) + ", " + std::to_string(m_MaxRadius) + ");\n"; } std::string FoldAbs::TransformationToGLSL() const { return "\tAbsFold(position, " + glm::to_string(m_Center) + ");\n"; } std::string FoldInversion::TransformationToGLSL() const { return "\tposition *= 1.0 / (dot(position.xyz, position.xyz) + " + std::to_string(m_Epsilon) + ");\n"; } std::string FoldRotateX::TransformationToGLSL() const { std::stringstream ss; ss << "\tRotationXFold(position, u_DoRotationX == 1 ? sin(u_ElapsedTime * u_RotationXSpeed * 2.0 * PI) : " + std::to_string(glm::sin(m_Radians)) + ", u_DoRotationX == 1 ? cos(u_ElapsedTime * u_RotationXSpeed * 2.0 * PI) : " + std::to_string(glm::cos(m_Radians)) + ");\n"; return ss.str(); } std::string FoldRotateY::TransformationToGLSL() const { std::stringstream ss; ss << "\tRotationYFold(position, u_DoRotationY == 1 ? sin(u_ElapsedTime * u_RotationYSpeed * 2.0 * PI) : " + std::to_string(glm::sin(m_Radians)) + ", u_DoRotationY == 1 ? cos(u_ElapsedTime * u_RotationYSpeed * 2.0 * PI) : " + std::to_string(glm::cos(m_Radians)) + ");\n"; return ss.str(); } std::string FoldRotateZ::TransformationToGLSL() const { std::stringstream ss; ss << "\tRotationZFold(position, u_DoRotationZ == 1 ? sin(u_ElapsedTime * u_RotationZSpeed * 2.0 * PI) : " + std::to_string(glm::sin(m_Radians)) + ", u_DoRotationZ == 1 ? cos(u_ElapsedTime * u_RotationZSpeed * 2.0 * PI) : " + std::to_string(glm::cos(m_Radians)) + ");\n"; return ss.str(); } std::string FoldRepeatX::TransformationToGLSL() const { return "\tposition.x = abs(mod(position.x - " + std::to_string(m_Step) + " / 2, " + std::to_string(m_Step) + ") - " + std::to_string(m_Step) + " / 2);\n"; } std::string FoldRepeatY::TransformationToGLSL() const { return "\tposition.y = abs(mod(position.y - " + std::to_string(m_Step) + " / 2, " + std::to_string(m_Step) + ") - " + std::to_string(m_Step) + " / 2);\n"; } std::string FoldRepeatZ::TransformationToGLSL() const { return "\tposition.z = abs(mod(position.z - " + std::to_string(m_Step) + " / 2, " + std::to_string(m_Step) + ") - " + std::to_string(m_Step) + " / 2);\n"; } std::string FoldRepeatXYZ::TransformationToGLSL() const { return "\tposition.xyz = abs(mod(position.xyz - " + std::to_string(m_Step) + " / 2, " + std::to_string(m_Step) + ") - " + std::to_string(m_Step) + " / 2);\n"; } std::string FoldScaleOrigin::TransformationToGLSL() const { return "\tposition = position * " + std::to_string(m_Scale) + "; position.w = abs(position.w); position += o;\n"; } void FoldScaleTranslate::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Scale" << YAML::Value << m_Scale; out << YAML::Key << "Translation" << YAML::Value << m_Translation; out << YAML::EndMap; out << YAML::EndMap; } void FoldScaleOrigin::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Scale" << YAML::Value << m_Scale; out << YAML::Key << "Origin" << YAML::Value << m_Origin; out << YAML::EndMap; out << YAML::EndMap; } void FoldPlane::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Factor" << YAML::Value << m_Factor; out << YAML::Key << "Direction" << YAML::Value << (int)m_Direction; out << YAML::EndMap; out << YAML::EndMap; } void FoldMenger::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::EndMap; } void FoldSierpinski::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::EndMap; } void FoldBox::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Range" << YAML::Value << m_Range; out << YAML::EndMap; out << YAML::EndMap; } void FoldSphere::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Min Radius" << YAML::Value << m_MinRadius; out << YAML::Key << "Max Radius" << YAML::Value << m_MaxRadius; out << YAML::EndMap; out << YAML::EndMap; } void FoldAbs::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Center" << YAML::Value << m_Center; out << YAML::EndMap; out << YAML::EndMap; } void FoldInversion::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Epsilon" << YAML::Value << m_Epsilon; out << YAML::EndMap; out << YAML::EndMap; } void FoldRotateX::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Radians" << YAML::Value << m_Radians; out << YAML::EndMap; out << YAML::EndMap; } void FoldRotateY::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Radians" << YAML::Value << m_Radians; out << YAML::EndMap; out << YAML::EndMap; } void FoldRotateZ::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Radians" << YAML::Value << m_Radians; out << YAML::EndMap; out << YAML::EndMap; } void FoldRepeatX::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Step" << YAML::Value << m_Step; out << YAML::EndMap; out << YAML::EndMap; } void FoldRepeatY::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Step" << YAML::Value << m_Step; out << YAML::EndMap; out << YAML::EndMap; } void FoldRepeatZ::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Step" << YAML::Value << m_Step; out << YAML::EndMap; out << YAML::EndMap; } void FoldRepeatXYZ::Serialize(YAML::Emitter& out) { out << YAML::BeginMap; out << YAML::Key << "Type" << YAML::Value << ToString(); out << YAML::Key << "Fields" << YAML::Value << YAML::BeginMap; out << YAML::Key << "Step" << YAML::Value << m_Step; out << YAML::EndMap; out << YAML::EndMap; } }
30.727848
273
0.606591
conholo
9ff74e42f109dacdfb1ef91e3a7ac43060fc99b2
781
cpp
C++
Luogu/107/P1104.cpp
anine09/ACM
e9e8f09157e4ec91c1752a4b4724e28dfeaae4e6
[ "MIT" ]
null
null
null
Luogu/107/P1104.cpp
anine09/ACM
e9e8f09157e4ec91c1752a4b4724e28dfeaae4e6
[ "MIT" ]
null
null
null
Luogu/107/P1104.cpp
anine09/ACM
e9e8f09157e4ec91c1752a4b4724e28dfeaae4e6
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> #include<string> using namespace std; struct student { string name; int year; int month; int day; int num; } s[110]; int n; bool cmp(student a,student b){ if(a.year==b.year){ if (a.month==b.month) { if(a.day==b.day) return a.num > b.num; else return a.day < b.day; } else return a.month < b.month; } return a.year < b.year; } int main(){ cin>>n; for (int i = 0; i < n; i++) { cin >> s[i].name >> s[i].year >> s[i].month >> s[i].day; s[i].num = i; } sort(s, s + n, cmp); for (int i = 0; i < n; i++) { cout << s[i].name << endl; } return 0; }
16.617021
64
0.441741
anine09