hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
f035ab93bef94a250ff2ca333fdd69a5f83a7943
6,444
cpp
C++
src/sim/entities/sim_Explosion.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
4
2021-01-28T17:39:38.000Z
2022-02-11T20:13:46.000Z
src/sim/entities/sim_Explosion.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
null
null
null
src/sim/entities/sim_Explosion.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
3
2021-02-22T21:22:30.000Z
2022-01-10T19:32:12.000Z
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * 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 <sim/entities/sim_Explosion.h> #include <osgParticle/ModularEmitter> #include <osgParticle/ParticleSystemUpdater> #include <osgParticle/RandomRateCounter> #include <osgParticle/RadialShooter> //////////////////////////////////////////////////////////////////////////////// using namespace sim; //////////////////////////////////////////////////////////////////////////////// Explosion::Explosion( float scale, Group *parent ) : Entity( parent, Active, 10.5f ) { createExplosionFire( scale ); createExplosionSmoke( scale ); } //////////////////////////////////////////////////////////////////////////////// Explosion::~Explosion() {} //////////////////////////////////////////////////////////////////////////////// void Explosion::createExplosionFire( float scale ) { osg::ref_ptr<osg::Group> group = new osg::Group(); _switch->addChild( group.get() ); osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform(); group->addChild( pat.get() ); pat->setAttitude( osg::Quat( 0.0, osg::Z_AXIS, -osg::PI_2, osg::Y_AXIS, -osg::PI_2, osg::X_AXIS ) ); osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem(); ps->getDefaultParticleTemplate().setLifeTime( 0.5f ); ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD ); ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(1.0f*scale, 2.0f*scale) ); ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) ); ps->getDefaultParticleTemplate().setColorRange( osgParticle::rangev4(osg::Vec4(1.0f,1.0f,0.5f,1.0f), osg::Vec4(1.0f,0.5f,0.0f,1.0f)) ); ps->setDefaultAttributes( getPath( "textures/explosion_fire.rgb" ), true, false ); osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter(); rrc->setRateRange( 10, 20 ); osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter(); shooter->setThetaRange( -osg::PI, osg::PI ); shooter->setPhiRange( -osg::PI, osg::PI ); shooter->setInitialSpeedRange( -10.0f, 10.0f ); osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter(); emitter->setParticleSystem( ps.get() ); emitter->setCounter( rrc.get() ); emitter->setShooter( shooter.get() ); emitter->setEndless( false ); emitter->setLifeTime( 0.25f ); pat->addChild( emitter.get() ); osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater(); updater->addParticleSystem( ps.get() ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode->addDrawable( ps.get() ); group->addChild( updater.get() ); group->addChild( geode.get() ); } //////////////////////////////////////////////////////////////////////////////// void Explosion::createExplosionSmoke( float scale ) { osg::ref_ptr<osg::Group> group = new osg::Group(); _switch->addChild( group.get() ); osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform(); group->addChild( pat.get() ); pat->setAttitude( osg::Quat( 0.0, osg::Z_AXIS, -osg::PI_2, osg::Y_AXIS, -osg::PI_2, osg::X_AXIS ) ); osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem(); ps->getDefaultParticleTemplate().setLifeTime( 10.0f ); ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD ); ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(1.0f*scale, 8.0f*scale) ); ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) ); ps->getDefaultParticleTemplate().setColorRange( osgParticle::rangev4(osg::Vec4(0.0f,0.0f,0.0f,1.0f), osg::Vec4(0.5f,0.5f,0.5f,1.0f)) ); ps->setDefaultAttributes( getPath( "textures/explosion_smoke.rgb" ), false, false ); osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter(); rrc->setRateRange( 10, 10 ); osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter(); shooter->setThetaRange( -osg::PI, osg::PI ); shooter->setPhiRange( -osg::PI, osg::PI ); shooter->setInitialSpeedRange( -2.0f, 2.0f ); osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter(); emitter->setStartTime( 0.1f ); emitter->setParticleSystem( ps.get() ); emitter->setCounter( rrc.get() ); emitter->setShooter( shooter.get() ); emitter->setEndless( false ); emitter->setLifeTime( 0.5f ); pat->addChild( emitter.get() ); osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater(); updater->addParticleSystem( ps.get() ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode->addDrawable( ps.get() ); group->addChild( updater.get() ); group->addChild( geode.get() ); }
43.836735
105
0.617008
marek-cel
f039bed9ffb5dc464e1986b13a2bfe6e726662a1
2,678
cc
C++
google/cloud/spanner/internal/time_format_benchmark.cc
devjgm/google-cloud-cpp-spanner
e9f73518069f69f79ab8e74e69ea68babcc20a58
[ "Apache-2.0" ]
29
2019-05-03T15:03:48.000Z
2021-06-04T06:15:55.000Z
google/cloud/spanner/internal/time_format_benchmark.cc
devjgm/google-cloud-cpp-spanner
e9f73518069f69f79ab8e74e69ea68babcc20a58
[ "Apache-2.0" ]
1,199
2019-05-03T13:05:54.000Z
2020-06-01T18:58:26.000Z
google/cloud/spanner/internal/time_format_benchmark.cc
devjgm/google-cloud-cpp-spanner
e9f73518069f69f79ab8e74e69ea68babcc20a58
[ "Apache-2.0" ]
18
2019-05-02T20:53:06.000Z
2021-10-07T21:29:36.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 // // 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 "google/cloud/spanner/internal/time_format.h" #include <benchmark/benchmark.h> #include <string> namespace google { namespace cloud { namespace spanner { inline namespace SPANNER_CLIENT_NS { namespace internal { namespace { // Run on (6 X 2300 MHz CPU s) // CPU Caches: // L1 Data 32K (x3) // L1 Instruction 32K (x3) // L2 Unified 256K (x3) // L3 Unified 46080K (x1) // Load Average: 0.22, 0.26, 0.77 // --------------------------------------------------------------- // Benchmark Time CPU Iterations // --------------------------------------------------------------- // BM_FormatTime 55.2 ns 54.7 ns 12779010 // BM_FormatTimeWithFmt 1047 ns 1042 ns 668990 // BM_ParseTime 129 ns 128 ns 5474604 // BM_ParseTimeWithFmt 1323 ns 1314 ns 489764 void BM_FormatTime(benchmark::State& state) { std::tm tm; tm.tm_year = 2020 - 1900; tm.tm_mon = 1 - 1; tm.tm_mday = 17; tm.tm_hour = 18; tm.tm_min = 54; tm.tm_sec = 12; for (auto _ : state) { benchmark::DoNotOptimize(FormatTime(tm)); } } BENCHMARK(BM_FormatTime); void BM_FormatTimeWithFmt(benchmark::State& state) { std::tm tm; tm.tm_year = 2020 - 1900; tm.tm_mon = 1 - 1; tm.tm_mday = 17; tm.tm_hour = 18; tm.tm_min = 54; tm.tm_sec = 12; for (auto _ : state) { benchmark::DoNotOptimize(FormatTime("%Y-%m-%dT%H:%M:%S", tm)); } } BENCHMARK(BM_FormatTimeWithFmt); void BM_ParseTime(benchmark::State& state) { std::tm tm; std::string s = "2020-01-17T18:54:12"; for (auto _ : state) { benchmark::DoNotOptimize(ParseTime(s, &tm)); } } BENCHMARK(BM_ParseTime); void BM_ParseTimeWithFmt(benchmark::State& state) { std::tm tm; std::string s = "2020-01-17T18:54:12"; for (auto _ : state) { benchmark::DoNotOptimize(ParseTime("%Y-%m-%dT%H:%M:%S", s, &tm)); } } BENCHMARK(BM_ParseTimeWithFmt); } // namespace } // namespace internal } // namespace SPANNER_CLIENT_NS } // namespace spanner } // namespace cloud } // namespace google
28.795699
75
0.621733
devjgm
f03efe79c0b859a5c1cd955d9e71fbd2de3487f7
3,001
cpp
C++
Source/Runtime/Private/Sound/SoundSystemSLES.cpp
redchew-fork/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
[ "Apache-2.0" ]
410
2017-03-03T08:56:54.000Z
2022-03-29T07:18:46.000Z
Source/Runtime/Private/Sound/SoundSystemSLES.cpp
redchew-fork/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
[ "Apache-2.0" ]
31
2017-03-05T11:37:44.000Z
2021-09-15T21:28:34.000Z
Source/Runtime/Private/Sound/SoundSystemSLES.cpp
redchew-fork/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
[ "Apache-2.0" ]
48
2017-03-18T05:28:21.000Z
2022-03-05T12:27:17.000Z
#include "Precompiled.h" #include "Math/Math.h" #include "SIMD/SIMD.h" #include "Core/CVars.h" #include "Sound/SoundSystem.h" BE_NAMESPACE_BEGIN static const int MaxSources = 12; static CVar s_khz("s_khz", "44", CVar::Flag::Integer | CVar::Flag::Archive, ""); static CVar s_doppler("s_doppler", "1.0", CVar::Flag::Float | CVar::Flag::Archive, ""); static CVar s_rolloff("s_rolloff", "2.0", CVar::Flag::Float | CVar::Flag::Archive, ""); bool SoundSystem::InitDevice(void *windowHandle) { BE_LOG("Initializing OpenSL ES...\n"); // Create the SL engine object SLresult result = slCreateEngine(&slEngineObject, 0, nullptr, 0, nullptr, nullptr); assert(SL_RESULT_SUCCESS == result); // Realize the SL engine object result = (*slEngineObject)->Realize(slEngineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // Get the SL engine interface, which is needed in order to create other objects result = (*slEngineObject)->GetInterface(slEngineObject, SL_IID_ENGINE, &slEngine); assert(SL_RESULT_SUCCESS == result); // Create output mix object result = (*slEngine)->CreateOutputMix(slEngine, &slOutputMixObject, 0, nullptr, nullptr); assert(SL_RESULT_SUCCESS == result); // Realize the output mix object result = (*slOutputMixObject)->Realize(slOutputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); #if 0 // Create listener object const SLInterfaceID listener_ids[] = { SL_IID_3DLOCATION, SL_IID_3DSOURCE }; const SLboolean listener_req[] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE }; result = (*slEngine)->CreateListener(slEngine, &slListenerObject, 1, listener_ids, listener_req); assert(SL_RESULT_SUCCESS == result); // Realize the listener object result = (*slListenerObject)->Realize(slListenerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); #endif // Initialize sources for (int sourceIndex = 0; sourceIndex < MaxSources; sourceIndex++) { SoundSource *source = new SoundSource; sources.Append(source); freeSources.Append(source); } return true; } void SoundSystem::ShutdownDevice() { BE_LOG("Shutting down OpenSL ES...\n"); // Delete sources for (int sourceIndex = 0; sourceIndex < sources.Count(); sourceIndex++) { SoundSource *source = sources[sourceIndex]; delete source; } sources.Clear(); freeSources.Clear(); // Destroy output mix object, and invalidate all associated interfaces if (slOutputMixObject) { (*slOutputMixObject)->Destroy(slOutputMixObject); slOutputMixObject = nullptr; } // Destroy engine object, and invalidate all associated interfaces if (slEngineObject) { (*slEngineObject)->Destroy(slEngineObject); slEngineObject = nullptr; slEngine = nullptr; } } void SoundSystem::PlaceListenerInternal(const Vec3 &pos, const Vec3 &forward, const Vec3 &up) { } BE_NAMESPACE_END
33.719101
101
0.693436
redchew-fork
f041d31b129f43e8f662762762b60e49a54adb12
2,124
cpp
C++
lib-vs/src/core/tfmodel.cpp
FRC3407/VisionServer
a76fe1a35525950863f7809b65fa72286c26f622
[ "MIT" ]
2
2022-01-10T23:29:55.000Z
2022-03-04T12:36:45.000Z
lib-vs/src/core/tfmodel.cpp
FRC3407/VisionServer
a76fe1a35525950863f7809b65fa72286c26f622
[ "MIT" ]
null
null
null
lib-vs/src/core/tfmodel.cpp
FRC3407/VisionServer
a76fe1a35525950863f7809b65fa72286c26f622
[ "MIT" ]
1
2022-01-29T04:25:16.000Z
2022-01-29T04:25:16.000Z
#include "tfmodel.h" void loadObjectLabels(const std::string& f, std::vector<std::string>& objs) { objs.clear(); std::ifstream file(f); std::string line; int32_t start, end; std::getline(file, line, '\n'); if(line == "item {") { while(std::getline(file, line, '\n')) { start = end = -1; for (size_t i = 0; i < line.size(); i++) { if (line.at(i) == '"') { if (start < 0) { start = i + 1; } else { end = i; i = line.size(); // break } } } if (start >= 0 && end >= 0) { objs.emplace_back(std::move(line.substr(start, end - start))); } } } else { objs.push_back(line); while(std::getline(file, line, '\n')) { objs.push_back(line); } } file.close(); } TfModel::TfModel(std::initializer_list<std::pair<const char*, Optimization> > models, size_t th) { for(auto item = models.begin(); item != models.end(); item++) { this->map = tflite::FlatBufferModel::BuildFromFile(item->first); if(this->map) { if(item->second == Optimization::EDGETPU && tpusAvailable()) { // switch-case if more optimization options this->resolver.AddCustom(edgetpu::kCustomOp, edgetpu::RegisterCustomOp()); tflite::InterpreterBuilder builder(*this->map, this->resolver); builder.SetNumThreads(th); builder(&this->model); this->edgetpu_context = edgetpu::EdgeTpuManager::GetSingleton()->OpenDevice(); this->model->SetExternalContext(kTfLiteEdgeTpuContext, this->edgetpu_context.get()); } else { tflite::InterpreterBuilder builder(*this->map, this->resolver); builder.SetNumThreads(th); builder(&this->model); } if(this->isValid()) { break; } } } if(this->isValid()) { this->model->AllocateTensors(); if(this->model->inputs().size() == 1) { TfLiteTensor* input = this->model->input_tensor(0); TfLiteIntArray* dims = input->dims; this->input_size = cv::Size(dims->data[1], dims->data[2]); if(dims->data[3] == 3 && input->type == kTfLiteUInt8) { this->input_tensor = cv::Mat(this->input_size, CV_8UC3, input->data.data); } } else { this->input_size = cv::Size(-1, -1); } } }
28.702703
109
0.612994
FRC3407
f0477bf7e895edc949eceae7f9ced2770cf779fe
664
hpp
C++
library/ATF/std___String_baseInfo.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/std___String_baseInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/std___String_baseInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <std___String_base.hpp> START_ATF_NAMESPACE namespace std { namespace Info { using std___String_basector__String_base1_ptr = int64_t (WINAPIV*)(struct std::_String_base*, struct std::_String_base*); using std___String_basector__String_base1_clbk = int64_t (WINAPIV*)(struct std::_String_base*, struct std::_String_base*, std___String_basector__String_base1_ptr); }; // end namespace Info }; // end namespace std END_ATF_NAMESPACE
34.947368
175
0.713855
lemkova
f053c47d0bc953e643b5c0aafc06430eca429c6e
3,922
cc
C++
src/ir/ir_printer_test.cc
Cypher1/raksha
0f52f108ceb8bc7b8be36a7bf8e9662188c57551
[ "Apache-2.0" ]
null
null
null
src/ir/ir_printer_test.cc
Cypher1/raksha
0f52f108ceb8bc7b8be36a7bf8e9662188c57551
[ "Apache-2.0" ]
null
null
null
src/ir/ir_printer_test.cc
Cypher1/raksha
0f52f108ceb8bc7b8be36a7bf8e9662188c57551
[ "Apache-2.0" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright 2022 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. //---------------------------------------------------------------------------- #include "src/ir/ir_printer.h" #include "absl/container/flat_hash_set.h" #include "src/common/testing/gtest.h" #include "src/ir/attribute.h" #include "src/ir/block_builder.h" #include "src/ir/module.h" #include "src/ir/value.h" namespace raksha::ir { namespace { enum class ToStringVariant { // Call IRPrinter::ToString(const Entity&) kToString, // Call IRPrinter::ToString(std::ostream&, const Entity&) kToStringOstream, // Call `out << entity` kOperator, }; class IRPrinterTest : public testing::TestWithParam<ToStringVariant> { public: IRPrinterTest() : plus_op_("core.plus"), minus_op_("core.minus") { BlockBuilder builder; operation_ = std::addressof(builder.AddOperation(plus_op_, {}, {})); block_ = std::addressof(global_module_.AddBlock(builder.build())); global_module_.AddBlock(std::make_unique<Block>()); } const Operator& plus_op() const { return plus_op_; } const Operator& minus_op() const { return minus_op_; } const Block& block() const { return *block_; } const Module& global_module() const { return global_module_; } template <typename T> std::string ToString(const T& entity) { switch (GetParam()) { case ToStringVariant::kToString: return IRPrinter::ToString(entity); case ToStringVariant::kToStringOstream: { std::ostringstream out; IRPrinter::ToString(out, entity); return out.str(); } case ToStringVariant::kOperator: { std::ostringstream out; out << entity; return out.str(); } } // Placate compiler by marking path as unreachable. CHECK(false) << "Unreachable!"; } private: Operator plus_op_; Operator minus_op_; Module global_module_; const Operation* operation_; const Block* block_; }; INSTANTIATE_TEST_SUITE_P(IRPrinterTest, IRPrinterTest, testing::Values(ToStringVariant::kToString, ToStringVariant::kToStringOstream, ToStringVariant::kOperator)); TEST_P(IRPrinterTest, PrettyPrintsModuleWithProperIndentation) { EXPECT_EQ(ToString(global_module()), R"(module m0 { block b0 { %0 = core.plus []() } // block b0 block b1 { } // block b1 } // module m0 )"); } TEST_P(IRPrinterTest, PrettyPrintsBlockWithProperIndentation) { EXPECT_EQ(ToString(block()), R"(block b0 { %0 = core.plus []() } // block b0 )"); } TEST_P(IRPrinterTest, PrettyPrintsOperationWithProperIndentation) { Operation operation(nullptr, plus_op(), {}, {}, std::make_unique<Module>()); EXPECT_EQ(ToString(operation), R"(%0 = core.plus []() { module m0 { } // module m0 } )"); } TEST_P(IRPrinterTest, PrettyPrintAttributesAndArgsInSortedOrder) { Operation operation( nullptr, minus_op(), {{"access", StringAttribute::Create("private")}, {"name", StringAttribute::Create("addition")}}, {{"const", Value(value::Any())}, {"arg", Value(value::Any())}}); EXPECT_EQ(ToString(operation), "%0 = core.minus [access: private, name: addition](arg: <<ANY>>, " "const: <<ANY>>)\n"); } } // namespace } // namespace raksha::ir
31.126984
79
0.63794
Cypher1
f053f6e90c761647c48770c12ec88db3da347152
2,526
cpp
C++
old_src/example_server/imageplot.cpp
InsightCenterNoodles/NoodlesPlusPlus
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
[ "MIT" ]
null
null
null
old_src/example_server/imageplot.cpp
InsightCenterNoodles/NoodlesPlusPlus
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
[ "MIT" ]
null
null
null
old_src/example_server/imageplot.cpp
InsightCenterNoodles/NoodlesPlusPlus
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
[ "MIT" ]
null
null
null
#include "imageplot.h" #include "plotty.h" void ImagePlot::rebuild(Domain const& d) { auto center = (m_top_left + m_bottom_right) / 2.0f; auto o = -(m_bottom_left - center); if (!m_image_texture) { m_image_texture = noo::create_texture_from_file(m_doc, m_image_data); } if (!m_image_mat) { noo::MaterialData mat; mat.color = { 1, 1, 1, 1 }; mat.metallic = 0; mat.roughness = 1; mat.texture = m_image_texture; m_image_mat = noo::create_material(m_doc, mat); } noo::MeshTPtr mesh; { // create a plane std::array<glm::vec3, 4> positions = { m_top_left, m_bottom_left, m_bottom_right, o }; for (auto& p : positions) { p = d.transform(p); } std::array<glm::vec3, 4> normals; for (auto& n : normals) { n = glm::cross(m_top_left - m_bottom_left, m_bottom_right - m_bottom_left); n = glm::normalize(n); } std::array<glm::u16vec3, 2> index = { glm::u16vec3 { 0, 1, 2 }, glm::u16vec3 { 3, 1, 2 }, }; noo::BufferMeshDataRef ref; ref.positions = positions; ref.normals = normals; ref.triangles = index; std::vector<std::byte> mesh_data; auto result = noo::pack_mesh_to_vector(ref, mesh_data); noo::BufferCopySource buffer_data; buffer_data.to_copy = mesh_data; auto buffer_ptr = noo::create_buffer(m_doc, buffer_data); noo::MeshData noo_mesh_data(result, buffer_ptr); mesh = create_mesh(m_doc, noo_mesh_data); } noo::ObjectData object_data; object_data.material = m_image_mat; object_data.transform = glm::mat4(1); object_data.mesh = mesh; m_obj = create_object(m_doc, object_data); } ImagePlot::ImagePlot(Plotty& host, int64_t id, std::vector<std::byte> image_data, glm::vec3 top_left, glm::vec3 bottom_left, glm::vec3 bottom_right) : Plot(host, id), m_image_data(std::move(image_data)), m_top_left(top_left), m_bottom_left(bottom_left), m_bottom_right(bottom_right) { rebuild(host.domain()->current_domain()); } ImagePlot::~ImagePlot() { } void ImagePlot::domain_updated(Domain const& d) { rebuild(d); }
25.515152
77
0.548694
InsightCenterNoodles
f0583e8c44290a1c1ed21be5fe6bf2c22121ca16
11,068
hpp
C++
shift/core/public/shift/core/ring_buffer.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
2
2018-11-28T18:14:08.000Z
2020-08-06T07:44:36.000Z
shift/core/public/shift/core/ring_buffer.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
4
2018-11-06T21:01:05.000Z
2019-02-19T07:52:52.000Z
shift/core/public/shift/core/ring_buffer.hpp
cspanier/shift
5b3b9be310155fbc57d165d06259b723a5728828
[ "Apache-2.0" ]
null
null
null
#ifndef SHIFT_CORE_RINGBUFFER_HPP #define SHIFT_CORE_RINGBUFFER_HPP #include <utility> #include <algorithm> #include <cstring> #include <shift/core/boost_disable_warnings.hpp> #include <boost/call_traits.hpp> #include <shift/core/boost_restore_warnings.hpp> namespace shift::core { /// A ring buffer using a single linear memory buffer to store elements of /// various type. /// @remarks /// The buffer is organized into up to two regions of memory which are /// marked using the begin and end member pointers. Use of these is as /// follows (b1 = _begin1, e1 = _end1, b2 = _begin2, e2 = _end2): /// Case 1) Buffer is empty: /// | | | | | | | | | | | /// ^b1=e1=e2 ^b2 /// Case 2) Buffer is full: /// |a|b|c|d|e|f|g|h|i|j| /// ^b1=e2 ^e1=b2 /// Case 3) Data is split into two blocks: /// |e|f|g| | | |a|b|c|d| /// ^b2 ^e2 ^b1 ^e1 /// Case 4) Free space is split into two blocks: /// | | |a|b|c|d|e|f| | | /// ^e2 ^b1 ^e1 ^b2 template <typename T> class ring_buffer { public: using buffer_range_t = std::pair<T*, std::size_t>; using const_buffer_range_t = std::pair<const T*, std::size_t>; /// Constructor. ring_buffer(std::size_t capacity = 4096); /// Destructor. ~ring_buffer(); /// Returns the size in bytes of the data currently being stored. std::size_t size() const; /// Returns the size in bytes of the internal memory buffer. std::size_t capacity() const; /// Attempts to write a block of data to the ring buffer. If there is not /// enough free space the method will write as much as possible. /// @param buffer /// A pointer to the memory to be written. If this is null then no data /// is actually written (see ring_buffer::produce). /// @param size /// The number of elements in the data block to write to the ring buffer. /// @param allow_partial /// When set to true attampts to write more elements than free space is /// available will instruct the method to write as many elements as /// possible to the ring buffer. Otherwise these calls will return without /// writing any data. /// @return /// The number of elements that have been written to the ring buffer. std::size_t write(const T* buffer, std::size_t size, bool allow_partial = false); /// Templated version of ring_buffer::write. template <typename U> inline std::size_t write(typename boost::call_traits<U>::param_type value, bool allow_partial = false); /// Attempts to read a number of elements from the ring buffer. /// @param buffer /// The memory location to write the elements to. If this parameter is /// null the method will not copy any elements (see ring_buffer::consume). /// If this parameter is not null it must be large enough to store at /// least size elements. /// @param size /// The number of elements to read from the ring buffer. /// @param allow_partial /// When set to true attempts to read more elements than are available /// instruct the method to read all available data. Otherwise these /// calls will return without reading any data. /// @return /// The number of elements that have been read from the ring buffer. std::size_t read(T* buffer, std::size_t size, bool allow_partial = false); /// Templated version of ring_buffer::read. template <typename U> inline std::size_t read(typename boost::call_traits<U>::reference value, bool allow_partial = false); /// Produces data without modifying the internal buffer. This is useful /// after directly writing to the buffer using spare_array*. /// @param size /// The number of elements to produce. /// @param allow_partial /// If there is not enough space in the ring buffer and this parameter is /// set to true then this call will write as many elements until the ring /// buffer is full. If this parameter is false attempts to write too many /// elements will be ignored. /// @return /// The number of elements successfully produced. std::size_t produce(std::size_t size, bool allow_partial = false); /// Consumes data without actually reading from the buffer. This is useful /// after directly reading from the buffer using data_array*. /// @param size /// The number of elements to consume from the ring buffer. /// @param allow_partial /// When set to true attempts to read more elements than are available /// will be performed partially. Otherwise these attempts will result in /// no elements being read from the ring buffer. /// @return /// The number of elements successfully consumed. std::size_t consume(std::size_t size, bool allow_partial = false); /// Returns a description of the memory region containing the first block /// of data. If there is none the size of the region will be zero and the /// pointer will be unspecified. buffer_range_t data_array1(); /// @see ring_buffer::data_array1. const_buffer_range_t data_array1() const; /// Returns a description of the memory region containing the second block /// of data. If there is none the size of the region will be zero and the /// pointer will be unspecified. buffer_range_t data_array2(); /// @see ring_buffer::data_array2. const_buffer_range_t data_array2() const; /// Returns a description of the free memory region behind the first block /// of data. If there is none the size of the region will be zero and the /// pointer will be unspecified. buffer_range_t spare_array1(); /// @see ring_buffer::spare_array1. const_buffer_range_t spare_array1() const; /// Returns a description of the free memory region behind the second block /// of data. If there is none the size of the region will be zero and the /// pointer will be unspecified. buffer_range_t spare_array2(); /// @see ring_buffer::spare_array2. const_buffer_range_t spare_array2() const; private: T* _data = nullptr; std::size_t _capacity; std::size_t _size = 0; T* _begin1 = nullptr; T* _end1 = nullptr; T* _begin2 = nullptr; T* _end2 = nullptr; }; template <typename T> ring_buffer<T>::ring_buffer(std::size_t capacity) : _capacity(capacity) { _data = new T[_capacity]; _begin1 = &_data[0]; _end1 = &_data[0]; _begin2 = &_data[_capacity]; _end2 = &_data[0]; } template <typename T> ring_buffer<T>::~ring_buffer() { delete _data; } template <typename T> std::size_t ring_buffer<T>::size() const { return _size; } template <typename T> std::size_t ring_buffer<T>::capacity() const { return _capacity; } template <typename T> std::size_t ring_buffer<T>::write(const T* buffer, std::size_t size, bool allow_partial) { std::size_t free = _capacity - _size; if (size == 0 || free == 0) return 0; if (size > free) { if (!allow_partial) return 0; size = free; } if (_begin2 > _end1) { // There is free space behind the first data block. std::size_t size_block1 = _begin2 - _end1; if (size_block1 > size) { if (buffer) memcpy(_end1, buffer, size); _end1 += size; _size += size; } else { std::size_t size_block2 = size - size_block1; if (buffer) memcpy(_end1, buffer, size_block1); _end1 = _begin2; // There is not enough space behind data block one, so start the second // one. _begin2 = _data; if (buffer) memcpy(_begin2, buffer + size_block1, size_block2); _end2 = _begin2 + size_block2; _size += size; } } else { if (buffer) memcpy(_end2, buffer, size); _end2 += size; _size += size; } return size; } template <typename T> template <typename U> inline std::size_t ring_buffer<T>::write( typename boost::call_traits<U>::param_type value, bool allow_partial) { return write(reinterpret_cast<const T*>(&value), sizeof(U) / sizeof(T), allow_partial); } template <typename T> std::size_t ring_buffer<T>::read(T* buffer, std::size_t size, bool allow_partial) { if (size == 0 || _size == 0) return 0; if (size > _size) { if (!allow_partial) return 0; size = _size; } std::size_t size_block1 = _end1 - _begin1; if (size_block1 > size) { if (buffer) memcpy(buffer, _begin1, size); _begin1 += size; _size -= size; } else { if (buffer) { memcpy(buffer, _begin1, size_block1); if (size_block1 < size) memcpy(buffer + size_block1, _data, size - size_block1); } if (_size > size) { _begin1 = _begin2 + (size - size_block1); _end1 = _end2; _size -= size; } else { // Ringbuffer is empty now, so completely reset it. _begin1 = _data; _end1 = _data; _size = 0; } _begin2 = _data + _capacity; _end2 = _begin2; } return size; } template <typename T> template <typename U> inline std::size_t ring_buffer<T>::read( typename boost::call_traits<U>::reference value, bool allow_partial) { return read(reinterpret_cast<T*>(&value), sizeof(U) / sizeof(T), allow_partial); } template <typename T> std::size_t ring_buffer<T>::produce(std::size_t size, bool allow_partial) { return write(nullptr, size, allow_partial); } template <typename T> std::size_t ring_buffer<T>::consume(std::size_t size, bool allow_partial) { return read(nullptr, size, allow_partial); } template <typename T> typename ring_buffer<T>::buffer_range_t ring_buffer<T>::data_array1() { return buffer_range_t(_begin1, _end1 - _begin1); } template <typename T> typename ring_buffer<T>::const_buffer_range_t ring_buffer<T>::data_array1() const { return const_buffer_range_t(_begin1, _end1 - _begin1); } template <typename T> typename ring_buffer<T>::buffer_range_t ring_buffer<T>::data_array2() { return buffer_range_t(_begin2, std::max<std::ptrdiff_t>(_end2 - _begin2, 0)); } template <typename T> typename ring_buffer<T>::const_buffer_range_t ring_buffer<T>::data_array2() const { return const_buffer_range_t(_begin2, std::max<std::ptrdiff_t>(_end2 - _begin2, 0)); } template <typename T> typename ring_buffer<T>::buffer_range_t ring_buffer<T>::spare_array1() { return buffer_range_t(_end1, std::max<std::ptrdiff_t>(_begin2 - _end1, 0)); } template <typename T> typename ring_buffer<T>::const_buffer_range_t ring_buffer<T>::spare_array1() const { return const_buffer_range_t(_end1, std::max<std::ptrdiff_t>(_begin2 - _end1, 0)); } template <typename T> typename ring_buffer<T>::buffer_range_t ring_buffer<T>::spare_array2() { return buffer_range_t(_end2, std::max<std::ptrdiff_t>(_begin1 - _end2, 0)); } template <typename T> typename ring_buffer<T>::const_buffer_range_t ring_buffer<T>::spare_array2() const { return const_buffer_range_t(_end2, std::max<std::ptrdiff_t>(_begin1 - _end2, 0)); } } #endif
29.752688
79
0.663896
cspanier
f05c7289ea1481eaad964d4db7cdafb1cd8c0b55
3,878
cpp
C++
NOV18B/PRITREE.cpp
Chhekur/codechef-solutions
14ca902ea693139de13ffe5b9f602447bf34b79f
[ "MIT" ]
1
2019-03-25T14:14:47.000Z
2019-03-25T14:14:47.000Z
NOV18B/PRITREE.cpp
Chhekur/codechef-solutions
14ca902ea693139de13ffe5b9f602447bf34b79f
[ "MIT" ]
null
null
null
NOV18B/PRITREE.cpp
Chhekur/codechef-solutions
14ca902ea693139de13ffe5b9f602447bf34b79f
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> #include<utility> #include<cstdlib> #include<set> #include<stack> using namespace std; vector<pair<int, int> > edges; vector<pair<int, int> > graph; vector<vector<int> > temp_graph; int a[1001]; bool isPrime(int num){ int f = 0; for(int i = 2; i * i <= num; i++){ if(num % i == 0) f = 1; } if(!f)return true; else return false; } // void genTree(int n){ // edges.clear(); // graph.clear(); // set< pair<int,int> >::iterator it; // while(edges.size() < n - 1){ // int x = ( rand() % ( n ) ); // int y = ( rand() % ( n ) ); // // cout<<x<<" "<<y<<"\n"; // // break; // int f = 0; // for(it=edges.begin(); it!=edges.end(); ++it){ // if(it->first == y && it->second == x)f = 1; // } // if(x == y) f = 1; // if(!f) edges.insert(make_pair(x , y)); // // i++; // } // for(it=edges.begin(); it!=edges.end(); ++it){ // graph.push_back(make_pair(it->first + 1, it->second + 1)); // // cout<<it->first<<" "<<it->second<<"\n"; // } // } void print_edges(){ for(int i = 0; i < edges.size(); i++){ cout<<edges[i].first + 1<<" "<<edges[i].second + 1<<"\n"; } } int main(void){ int n;cin>>n; vector<int> prime_index; vector<int> numbers; int index = -1; for(int i = 0; i < n; i++){ cin>>a[i]; // if(a[i] == 2) index = i + 1; // int f = 0; // for(int j = 2; j * j <= a[i]; j++){ // if(a[i] % j == 0) f = 1; // } // if(!f)prime_index.push_back(i + 1); // else numbers.push_back(i + 1); } // if(n == 2) cout<<"1 2\n"; // else{ for(int i = 0; i < n; i++){ if(a[i] != 0){ for(int j = i + 1; j < n; j++){ if(a[j] != 0){ if(isPrime(a[i] + a[j])){ edges.push_back(make_pair(i,j)); a[i] = 0; a[j] = 0; break; } } } } } // print_edges(); if(edges.size() == 0){ int f = 0, ind; for(int i = 0; i < n; i++){ if(isPrime(a[i])) { f = 1; ind = i; break; } } if(f){ for(int i = 0; i < n; i++){ if(ind + 1 == i + 1) continue; cout<<ind + 1<<" "<<i + 1<<"\n"; } }else{ for(int i = 0; i < n - 1; i++){ edges.push_back(make_pair(i,i + 1)); } print_edges(); } } else{ vector <int> temp; for(int i = 0; i < n; i++){ if(a[i] == 0) continue; // cout<<a[i]<<" "<<i<<"\n"; temp.push_back(i); } int size = edges.size(); if(temp.size() > 0){ for(int j = 0; j < size; j++){ if(j % 2 == 0) // cout<<temp[j]<<" "; edges.push_back(make_pair(temp[temp.size()/2],edges[j].first)); else edges.push_back(make_pair(temp[temp.size() / 2],edges[j].second)); } for(int j = 0; j < temp.size() - 1; j++){ edges.push_back(make_pair(temp[j],temp[j + 1])); } } else{ int size = edges.size(); for(int i = 0; i < size - 1; i++){ edges.push_back(make_pair(edges[i].first, edges[i + 1].second)); } } print_edges(); } // } // int z = 10; // int tree_count = 0; // vector<pair<int, int> > ans; // while(z--){ // genTree(n); // int count = 0; // for(int i = 0; i < graph.size(); i++){ // // cout<<graph[i].first<<" "<<graph[i].second<<"\n"; // set<int> temp; // temp.insert(graph[i].second); // for(int j = 0; j < graph.size(); j++){ // if(i == j)continue; // temp.insert(graph[j].first); // temp.insert(graph[j].second); // } // set<int>::iterator it; // long val = 0; // for(it = temp.begin(); it != temp.end(); it++){ // // cout<<*it<<" "; // val += *it; // } // // cout<<"\n"; // if(isPrime(graph[i].first))count++; // if(isPrime(val))count++; // } // if(count > tree_count){ // // cout<<count<<" "<<tree_count<<"\n"; // tree_count = count; // ans = graph; // } // } // for(int i = 0; i < ans.size(); i++){ // cout<<ans[i].first<<" "<<ans[i].second<<"\n"; // } }
22.287356
72
0.465446
Chhekur
f05d7aafd52938ad7b393f36679dfc15e8292de4
22,731
cpp
C++
unittests/utils/FileCheckTest.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
unittests/utils/FileCheckTest.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
unittests/utils/FileCheckTest.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
//===- llvm/unittest/Support/FileCheckTest.cpp - FileCheck tests --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "FileChecker.h" #include "gtest/gtest.h" #include <unordered_set> using namespace polar::basic; using namespace polar::filechecker; using namespace polar::utils; namespace { class FileCheckTest : public ::testing::Test {}; TEST_F(FileCheckTest, testLiteral) { // Eval returns the literal's value. FileCheckExpressionLiteral ten(10); Expected<uint64_t> value = ten.eval(); EXPECT_TRUE(bool(value)); EXPECT_EQ(10U, *value); // max value can be correctly represented. FileCheckExpressionLiteral max(std::numeric_limits<uint64_t>::max()); value = max.eval(); EXPECT_TRUE(bool(value)); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), *value); } static std::string toString(const std::unordered_set<std::string> &Set) { bool First = true; std::string Str; for (StringRef S : Set) { Str += Twine(First ? "{" + S : ", " + S).getStr(); First = false; } Str += '}'; return Str; } static void expectUndefErrors(std::unordered_set<std::string> ExpectedUndefVarNames, Error Err) { handle_all_errors(std::move(Err), [&](const FileCheckUndefVarError &E) { ExpectedUndefVarNames.erase(E.getVarName()); }); EXPECT_TRUE(ExpectedUndefVarNames.empty()) << toString(ExpectedUndefVarNames); } static void expectUndefError(const Twine &ExpectedUndefVarName, Error Err) { expectUndefErrors({ExpectedUndefVarName.getStr()}, std::move(Err)); } TEST_F(FileCheckTest, testNumericVariable) { // Undefined variable: getValue and eval fail, error returned by eval holds // the name of the undefined variable and setValue does not trigger assert. FileCheckNumericVariable fooVar = FileCheckNumericVariable("FOO", 1); EXPECT_EQ("FOO", fooVar.getName()); FileCheckNumericVariableUse fooVarUse = FileCheckNumericVariableUse("FOO", &fooVar); EXPECT_FALSE(fooVar.getValue()); Expected<uint64_t> evalResult = fooVarUse.eval(); EXPECT_FALSE(evalResult); expectUndefError("FOO", evalResult.takeError()); fooVar.setValue(42); // Defined variable: getValue and eval return value set. std::optional<uint64_t> value = fooVar.getValue(); EXPECT_TRUE(bool(value)); EXPECT_EQ(42U, *value); evalResult = fooVarUse.eval(); EXPECT_TRUE(bool(evalResult)); EXPECT_EQ(42U, *evalResult); // Clearing variable: getValue and eval fail. Error returned by eval holds // the name of the cleared variable. fooVar.clearValue(); value = fooVar.getValue(); EXPECT_FALSE(value); evalResult = fooVarUse.eval(); EXPECT_FALSE(evalResult); expectUndefError("FOO", evalResult.takeError()); } uint64_t doAdd(uint64_t OpL, uint64_t OpR) { return OpL + OpR; } TEST_F(FileCheckTest, testBinop) { FileCheckNumericVariable fooVar = FileCheckNumericVariable("FOO"); fooVar.setValue(42); std::unique_ptr<FileCheckNumericVariableUse> fooVarUse = std::make_unique<FileCheckNumericVariableUse>("FOO", &fooVar); FileCheckNumericVariable barVar = FileCheckNumericVariable("BAR"); barVar.setValue(18); std::unique_ptr<FileCheckNumericVariableUse> BarVarUse = std::make_unique<FileCheckNumericVariableUse>("BAR", &barVar); FileCheckASTBinop Binop = FileCheckASTBinop(doAdd, std::move(fooVarUse), std::move(BarVarUse)); // Defined variable: eval returns right value. Expected<uint64_t> value = Binop.eval(); EXPECT_TRUE(bool(value)); EXPECT_EQ(60U, *value); // 1 undefined variable: eval fails, error contains name of undefined // variable. fooVar.clearValue(); value = Binop.eval(); EXPECT_FALSE(value); expectUndefError("FOO", value.takeError()); // 2 undefined variables: eval fails, error contains names of all undefined // variables. barVar.clearValue(); value = Binop.eval(); EXPECT_FALSE(value); expectUndefErrors({"FOO", "BAR"}, value.takeError()); } TEST_F(FileCheckTest, testValidVarNameStart) { EXPECT_TRUE(FileCheckPattern::isValidVarNameStart('a')); EXPECT_TRUE(FileCheckPattern::isValidVarNameStart('G')); EXPECT_TRUE(FileCheckPattern::isValidVarNameStart('_')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('2')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('$')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('@')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('+')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('-')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart(':')); } static StringRef bufferize(SourceMgr &SM, StringRef Str) { std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBufferCopy(Str, "TestBuffer"); StringRef StrBufferRef = Buffer->getBuffer(); SM.addNewSourceBuffer(std::move(Buffer), SMLocation()); return StrBufferRef; } TEST_F(FileCheckTest, testParseVar) { SourceMgr SM; StringRef OrigVarName = bufferize(SM, "GoodVar42"); StringRef varName = OrigVarName; Expected<FileCheckPattern::VariableProperties> parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(parsedVarResult->name, OrigVarName); EXPECT_TRUE(varName.empty()); EXPECT_FALSE(parsedVarResult->isPseudo); varName = OrigVarName = bufferize(SM, "$GoodGlobalVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(parsedVarResult->name, OrigVarName); EXPECT_TRUE(varName.empty()); EXPECT_FALSE(parsedVarResult->isPseudo); varName = OrigVarName = bufferize(SM, "@GoodPseudoVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(parsedVarResult->name, OrigVarName); EXPECT_TRUE(varName.empty()); EXPECT_TRUE(parsedVarResult->isPseudo); varName = bufferize(SM, "42BadVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(error_to_bool(parsedVarResult.takeError())); varName = bufferize(SM, "$@"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(error_to_bool(parsedVarResult.takeError())); varName = OrigVarName = bufferize(SM, "B@dVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, OrigVarName.substr(1)); EXPECT_EQ(parsedVarResult->name, "B"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = OrigVarName = bufferize(SM, "B$dVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, OrigVarName.substr(1)); EXPECT_EQ(parsedVarResult->name, "B"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = bufferize(SM, "BadVar+"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, "+"); EXPECT_EQ(parsedVarResult->name, "BadVar"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = bufferize(SM, "BadVar-"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, "-"); EXPECT_EQ(parsedVarResult->name, "BadVar"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = bufferize(SM, "BadVar:"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, ":"); EXPECT_EQ(parsedVarResult->name, "BadVar"); EXPECT_FALSE(parsedVarResult->isPseudo); } class PatternTester { private: size_t LineNumber = 1; SourceMgr SM; FileCheckRequest Req; FileCheckPatternContext Context; FileCheckPattern P = FileCheckPattern(check::CheckPlain, &Context, LineNumber++); public: PatternTester() { std::vector<std::string> globalDefines; globalDefines.emplace_back(std::string("#FOO=42")); globalDefines.emplace_back(std::string("BAR=BAZ")); EXPECT_FALSE( error_to_bool(Context.defineCmdlineVariables(globalDefines, SM))); Context.createLineVariable(); // Call parsePattern to have @LINE defined. P.parsePattern("N/A", "CHECK", SM, Req); // parsePattern does not expect to be called twice for the same line and // will set FixedStr and RegExStr incorrectly if it is. Therefore prepare // a pattern for a different line. initNextPattern(); } void initNextPattern() { P = FileCheckPattern(check::CheckPlain, &Context, LineNumber++); } bool parseNumVarDefExpect(StringRef Expr) { StringRef ExprBufferRef = bufferize(SM, Expr); return error_to_bool(FileCheckPattern::parseNumericVariableDefinition( ExprBufferRef, &Context, LineNumber, SM) .takeError()); } bool parseSubstExpect(StringRef Expr) { StringRef ExprBufferRef = bufferize(SM, Expr); std::optional<FileCheckNumericVariable *> DefinedNumericVariable; return error_to_bool(P.parseNumericSubstitutionBlock( ExprBufferRef, DefinedNumericVariable, false, SM) .takeError()); } bool parsePatternExpect(StringRef Pattern) { StringRef PatBufferRef = bufferize(SM, Pattern); return P.parsePattern(PatBufferRef, "CHECK", SM, Req); } bool matchExpect(StringRef Buffer) { StringRef BufferRef = bufferize(SM, Buffer); size_t MatchLen; return error_to_bool(P.match(BufferRef, MatchLen, SM).takeError()); } }; TEST_F(FileCheckTest, testParseNumericVariableDefinition) { PatternTester tester; // Invalid definition of pseudo. EXPECT_TRUE(tester.parseNumVarDefExpect("@LINE")); // Conflict with pattern variable. EXPECT_TRUE(tester.parseNumVarDefExpect("BAR")); // Defined variable. EXPECT_FALSE(tester.parseNumVarDefExpect("FOO")); } TEST_F(FileCheckTest, testParseExpr) { PatternTester tester; // Variable definition. // Definition of invalid variable. EXPECT_TRUE(tester.parseSubstExpect("10VAR:")); EXPECT_TRUE(tester.parseSubstExpect("@FOO:")); EXPECT_TRUE(tester.parseSubstExpect("@LINE:")); // Garbage after name of variable being defined. EXPECT_TRUE(tester.parseSubstExpect("VAR GARBAGE:")); // Variable defined to numeric expression. EXPECT_TRUE(tester.parseSubstExpect("VAR1: FOO")); // Acceptable variable definition. EXPECT_FALSE(tester.parseSubstExpect("VAR1:")); EXPECT_FALSE(tester.parseSubstExpect(" VAR2:")); EXPECT_FALSE(tester.parseSubstExpect("VAR3 :")); EXPECT_FALSE(tester.parseSubstExpect("VAR3: ")); // Numeric expression. // Unacceptable variable. EXPECT_TRUE(tester.parseSubstExpect("10VAR")); EXPECT_TRUE(tester.parseSubstExpect("@FOO")); // Only valid variable. EXPECT_FALSE(tester.parseSubstExpect("@LINE")); EXPECT_FALSE(tester.parseSubstExpect("FOO")); EXPECT_FALSE(tester.parseSubstExpect("UNDEF")); // Use variable defined on same line. EXPECT_FALSE(tester.parsePatternExpect("[[#LINE1VAR:]]")); EXPECT_TRUE(tester.parseSubstExpect("LINE1VAR")); // Unsupported operator. EXPECT_TRUE(tester.parseSubstExpect("@LINE/2")); // Missing offset operand. EXPECT_TRUE(tester.parseSubstExpect("@LINE+")); // Valid expression. EXPECT_FALSE(tester.parseSubstExpect("@LINE+5")); EXPECT_FALSE(tester.parseSubstExpect("FOO+4")); tester.initNextPattern(); EXPECT_FALSE(tester.parsePatternExpect("[[#FOO+FOO]]")); EXPECT_FALSE(tester.parsePatternExpect("[[#FOO+3-FOO]]")); } TEST_F(FileCheckTest, testParsePattern) { PatternTester tester; // Space in pattern variable expression. EXPECT_TRUE(tester.parsePatternExpect("[[ BAR]]")); // Invalid variable name. EXPECT_TRUE(tester.parsePatternExpect("[[42INVALID]]")); // Invalid pattern variable definition. EXPECT_TRUE(tester.parsePatternExpect("[[@PAT:]]")); EXPECT_TRUE(tester.parsePatternExpect("[[PAT+2:]]")); // Collision with numeric variable. EXPECT_TRUE(tester.parsePatternExpect("[[FOO:]]")); // Valid use of pattern variable. EXPECT_FALSE(tester.parsePatternExpect("[[BAR]]")); // Valid pattern variable definition. EXPECT_FALSE(tester.parsePatternExpect("[[PAT:[0-9]+]]")); // Invalid numeric expressions. EXPECT_TRUE(tester.parsePatternExpect("[[#42INVALID]]")); EXPECT_TRUE(tester.parsePatternExpect("[[#@FOO]]")); EXPECT_TRUE(tester.parsePatternExpect("[[#@LINE/2]]")); EXPECT_TRUE(tester.parsePatternExpect("[[#YUP:@LINE]]")); // Valid numeric expressions and numeric variable definition. EXPECT_FALSE(tester.parsePatternExpect("[[#FOO]]")); EXPECT_FALSE(tester.parsePatternExpect("[[#@LINE+2]]")); EXPECT_FALSE(tester.parsePatternExpect("[[#NUMVAR:]]")); } TEST_F(FileCheckTest, testMatch) { PatternTester tester; // Check matching a definition only matches a number. tester.parsePatternExpect("[[#NUMVAR:]]"); EXPECT_TRUE(tester.matchExpect("FAIL")); EXPECT_FALSE(tester.matchExpect("18")); // Check matching the variable defined matches the correct number only tester.initNextPattern(); tester.parsePatternExpect("[[#NUMVAR]] [[#NUMVAR+2]]"); EXPECT_TRUE(tester.matchExpect("19 21")); EXPECT_TRUE(tester.matchExpect("18 21")); EXPECT_FALSE(tester.matchExpect("18 20")); // Check matching a numeric expression using @LINE after match failure uses // the correct value for @LINE. tester.initNextPattern(); EXPECT_FALSE(tester.parsePatternExpect("[[#@LINE]]")); // Ok, @LINE is 4 now. EXPECT_FALSE(tester.matchExpect("4")); tester.initNextPattern(); // @LINE is now 5, match with substitution failure. EXPECT_FALSE(tester.parsePatternExpect("[[#UNKNOWN]]")); EXPECT_TRUE(tester.matchExpect("FOO")); tester.initNextPattern(); // Check that @LINE is 6 as expected. EXPECT_FALSE(tester.parsePatternExpect("[[#@LINE]]")); EXPECT_FALSE(tester.matchExpect("6")); } TEST_F(FileCheckTest, testSubstitution) { SourceMgr SM; FileCheckPatternContext Context; std::vector<std::string> globalDefines; globalDefines.emplace_back(std::string("FOO=BAR")); EXPECT_FALSE(error_to_bool(Context.defineCmdlineVariables(globalDefines, SM))); // Substitution of an undefined string variable fails and error holds that // variable's name. FileCheckStringSubstitution StringSubstitution = FileCheckStringSubstitution(&Context, "VAR404", 42); Expected<std::string> SubstValue = StringSubstitution.getResult(); EXPECT_FALSE(bool(SubstValue)); expectUndefError("VAR404", SubstValue.takeError()); // Substitutions of defined pseudo and non-pseudo numeric variables return // the right value. FileCheckNumericVariable LineVar = FileCheckNumericVariable("@LINE"); LineVar.setValue(42); FileCheckNumericVariable nvar = FileCheckNumericVariable("N"); nvar.setValue(10); auto LineVarUse = std::make_unique<FileCheckNumericVariableUse>("@LINE", &LineVar); auto NVarUse = std::make_unique<FileCheckNumericVariableUse>("N", &nvar); FileCheckNumericSubstitution SubstitutionLine = FileCheckNumericSubstitution( &Context, "@LINE", std::move(LineVarUse), 12); FileCheckNumericSubstitution SubstitutionN = FileCheckNumericSubstitution(&Context, "N", std::move(NVarUse), 30); SubstValue = SubstitutionLine.getResult(); EXPECT_TRUE(bool(SubstValue)); EXPECT_EQ("42", *SubstValue); SubstValue = SubstitutionN.getResult(); EXPECT_TRUE(bool(SubstValue)); EXPECT_EQ("10", *SubstValue); // Substitution of an undefined numeric variable fails, error holds name of // undefined variable. LineVar.clearValue(); SubstValue = SubstitutionLine.getResult(); EXPECT_FALSE(bool(SubstValue)); expectUndefError("@LINE", SubstValue.takeError()); nvar.clearValue(); SubstValue = SubstitutionN.getResult(); EXPECT_FALSE(bool(SubstValue)); expectUndefError("N", SubstValue.takeError()); // Substitution of a defined string variable returns the right value. FileCheckPattern P = FileCheckPattern(check::CheckPlain, &Context, 1); StringSubstitution = FileCheckStringSubstitution(&Context, "FOO", 42); SubstValue = StringSubstitution.getResult(); EXPECT_TRUE(bool(SubstValue)); EXPECT_EQ("BAR", *SubstValue); } TEST_F(FileCheckTest, testFileCheckContext) { FileCheckPatternContext cxt = FileCheckPatternContext(); std::vector<std::string> globalDefines; SourceMgr SM; // Missing equal sign. globalDefines.emplace_back(std::string("LocalVar")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); globalDefines.clear(); globalDefines.emplace_back(std::string("#LocalNumVar")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Empty variable name. globalDefines.clear(); globalDefines.emplace_back(std::string("=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); globalDefines.clear(); globalDefines.emplace_back(std::string("#=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Invalid variable name. globalDefines.clear(); globalDefines.emplace_back(std::string("18LocalVar=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); globalDefines.clear(); globalDefines.emplace_back(std::string("#18LocalNumVar=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // name conflict between pattern and numeric variable. globalDefines.clear(); globalDefines.emplace_back(std::string("LocalVar=18")); globalDefines.emplace_back(std::string("#LocalVar=36")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); cxt = FileCheckPatternContext(); globalDefines.clear(); globalDefines.emplace_back(std::string("#LocalNumVar=18")); globalDefines.emplace_back(std::string("LocalNumVar=36")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); cxt = FileCheckPatternContext(); // Invalid numeric value for numeric variable. globalDefines.clear(); globalDefines.emplace_back(std::string("#LocalNumVar=x")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Define local variables from command-line. globalDefines.clear(); globalDefines.emplace_back(std::string("LocalVar=FOO")); globalDefines.emplace_back(std::string("emptyVar=")); globalDefines.emplace_back(std::string("#LocalNumVar=18")); EXPECT_FALSE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Check defined variables are present and undefined is absent. StringRef LocalVarStr = "LocalVar"; StringRef LocalNumVarRef = bufferize(SM, "LocalNumVar"); StringRef EmptyVarStr = "emptyVar"; StringRef UnknownVarStr = "UnknownVar"; Expected<StringRef> LocalVar = cxt.getPatternVarValue(LocalVarStr); FileCheckPattern P = FileCheckPattern(check::CheckPlain, &cxt, 1); std::optional<FileCheckNumericVariable *> DefinedNumericVariable; Expected<std::unique_ptr<FileCheckExpressionAST>> expressionAST = P.parseNumericSubstitutionBlock(LocalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(LocalVar)); EXPECT_EQ(*LocalVar, "FOO"); Expected<StringRef> emptyVar = cxt.getPatternVarValue(EmptyVarStr); Expected<StringRef> UnknownVar = cxt.getPatternVarValue(UnknownVarStr); EXPECT_TRUE(bool(expressionAST)); Expected<uint64_t> expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(bool(expressionVal)); EXPECT_EQ(*expressionVal, 18U); EXPECT_TRUE(bool(emptyVar)); EXPECT_EQ(*emptyVar, ""); EXPECT_TRUE(error_to_bool(UnknownVar.takeError())); // Clear local variables and check they become absent. cxt.clearLocalVars(); LocalVar = cxt.getPatternVarValue(LocalVarStr); EXPECT_TRUE(error_to_bool(LocalVar.takeError())); // Check a numeric expression's evaluation fails if called after clearing of // local variables, if it was created before. This is important because local // variable clearing due to --enable-var-scope happens after numeric // expressions are linked to the numeric variables they use. EXPECT_TRUE(error_to_bool((*expressionAST)->eval().takeError())); P = FileCheckPattern(check::CheckPlain, &cxt, 2); expressionAST = P.parseNumericSubstitutionBlock( LocalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(expressionAST)); expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(error_to_bool(expressionVal.takeError())); emptyVar = cxt.getPatternVarValue(EmptyVarStr); EXPECT_TRUE(error_to_bool(emptyVar.takeError())); // Clear again because parseNumericSubstitutionBlock would have created a // dummy variable and stored it in GlobalNumericVariableTable. cxt.clearLocalVars(); // Redefine global variables and check variables are defined again. globalDefines.emplace_back(std::string("$GlobalVar=BAR")); globalDefines.emplace_back(std::string("#$GlobalNumVar=36")); EXPECT_FALSE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); StringRef GlobalVarStr = "$GlobalVar"; StringRef GlobalNumVarRef = bufferize(SM, "$GlobalNumVar"); Expected<StringRef> GlobalVar = cxt.getPatternVarValue(GlobalVarStr); EXPECT_TRUE(bool(GlobalVar)); EXPECT_EQ(*GlobalVar, "BAR"); P = FileCheckPattern(check::CheckPlain, &cxt, 3); expressionAST = P.parseNumericSubstitutionBlock( GlobalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(expressionAST)); expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(bool(expressionVal)); EXPECT_EQ(*expressionVal, 36U); // Clear local variables and check global variables remain defined. cxt.clearLocalVars(); EXPECT_FALSE(error_to_bool(cxt.getPatternVarValue(GlobalVarStr).takeError())); P = FileCheckPattern(check::CheckPlain, &cxt, 4); expressionAST = P.parseNumericSubstitutionBlock( GlobalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(expressionAST)); expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(bool(expressionVal)); EXPECT_EQ(*expressionVal, 36U); } } // namespace
39.259067
85
0.723505
PHP-OPEN-HUB
f05e11c9aa8b06d2cce2ca4aa7b0eb9e2b992d49
5,180
hpp
C++
include/System/Data/DataRowAction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/DataRowAction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/DataRowAction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: System.Data namespace System::Data { // Forward declaring type: DataRowAction struct DataRowAction; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::System::Data::DataRowAction, "System.Data", "DataRowAction"); // Type namespace: System.Data namespace System::Data { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: System.Data.DataRowAction // [TokenAttribute] Offset: FFFFFFFF // [FlagsAttribute] Offset: FFFFFFFF struct DataRowAction/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: DataRowAction constexpr DataRowAction(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public System.Data.DataRowAction Nothing static constexpr const int Nothing = 0; // Get static field: static public System.Data.DataRowAction Nothing static ::System::Data::DataRowAction _get_Nothing(); // Set static field: static public System.Data.DataRowAction Nothing static void _set_Nothing(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Delete static constexpr const int Delete = 1; // Get static field: static public System.Data.DataRowAction Delete static ::System::Data::DataRowAction _get_Delete(); // Set static field: static public System.Data.DataRowAction Delete static void _set_Delete(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Change static constexpr const int Change = 2; // Get static field: static public System.Data.DataRowAction Change static ::System::Data::DataRowAction _get_Change(); // Set static field: static public System.Data.DataRowAction Change static void _set_Change(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Rollback static constexpr const int Rollback = 4; // Get static field: static public System.Data.DataRowAction Rollback static ::System::Data::DataRowAction _get_Rollback(); // Set static field: static public System.Data.DataRowAction Rollback static void _set_Rollback(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Commit static constexpr const int Commit = 8; // Get static field: static public System.Data.DataRowAction Commit static ::System::Data::DataRowAction _get_Commit(); // Set static field: static public System.Data.DataRowAction Commit static void _set_Commit(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Add static constexpr const int Add = 16; // Get static field: static public System.Data.DataRowAction Add static ::System::Data::DataRowAction _get_Add(); // Set static field: static public System.Data.DataRowAction Add static void _set_Add(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction ChangeOriginal static constexpr const int ChangeOriginal = 32; // Get static field: static public System.Data.DataRowAction ChangeOriginal static ::System::Data::DataRowAction _get_ChangeOriginal(); // Set static field: static public System.Data.DataRowAction ChangeOriginal static void _set_ChangeOriginal(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction ChangeCurrentAndOriginal static constexpr const int ChangeCurrentAndOriginal = 64; // Get static field: static public System.Data.DataRowAction ChangeCurrentAndOriginal static ::System::Data::DataRowAction _get_ChangeCurrentAndOriginal(); // Set static field: static public System.Data.DataRowAction ChangeCurrentAndOriginal static void _set_ChangeCurrentAndOriginal(::System::Data::DataRowAction value); // Get instance field reference: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& dyn_value__(); }; // System.Data.DataRowAction #pragma pack(pop) static check_size<sizeof(DataRowAction), 0 + sizeof(int)> __System_Data_DataRowActionSizeCheck; static_assert(sizeof(DataRowAction) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
51.287129
97
0.733398
v0idp
f067bf169df312c8a05d493bf7541d4c1604c824
18,457
cpp
C++
kol_ontology/unit_test/kol_test_GoGraph.cpp
kellerberrin/KGL_Gene
f8e6c14b8b2009d82d692b28354561b5f0513c5e
[ "MIT" ]
1
2021-04-09T16:24:06.000Z
2021-04-09T16:24:06.000Z
kol_ontology/unit_test/kol_test_GoGraph.cpp
kellerberrin/KGL_Gene
f8e6c14b8b2009d82d692b28354561b5f0513c5e
[ "MIT" ]
null
null
null
kol_ontology/unit_test/kol_test_GoGraph.cpp
kellerberrin/KGL_Gene
f8e6c14b8b2009d82d692b28354561b5f0513c5e
[ "MIT" ]
null
null
null
// // Created by kellerberrin on 1/4/21. // #include <kol_library.h> #include "kol_test.h" #include <boost/test/unit_test.hpp> namespace kellerberrin::ontology { // This object is re-created for each test case; store the graph in a static pointer so that it is only created once. class TestGoGraph { public: TestGoGraph() = default; ~TestGoGraph() = default; [[nodiscard]] static const GoGraph &goGraph() { if (not static_graph_) { static_graph_ = getGoGraph(); } // BOOST_REQUIRE(static_graph_); return *static_graph_; } // Utility function. // Convert an OntologySetType (which may be a std::unordered_set<>) into a std::set<> for convenient '==' comparison. template<class T> [[nodiscard]] static std::set<T> convertSet(OntologySetType<T> &&from_set) { if constexpr(std::is_same<std::set<T>, OntologySetType<T>>::value) { return std::set<T>(from_set); } else { std::set<T> plain_set; for (auto &&element : from_set) { plain_set.insert(element); } return plain_set; } } private: [[nodiscard]] static std::shared_ptr<GoGraph> getGoGraph() { auto go_parser_ptr = ParserGoFactory::createGoParser(ParserGoType::PARSER_GO_OBO); BOOST_REQUIRE(go_parser_ptr); return go_parser_ptr->parseGoFile(UnitTestDefinitions::oboFileName()); } inline static std::shared_ptr<const GoGraph> static_graph_; }; } // namespace namespace kol = kellerberrin::ontology; BOOST_FIXTURE_TEST_SUITE(TestGoGraphSuite, kol::TestGoGraph) ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Vertex and Edge count accessors ////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_vertex_count_accessor) { const size_t vertex_count{42718}; if (goGraph().getNumVertices() != vertex_count) BOOST_FAIL("Obo graph vertex count is incorrect" ); BOOST_TEST_MESSAGE( "test_vertex_count_accessor ... OK" ); } BOOST_AUTO_TEST_CASE(test_edge_count_accessor) { const size_t edge_count{81084}; if (goGraph().getNumEdges() != edge_count) BOOST_FAIL("Obo graph edge count is incorrect" ); BOOST_TEST_MESSAGE( "test_edge_count_accessor ... OK" ); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // Term attribute access, Name Description and Ontology type ////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_name_bad_id) { const std::string bad_term("GO:00507"); if (not goGraph().getTermName(bad_term).empty()) BOOST_FAIL( "Bad term found" ); BOOST_TEST_MESSAGE( "test_term_name_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_desc_bad_id) { const std::string bad_term("GO:00507"); if (not goGraph().getTermDescription(bad_term).empty()) BOOST_FAIL( "Bad term description found" ); BOOST_TEST_MESSAGE( "test_term_desc_bad_id ... OK" ); } /////////////////////////////////////////////////////// // Vertex and Edge count accessors ////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_name_BP) { const std::string BP_term("GO:0050789"); const std::string BP_name("regulation of biological process"); if (goGraph().getTermName(BP_term) != BP_name) BOOST_FAIL( "BP term for: " + BP_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_name_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_desc_BP) { const std::string BP_term("GO:0050789"); const std::string part_desc("Any process that modulates the frequency, rate or extent of a biological process"); if (goGraph().getTermDescription(BP_term).find(part_desc) == std::string::npos) BOOST_FAIL( "BP description for: " + BP_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_desc_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_name_MF) { const std::string MF_term("GO:0005385"); const std::string MF_name("zinc ion transmembrane transporter activity"); if (goGraph().getTermName(MF_term) != MF_name) BOOST_FAIL( "MF term for: " + MF_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_name_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_desc_MF) { const std::string MF_term("GO:0005385"); const std::string part_desc("\"Enables the transfer of zinc (Zn) ions from one side of a membrane to the other.\" [GOC:dgf]"); if (goGraph().getTermDescription(MF_term).find(part_desc) == std::string::npos) BOOST_FAIL( "MF description for: " + MF_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_desc_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_name_CC) { const std::string CC_term("GO:0009898"); const std::string CC_name("cytoplasmic side of plasma membrane"); if (goGraph().getTermName(CC_term) != CC_name) BOOST_FAIL( "CC term for: " + CC_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_name_CC ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_desc_CC) { const std::string CC_term("GO:0009898"); const std::string part_desc("\"The leaflet the plasma membrane that faces the cytoplasm and any proteins embedded or anchored in it or attached to its surface.\" [GOC:dos, GOC:tb]"); if (goGraph().getTermDescription(CC_term).find(part_desc) == std::string::npos) BOOST_FAIL( "CC description for: " + CC_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_desc_CC ... OK" ); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Ontology type and code ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_ontology_bad_id) { const std::string bad_term("GO:00098"); if (kol::GO::ontologyToString(goGraph().getTermOntology(bad_term)) != kol::GO::ONTOLOGY_ERROR_TEXT) BOOST_FAIL( "Bad ontology term for: " + bad_term + " found" ); BOOST_TEST_MESSAGE( "test_term_ontology_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_code_bad_id) { const std::string bad_term("GO:00098"); if (goGraph().getTermOntology(bad_term) != kol::GO::Ontology::ONTO_ERROR) BOOST_FAIL( "Bad ontology term for: " + bad_term + " found" ); BOOST_TEST_MESSAGE( "test_term_ontology_code_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_BP) { const std::string BP_term("GO:0022403"); if (kol::GO::ontologyToString(goGraph().getTermOntology(BP_term)) != kol::GO::ONTOLOGY_BIOLOGICAL_PROCESS_TEXT) BOOST_FAIL( "BP ontology term for: " + BP_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_ontology_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_code_BP) { const std::string BP_term("GO:0022403"); if (goGraph().getTermOntology(BP_term) != kol::GO::Ontology::BIOLOGICAL_PROCESS) BOOST_FAIL( "BP ontology term for: " + BP_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_ontology_code_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_MF) { const std::string MF_term("GO:0048037"); if (kol::GO::ontologyToString(goGraph().getTermOntology(MF_term)) != kol::GO::ONTOLOGY_MOLECULAR_FUNCTION_TEXT) BOOST_FAIL( "MF ontology term for: " + MF_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_ontology_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_code_MF) { const std::string MF_term("GO:0048037"); if (goGraph().getTermOntology(MF_term) != kol::GO::Ontology::MOLECULAR_FUNCTION) BOOST_FAIL( "MF ontology term for: " + MF_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_ontology_code_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_CC) { const std::string CC_term("GO:0005911"); if (kol::GO::ontologyToString(goGraph().getTermOntology(CC_term)) != kol::GO::ONTOLOGY_CELLULAR_COMPONENT_TEXT) BOOST_FAIL( "CC ontology term for: " + CC_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_ontology_CC ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ontology_code_CC) { const std::string CC_term("GO:0005911"); if (goGraph().getTermOntology(CC_term) != kol::GO::Ontology::CELLULAR_COMPONENT) BOOST_FAIL( "CC ontology term for: " + CC_term + " not found" ); BOOST_TEST_MESSAGE( "test_term_ontology_code_CC ... OK" ); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Relative accessors, Ancestors, Descendants, Parents, Children ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////// // Ancestors ///////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_ancestors_bad_id) { const std::string Bad_term("GO:00098"); if (not goGraph().getAncestorTerms(Bad_term).empty()) BOOST_FAIL( "Bad ontology term: " + Bad_term + " found ancestors" ); BOOST_TEST_MESSAGE( "test_term_ancestors_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ancestors_BP) { const std::string BP_term("GO:0022403"); const std::set<std::string> ancestors{"GO:0044848", "GO:0008150"}; if (convertSet(goGraph().getAncestorTerms(BP_term)) != ancestors) BOOST_FAIL( "BP term: " + BP_term + " ancestors not found" ); BOOST_TEST_MESSAGE( "test_term_ancestors_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ancestors_MF) { const std::string MF_term("GO:0048037"); const std::set<std::string> ancestors{"GO:0005488", "GO:0003674"}; if (convertSet(goGraph().getAncestorTerms(MF_term)) != ancestors) BOOST_FAIL( "MF term: " + MF_term + " ancestors not found" ); BOOST_TEST_MESSAGE( "test_term_ancestors_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_ancestors_CC) { const std::string CC_term("GO:0005911"); const std::set<std::string> ancestors{"GO:0005575", "GO:0030054"}; if (convertSet(goGraph().getAncestorTerms(CC_term)) != ancestors) BOOST_FAIL( "CC term: " + CC_term + " ancestors not found" ); BOOST_TEST_MESSAGE( "test_term_ancestors_CC ... OK" ); } ///////////////////////////////////////////// // Descendants ///////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_descendants_bad_id) { const std::string Bad_term("GO:00098"); if (not goGraph().getDescendantTerms(Bad_term).empty()) BOOST_FAIL( "Bad ontology term: " + Bad_term + " found descendants" ); BOOST_TEST_MESSAGE( "test_term_descendants_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_terms_with_zero_descendants) { const size_t leaf_terms{23717}; auto const term_set = goGraph().getAllTerms(); size_t leaf_count{0}; for (auto const& term : term_set) { if (goGraph().isLeaf(term)) { ++leaf_count; } } if (leaf_count != leaf_terms) BOOST_FAIL( "Unexpected leaf terms: " + std::to_string(leaf_count) ); BOOST_TEST_MESSAGE( "test_terms_with_zero_descendants ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_descendants_BP) { const std::string BP_term("GO:0051318"); const std::set<std::string> descendants{"GO:0000080", "GO:0051330"}; if (convertSet(goGraph().getDescendantTerms(BP_term)) != descendants) BOOST_FAIL( "BP term: " + BP_term + " descendants not found" ); BOOST_TEST_MESSAGE( "test_term_descendants_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_descendants_MF) { const std::string MF_term("GO:0042165"); const std::set<std::string> descendants{"GO:0031626", "GO:0042166"}; if (convertSet(goGraph().getDescendantTerms(MF_term)) != descendants) BOOST_FAIL( "MF term: " + MF_term + " descendants not found" ); BOOST_TEST_MESSAGE( "test_term_descendants_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_descendants_CC) { const std::string CC_term("GO:0030057"); const std::set<std::string> descendants{"GO:0090635", "GO:0090636", "GO:0090637"}; if (convertSet(goGraph().getDescendantTerms(CC_term)) != descendants) BOOST_FAIL( "CC term: " + CC_term + " descendants not found" ); BOOST_TEST_MESSAGE( "test_term_descendants_CC ... OK" ); } //////////////////////////////////////////////// // Parents, immediate ancestors //////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_parents_bad_id) { const std::string Bad_term("GO:0022"); if (not goGraph().getParentTerms(Bad_term).empty()) BOOST_FAIL( "Bad ontology term: " + Bad_term + " found parents" ); BOOST_TEST_MESSAGE( "test_term_parents_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_parents_BP) { const std::string BP_term("GO:0022403"); const std::set<std::string> parents{"GO:0044848"}; if (convertSet(goGraph().getParentTerms(BP_term)) != parents) BOOST_FAIL( "BP term: " + BP_term + " parents not found" ); BOOST_TEST_MESSAGE( "test_term_parents_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_parents_MF) { const std::string MF_term("GO:0048037"); const std::set<std::string> parents{"GO:0005488"}; if (convertSet(goGraph().getParentTerms(MF_term)) != parents) BOOST_FAIL( "MF term: " + MF_term + " parents not found" ); BOOST_TEST_MESSAGE( "test_term_parents_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_parents_CC) { const std::string CC_term("GO:0005911"); const std::set<std::string> parents{"GO:0030054"}; if (convertSet(goGraph().getParentTerms(CC_term)) != parents) BOOST_FAIL( "CC term: " + CC_term + " parents not found" ); BOOST_TEST_MESSAGE( "test_term_parents_CC ... OK" ); } //////////////////////////////////////////////// // Children, immediate descendants //////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_term_children_bad_id) { const std::string Bad_term("GO:00098"); if (not goGraph().getChildTerms(Bad_term).empty()) BOOST_FAIL( "Bad ontology term: " + Bad_term + " found children" ); BOOST_TEST_MESSAGE( "test_term_children_bad_id ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_children_BP) { const std::string BP_term("GO:0051319"); const std::set<std::string> children{"GO:0051331", "GO:0000085"}; if (convertSet(goGraph().getChildTerms(BP_term)) != children) BOOST_FAIL( "BP term: " + BP_term + " children not found" ); BOOST_TEST_MESSAGE( "test_term_children_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_children_MF) { const std::string MF_term("GO:0001071"); const std::set<std::string> children{"GO:0003700", "GO:0001070"}; if (convertSet(goGraph().getChildTerms(MF_term)) != children) BOOST_FAIL( "MF term: " + MF_term + " children not found" ); BOOST_TEST_MESSAGE( "test_term_children_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_term_children_CC) { const std::string CC_term("GO:0031974"); const std::set<std::string> children{"GO:1904724", "GO:1904813", "GO:0043233", "GO:0031970"}; if (convertSet(goGraph().getChildTerms(CC_term)) != children) BOOST_FAIL( "CC term: " + CC_term + " children not found" ); BOOST_TEST_MESSAGE( "test_term_children_CC ... OK" ); } ///////////////////////////////////////////////////////////////////// // Retrieve terms sets and ontology term sets ///////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_all_terms_accessor) { const size_t term_count = 42718; if (goGraph().getAllTerms().size() != term_count) BOOST_FAIL( "All terms count not equal : " + std::to_string(term_count)); BOOST_TEST_MESSAGE( "test_all_terms_accessor ... OK" ); } BOOST_AUTO_TEST_CASE(test_all_terms_accessor_BP) { const size_t term_count = 28651; if (goGraph().getAllTermsBP().size() != term_count) BOOST_FAIL( "All BP terms count not equal : " + std::to_string(term_count)); BOOST_TEST_MESSAGE( "test_all_terms_accessor_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_all_terms_accessor_MF) { const size_t term_count = 10160; if (goGraph().getAllTermsMF().size() != term_count) BOOST_FAIL( "All MF terms count not equal : " + std::to_string(term_count)); BOOST_TEST_MESSAGE( "test_all_terms_accessor_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_all_terms_accessor_CC) { const size_t term_count = 3907; if (goGraph().getAllTermsCC().size() != term_count) BOOST_FAIL( "All CC terms count not equal : " + std::to_string(term_count)); BOOST_TEST_MESSAGE( "test_all_terms_accessor_CC ... OK" ); } /////////////////////////////////////////////////////////////////////////// // Test filtering functions /////////////////////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_filter_for_BP) { kol::OntologySetType<std::string> unfiltered_list{"GO:0033631", "GO:0033627", "GO:0004099", "GO:0019213", "GO:0044225", "GO:0043025"}; std::set<std::string> filtered_list{"GO:0033631", "GO:0033627"}; if (convertSet(goGraph().filterSetForBP(unfiltered_list)) != filtered_list) BOOST_FAIL( "Filtered terms count not all BP"); BOOST_TEST_MESSAGE( "test_filter_for_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_filter_for_MF) { kol::OntologySetType<std::string> unfiltered_list{"GO:0033631", "GO:0033627", "GO:0004099", "GO:0019213", "GO:0044225", "GO:0043025"}; std::set<std::string> filtered_list{"GO:0004099", "GO:0019213"}; if (convertSet(goGraph().filterSetForMF(unfiltered_list)) != filtered_list) BOOST_FAIL( "Filtered terms count not all MF"); BOOST_TEST_MESSAGE( "test_filter_for_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_filter_for_CC) { kol::OntologySetType<std::string> unfiltered_list{"GO:0033631", "GO:0033627", "GO:0004099", "GO:0019213", "GO:0044225", "GO:0043025"}; std::set<std::string> filtered_list{"GO:0044225", "GO:0043025"}; if (convertSet(goGraph().filterSetForCC(unfiltered_list)) != filtered_list) BOOST_FAIL( "Filtered terms count not all CC"); BOOST_TEST_MESSAGE( "test_filter_for_CC ... OK" ); } /////////////////////////////////////////////////////////// // Test accessors for the root terms of the 3 ontologies ////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(test_root_term_access_BP) { if (goGraph().getTermRoot("GO:0033631") != kol::GO::getRootTermBP()) BOOST_FAIL( "Failed to get root term for BP"); BOOST_TEST_MESSAGE( "test_root_term_access_BP ... OK" ); } BOOST_AUTO_TEST_CASE(test_root_term_access_MF) { if (goGraph().getTermRoot("GO:0019213") != kol::GO::getRootTermMF()) BOOST_FAIL( "Failed to get root term for MF"); BOOST_TEST_MESSAGE( "test_root_term_access_MF ... OK" ); } BOOST_AUTO_TEST_CASE(test_root_term_access_CC) { if (goGraph().getTermRoot("GO:0044225") != kol::GO::getRootTermCC()) BOOST_FAIL( "Failed to get root term for CC"); BOOST_TEST_MESSAGE( "test_root_term_access_CC ... OK" ); } BOOST_AUTO_TEST_SUITE_END()
32.380702
184
0.653627
kellerberrin
f06de431cb9933773c4c4fbea87a43ffd31cbb7c
2,404
cpp
C++
lua100/sources/utils/plugin_loader.cpp
SoulWorkerResearch/swp-loader
00d8ca0d59e0e5a0d279e5d4b5d08850042aa190
[ "WTFPL" ]
1
2022-01-05T13:36:26.000Z
2022-01-05T13:36:26.000Z
lua100/sources/utils/plugin_loader.cpp
SoulWorkerResearch/swp-loader
00d8ca0d59e0e5a0d279e5d4b5d08850042aa190
[ "WTFPL" ]
1
2022-01-06T04:41:02.000Z
2022-01-06T04:41:02.000Z
lua100/sources/utils/plugin_loader.cpp
SoulWorkerResearch/swp-loader
00d8ca0d59e0e5a0d279e5d4b5d08850042aa190
[ "WTFPL" ]
null
null
null
// local #include "../../headers/utils/plugin_loader.hpp" #include "../../headers/utils/game_version.hpp" #include "../../headers/plugins.hpp" // windows #include <Windows.h> // local deps #include <swpsdk/utils/spdlog_formatter.hpp> #include <swpsdk/plugin/attach.hpp> #include <swpsdk/plugin/loader.hpp> // deps #include <spdlog/spdlog.h> #include <spdlog/async.h> #include <spdlog/sinks/stdout_color_sinks.h> // cpp #include <system_error> #include <filesystem> #include <ranges> #include <future> namespace fs = std::filesystem; auto create_logger(const std::string& _name) { return spdlog::stdout_color_mt<spdlog::async_factory>(_name, spdlog::color_mode::always); } auto lua100::utils::plugin_loader::operator()(const fs::directory_entry& _entry) const->std::unique_ptr<plugin_info> { win::dll dll{ _entry }; auto logger{ m_logger_factory->create(_entry.path()) }; if (not dll) { logger->error(std::system_category().message(GetLastError())); return nullptr; } using attach_ptr_t = decltype(swpsdk::plugin::attach)*; const auto address{ GetProcAddress(static_cast<HMODULE>(dll), "attach") }; const auto attach{ reinterpret_cast<attach_ptr_t>(address) }; if (not attach) { logger->error("haven't attach function.", _entry); return nullptr; } const std::unique_ptr<swpsdk::plugin::info> info{ attach() }; if (not info) { logger->error("can't get info.", _entry); return nullptr; } if (info->game_version != m_game_version) { logger->warn("mismatch game version [plugin: {}] != [game: {}]", info->game_version, m_game_version); } if (info->sdk_version != swpsdk::current_version) { logger->warn("mismatch sdk version [plugin: {}] != [loader: {}]", info->sdk_version, swpsdk::current_version); } using loader_t = swpsdk::plugin::loader; auto p{ reinterpret_cast<const loader_t*>(info->instance) }; std::invoke(&loader_t::attach, p, logger); logger->info("attached v{}", info->plugin_version); return std::make_unique<plugin_info>(std::forward<decltype(dll)>(dll), std::forward<decltype(logger)>(logger)); } lua100::utils::plugin_loader::plugin_loader(const logger_factory_t& _logger_factory) : m_game_version{ utils::game_version::read() } , m_logger_factory{ _logger_factory } { spdlog::info("game v{}", m_game_version); }
30.05
117
0.680532
SoulWorkerResearch
f06e06a626ae3b1a04475f95d063151b67b07c4d
1,122
cpp
C++
boboleetcode/Play-Leetcode-master/0470-Implement-Rand10-Using-Rand7/cpp-0470/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2019-03-20T17:05:59.000Z
2019-10-15T07:56:45.000Z
boboleetcode/Play-Leetcode-master/0470-Implement-Rand10-Using-Rand7/cpp-0470/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0470-Implement-Rand10-Using-Rand7/cpp-0470/main2.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/implement-rand10-using-rand7/description/ /// Author : liuyubobobo /// Time : 2018-08-05 #include <iostream> #include <cassert> using namespace std; // The rand7() API is already defined for you. // int rand7(); // @return a random integer in the range 1 to 7 int rand7(){ return rand() % 7 + 1; } /// Rejection Sampling improved /// Utilizing out-of-range-samples /// The accurate expectation for calling number of rand7() can be seen here: /// https://leetcode.com/problems/implement-rand10-using-rand7/solution/ /// /// Time Complexity: O(1) /// Space Complexity: O(1) class Solution { public: int rand10() { int a = -1, b = rand7(), M = 7; do{ a = b; b = rand7(); int randNum = 7 * (a - 1) + b - 1; int largest = 7 * (M - 1) + 7 - 1; M = largest % 10 + 1; if(randNum < largest - largest % 10) return randNum % 10 + 1; b = randNum % 10 + 1; }while(true); assert(false); return -1; } }; int main() { return 0; }
23.375
84
0.552585
mcuallen
f070282cc4457847cf7540db2ebe08be1d4c5c4f
7,027
hpp
C++
RobWork/src/rw/proximity/BasicFilterStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/proximity/BasicFilterStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/proximity/BasicFilterStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_PROXIMITY_BasicFilterStrategy_HPP_ #define RW_PROXIMITY_BasicFilterStrategy_HPP_ #if !defined(SWIG) #include "ProximityFilterStrategy.hpp" #include "ProximitySetup.hpp" #include <rw/kinematics/Frame.hpp> #include <rw/kinematics/FrameMap.hpp> #endif namespace rw { namespace models { class WorkCell; }} // namespace rw::models namespace rw { namespace proximity { /** * @brief a simple rule based broadphase filter strategy. A static frame pair list of * frame pairs that is to be checked for collision is maintained. The list is static in * the sense that it is not optimized to be changed. However the user can both add and remove * new geometries and rules. * * @note The framepair list is explicitly kept in this class which makes this broadphase * strategy infeasible for workcells with many objects. Consider a workcell with 100 objects, * this will in worst case make a list of 10000 framepairs. */ class BasicFilterStrategy : public ProximityFilterStrategy { public: //! @brief smart pointer type to this class typedef rw::core::Ptr< BasicFilterStrategy > Ptr; //! @brief smart pointer type to this const class typedef rw::core::Ptr< const BasicFilterStrategy > CPtr; private: /** * @brief the proximity cache of the basic filter */ struct Cache : public ProximityCache { public: Cache (void* owner) : ProximityCache (owner){}; size_t size () const { return 0; }; void clear (){}; }; struct Filter : public ProximityFilter { public: Filter (kinematics::FramePairSet::iterator front, kinematics::FramePairSet::iterator end) : _front (front), _end (end) {} void pop () { ++_front; }; kinematics::FramePair frontAndPop () { kinematics::FramePair res = *_front; pop (); return (res); } rw::kinematics::FramePair front () { return *_front; }; bool isEmpty () { return _front == _end; }; private: kinematics::FramePairSet::iterator _front, _end; }; public: /** * @brief constructor - the ProximitySetup will be extracted from * the workcell description if possible. * * @param workcell [in] the workcell. */ BasicFilterStrategy (rw::core::Ptr< rw::models::WorkCell > workcell); /** * @brief constructor - constructs frame pairs based on the \b setup * @param workcell [in] the workcell * @param setup [in] the ProximitySetup describing exclude/include relations */ BasicFilterStrategy (rw::core::Ptr< rw::models::WorkCell > workcell, const rw::proximity::ProximitySetup& setup); //! @brief destructor virtual ~BasicFilterStrategy (){}; //////// interface inherited from BroadPhaseStrategy //! @copydoc ProximityFilterStrategy::reset virtual void reset (const rw::kinematics::State& state); //! @copydoc ProximityFilterStrategy::createProximityCache virtual rw::core::Ptr<rw::proximity::ProximityCache> createProximityCache () { return rw::core::ownedPtr (new Cache (this)); } //! @copydoc ProximityFilterStrategy::update virtual rw::core::Ptr<rw::proximity::ProximityFilter> update (const rw::kinematics::State& state); //! @copydoc ProximityFilterStrategy::createProximityCache virtual rw::core::Ptr<rw::proximity::ProximityFilter> update (const rw::kinematics::State& state, rw::core::Ptr<rw::proximity::ProximityCache> data); /** * @copydoc ProximityFilterStrategy::getProximitySetup */ rw::proximity::ProximitySetup& getProximitySetup (); /** * @brief Adds geometry associated to frame * @param frame [in] Frame which has the geometry associated */ virtual void addGeometry (rw::kinematics::Frame* frame, const rw::core::Ptr< rw::geometry::Geometry >); /** * @brief Removes the geometric model \b geo associated with * Frame \b frame from this strategy. * * @param frame [in] Frame which has the geometry associated */ virtual void removeGeometry (rw::kinematics::Frame* frame, const rw::core::Ptr< rw::geometry::Geometry >); /** * @brief Removes the geometric model \b geo associated with * Frame \b frame from this strategy. * * @param frame [in] Frame which has the geometry associated * @param geometryId [in] Geometry */ virtual void removeGeometry (rw::kinematics::Frame* frame, const std::string& geometryId); /** * @copydoc ProximityFilterStrategy::addRule */ virtual void addRule (const rw::proximity::ProximitySetupRule& rule); /** * @copydoc ProximityFilterStrategy::removeRule */ virtual void removeRule (const rw::proximity::ProximitySetupRule& rule); private: rw::core::Ptr< rw::models::WorkCell > _workcell; rw::proximity::ProximitySetup _psetup; kinematics::FramePairSet _collisionPairs; kinematics::FrameMap< std::vector< std::string > > _frameToGeoIdMap; void applyRule (const rw::proximity::ProximitySetupRule& rule, rw::core::Ptr< rw::models::WorkCell > workcell, rw::kinematics::FramePairSet& result); void initialize (); void initializeCollisionFramePairs (const rw::kinematics::State& state); }; #ifdef RW_USE_DEPREACTED typedef rw::core::Ptr< BasicFilterStrategy > BasicFilterStrategyPtr; #endif }} // namespace rw::proximity #endif /* BasicFilterStrategy_HPP_ */
37.179894
106
0.602675
ZLW07
f07244b9aa7b9739d855c629eed6db0a68eb950c
12,578
hpp
C++
src/include/InterpolationTemplate.hpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
5
2022-03-21T08:50:42.000Z
2022-03-31T05:31:41.000Z
src/include/InterpolationTemplate.hpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
null
null
null
src/include/InterpolationTemplate.hpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
1
2022-03-31T11:12:24.000Z
2022-03-31T11:12:24.000Z
#pragma once #include "BSpline.hpp" #include "Mesh.hpp" namespace intp { template <typename T, size_t D> class InterpolationFunction; // Forward declaration, since template has // a member of it. /** * @brief Template for interpolation with only coordinates, and generate * interpolation function when fed by function values. * */ template <typename T, size_t D> class InterpolationFunctionTemplate { public: using function_type = InterpolationFunction<T, D>; using size_type = typename function_type::size_type; using coord_type = typename function_type::coord_type; using val_type = typename function_type::val_type; static constexpr size_type dim = D; template <typename U> using DimArray = std::array<U, dim>; using MeshDim = MeshDimension<dim>; /** * @brief Construct a new Interpolation Function Template object * * @param order Order of BSpline * @param periodicity Periodicity of each dimension * @param interp_mesh_dimension The structure of coordinate mesh * @param x_ranges Begin and end iterator/value pairs of each dimension */ template <typename... Ts> InterpolationFunctionTemplate(size_type order, DimArray<bool> periodicity, MeshDim interp_mesh_dimension, std::pair<Ts, Ts>... x_ranges) : input_coords{}, mesh_dimension(interp_mesh_dimension), base(order, periodicity, input_coords, mesh_dimension, x_ranges...) { // adjust dimension according to periodicity { DimArray<size_type> dim_size_tmp; bool p_flag = false; for (size_type d = 0; d < dim; ++d) { dim_size_tmp[d] = mesh_dimension.dim_size(d) - (base.periodicity(d) ? ((p_flag = true), 1) : 0); } if (p_flag) { mesh_dimension.resize(dim_size_tmp); } } DimArray<typename function_type::spline_type::BaseSpline> base_spline_vals_per_dim; const auto& spline = base.spline(); // pre-calculate base spline of periodic dimension, since it never // changes due to its even-spaced knots for (size_type d = 0; d < dim; ++d) { if (base.periodicity(d) && base.uniform(d)) { base_spline_vals_per_dim[d] = spline.base_spline_value( d, spline.knots_begin(d) + order, spline.knots_begin(d)[order] + (1 - order % 2) * base.__dx[d] * .5); } } // loop through each dimension to construct coefficient matrix for (size_type d = 0; d < dim; ++d) { std::vector<Eigen::Triplet<val_type>> coef_list; // rough estimate of upper limit of coefficient number, reserve // space to make sure no re-allocation occurs during the filling // process coef_list.reserve(mesh_dimension.dim_size(d) * (order + 1)); for (size_type i = 0; i < mesh_dimension.dim_size(d); ++i) { const auto knot_num = spline.knots_num(d); // This is the index of knot point to the left of i-th // interpolated value's coordinate, notice that knot points has // a larger gap in both ends in non-periodic case. size_type knot_ind{}; if (base.uniform(d)) { knot_ind = base.periodicity(d) ? i + order : std::min( knot_num - order - 2, i > order / 2 ? i + (order + 1) / 2 : order); if (!base.periodicity(d)) { if (knot_ind <= 2 * order + 1 || knot_ind >= knot_num - 2 * order - 2) { // update base spline const auto iter = spline.knots_begin(d) + knot_ind; const coord_type x = spline.range(d).first + i * base.__dx[d]; base_spline_vals_per_dim[d] = spline.base_spline_value(d, iter, x); } } } else { coord_type x = input_coords[d][i]; // using BSpline::get_knot_iter to find current // knot_ind const auto iter = base.periodicity(d) ? spline.knots_begin(d) + i + order : i == 0 ? spline.knots_begin(d) + order : i == input_coords[d].size() - 1 ? spline.knots_end(d) - order - 2 : spline.get_knot_iter( d, x, i + 1, std::min(knot_num - order - 1, i + order)); knot_ind = iter - spline.knots_begin(d); base_spline_vals_per_dim[d] = spline.base_spline_value(d, iter, x); } for (size_type j = 0; j < order + 1; ++j) { coef_list.emplace_back( i, (knot_ind - order + j) % mesh_dimension.dim_size(d), base_spline_vals_per_dim[d][j]); } } // fill coefficient matrix { Eigen::SparseMatrix<double> coef(mesh_dimension.dim_size(d), mesh_dimension.dim_size(d)); coef.setFromTriplets(coef_list.begin(), coef_list.end()); solver[d].compute(coef); } #ifdef _DEBUG if (solver[d].info() != Eigen::Success) { throw std::runtime_error( std::string{ "Coefficient matrix decomposition failed at dim "} + std::to_string(d) + std::string{".\n"}); } #endif } } /** * @brief Construct a new 1D Interpolation Function Template object. * * @param order order of interpolation, the interpolated function is of * $C^{order-1}$ * @param periodic whether to construct a periodic spline * @param f_length point number of to-be-interpolated data * @param x_range a pair of x_min and x_max */ template <typename C1, typename C2> InterpolationFunctionTemplate(size_type order, bool periodicity, size_type f_length, std::pair<C1, C2> x_range) : InterpolationFunctionTemplate(order, {periodicity}, MeshDim{f_length}, x_range) { static_assert( dim == size_type{1}, "You can only use this overload of constructor in 1D case."); } template <typename C1, typename C2> InterpolationFunctionTemplate(size_type order, size_type f_length, std::pair<C1, C2> x_range) : InterpolationFunctionTemplate(order, false, f_length, x_range) {} /** * @brief Construct a new (nonperiodic) Interpolation Function Template * object * * @param order Order of BSpline * @param interp_mesh_dimension The structure of coordinate mesh * @param x_ranges Begin and end iterator/value pairs of each dimension */ template <typename... Ts> InterpolationFunctionTemplate(size_type order, MeshDim interp_mesh_dimension, std::pair<Ts, Ts>... x_ranges) : InterpolationFunctionTemplate(order, {}, interp_mesh_dimension, x_ranges...) {} template <typename MeshOrIterPair> function_type interpolate(MeshOrIterPair&& mesh_or_iter_pair) const& { function_type interp{base}; interp.__spline.load_ctrlPts( __solve_for_control_points(Mesh<val_type, dim>{ std::forward<MeshOrIterPair>(mesh_or_iter_pair)})); return interp; } template <typename MeshOrIterPair> function_type interpolate(MeshOrIterPair&& mesh_or_iter_pair) && { base.__spline.load_ctrlPts( __solve_for_control_points(Mesh<val_type, dim>{ std::forward<MeshOrIterPair>(mesh_or_iter_pair)})); return std::move(base); } private: // input coordinates, needed only in nonuniform case DimArray<typename function_type::spline_type::KnotContainer> input_coords; MeshDim mesh_dimension; // the base interpolation function with unspecified weights function_type base; // solver for weights DimArray<Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>> solver; Mesh<val_type, dim> __solve_for_control_points( const Mesh<val_type, dim>& f_mesh) const { Mesh<val_type, dim> weights{mesh_dimension}; // Copy interpolating values into weights mesh as the initial state of // the iterative control points solving algorithm for (auto it = f_mesh.begin(); it != f_mesh.end(); ++it) { auto f_indices = f_mesh.iter_indices(it); bool skip_flag = false; for (size_type d = 0; d < dim; ++d) { // Skip last point of periodic dimension if (f_indices[d] == weights.dim_size(d)) { skip_flag = true; break; } } if (!skip_flag) { weights(f_indices) = *it; } } // loop through each dimension to solve for control points for (size_type d = 0; d < dim; ++d) { // size of hyperplane when given dimension is fixed size_type hyperplane_size = weights.size() / weights.dim_size(d); // loop over each point (representing a 1D spline) of hyperplane for (size_type i = 0; i < hyperplane_size; ++i) { DimArray<size_type> ind_arr; for (size_type d_ = 0, total_ind = i; d_ < dim; ++d_) { if (d_ == d) { continue; } ind_arr[d_] = total_ind % weights.dim_size(d_); total_ind /= weights.dim_size(d_); } // loop through one dimension, update interpolating value to // control points Eigen::VectorXd mesh_val_1d(weights.dim_size(d)); size_type ind_1d{}; for (auto it = weights.begin(d, ind_arr); it != weights.end(d, ind_arr); ++it, ++ind_1d) { mesh_val_1d(ind_1d) = *it; } Eigen::VectorXd weights_1d = solver[d].solve(mesh_val_1d); ind_1d = 0; for (auto it = weights.begin(d, ind_arr); it != weights.end(d, ind_arr); ++it, ++ind_1d) { *it = weights_1d(ind_1d); } } } return weights; } }; template <typename T> class InterpolationFunctionTemplate1D : public InterpolationFunctionTemplate<T, size_t{1}> { private: using base = InterpolationFunctionTemplate<T, size_t{1}>; public: InterpolationFunctionTemplate1D(typename base::size_type f_length, typename base::size_type order = 3, bool periodicity = false) : InterpolationFunctionTemplate1D( std::make_pair( (typename base::coord_type){}, static_cast<typename base::coord_type>(f_length - 1)), f_length, order, periodicity) {} template <typename C1, typename C2> InterpolationFunctionTemplate1D(std::pair<C1, C2> x_range, typename base::size_type f_length, typename base::size_type order = 3, bool periodicity = false) : base(order, periodicity, f_length, x_range) {} }; } // namespace intp
40.574194
79
0.5225
12ff54e
f073a8f2172f9a84bb1539aa1a7d706d36e8e251
25,075
cpp
C++
src/Networking.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
1
2015-08-27T17:01:48.000Z
2015-08-27T17:01:48.000Z
src/Networking.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
11
2015-09-24T03:15:13.000Z
2016-02-23T03:03:04.000Z
src/Networking.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
1
2016-02-16T22:25:06.000Z
2016-02-16T22:25:06.000Z
#include "Networking.h" #include "globalvars.h" #include <iostream> #include <iomanip> #include <stdio.h> #include <string> namespace network { int mainPort = 23636; bool packetDeletion = false; bool servWait = false; bool cliWait = false; bool server = false; bool client = false; bool chatting = false; bool needTime = false; bool givingTime = false; std::string name = ""; std::string connectedServer = ""; } int displayPort() { return network::mainPort; } Identity::Identity() { wrongVersion = "Wrong Version"; connection = "Connection"; connectionSuccessful = "Connection Successful"; textMessage = "Text Message"; drawStuffs = "Draw Stuffs"; grid = "Grid"; peers = "Peers"; clientMouse = "Client Mouse Position"; gridUpdate = "Grid Update"; tilesUpdate = "Tiles Update"; ping = "Ping"; pong = "Pong"; updateRoster = "Update Roster"; updateItems = "Update Items"; } Identity ident; sf::IpAddress server("127.0.0.1"); bool TcpFirstRun = true; sf::TcpListener servListener; sf::TcpSocket servSocket; sf::TcpSocket cliSocket; std::list<sf::TcpSocket*> clients; sf::SocketSelector selector; BoolPacket::BoolPacket() { toDelete = false; } std::vector<BoolPacket> packetContainer; /////////////////////////////////////////////////// ///////// /// Launch a server, wait for an incoming connection, /// send a message and wait for the answer. /// //////////////////////////////////////////////////////////// ServerController::ServerController() { waiting = false; conID = 100; } ServerController servCon; ClientController::ClientController() { mode = "Local"; waiting = false; connected = false; chatting = false; name = ""; ID = -1; } ClientController cliCon; Peer::Peer() { name = ""; ID = servCon.conID++; } Peers peers; void DealPackets() { if(gvars::debug) std::cout << "DealPacket Begins" << packetContainer.size() << std::endl; int PackLimit = packetContainer.size(); for(int i = 0; i != PackLimit; i++) { //packetContainer[i].Packet std::string GotIdent; packetContainer[i].packet >> GotIdent; if(gvars::debug) std::cout << "GotIdent: \n" << GotIdent << std::endl; if(GotIdent != "") { cliCon.waiting = false; if(gvars::debug) std::cout << "Message received from server " << ", Type:" << GotIdent << std::endl; if(GotIdent == ident.wrongVersion) { std::string ver; packetContainer[i].packet >> ver; std::cout << "You have the wrong version. \n"; std::cout << "Servers Version: " << ver << ", Your Version: " << gvars::version << std::endl; std::cout << "You should acquire the same version as the server. \n"; cliCon.connected = false; } if(GotIdent == ident.connectionSuccessful) { std::cout << "Your now connected to " << cliCon.server << std::endl; cliCon.connected = true; } if(GotIdent == ident.textMessage) { if(gvars::debug) std::cout << "Dealing with Text Message, Pack: " << i << std::endl; std::string Text; packetContainer[i].packet >> Text; cliCon.chatHistory.push_back(Text); std::cout << "* " << Text; sf::Packet SendPacket; SendPacket << ident.textMessage << Text; for (std::list<sf::TcpSocket*>::iterator zit = clients.begin(); zit != clients.end(); ++zit) { if(gvars::debug) std::cout << "Running through clients \n"; sf::TcpSocket& clientz = **zit; clientz.send(SendPacket); } if(gvars::debug) std::cout << "Done with Text Message Packet:" << i << std::endl; } if(GotIdent == ident.drawStuffs) { //NeedsToDraw = true; } if(GotIdent == ident.connection) { Peer peer; packetContainer[i].packet >> peer.name; peers.connected.push_back(peer); } if(GotIdent == ident.clientMouse) { std::string Name; packetContainer[i].packet >> Name; if(gvars::debug) std::cout << "Dealing with ClientMouse from," << Name << ", Pack: " << i << std::endl; for(int i = 0; i != peers.connected.size(); i++) { if(Name == peers.connected[i].name) { //packetContainer[i].Packet >> peers.Connected[i].MousePos.x >> peers.Connected[i].MousePos.y; sf::Uint32 x; sf::Uint32 y; packetContainer[i].packet >> x >> y; peers.connected[i].mousePos.x = x; peers.connected[i].mousePos.y = y; } } } if(GotIdent == ident.pong) { std::string peerName; packetContainer[i].packet >> peerName; for(auto &peer : peers.connected) { if(peer.name == peerName) { sf::Clock myClock; sf::Time recvTime; sf::Time myTime = myClock.getElapsedTime(); sf::Uint32 recvValue; packetContainer[i].packet >> recvValue; recvTime = sf::microseconds(recvValue); int thePing = myTime.asMicroseconds() - recvTime.asMicroseconds(); peer.ping = thePing; } } } if(GotIdent == ident.tilesUpdate) { int regionX, regionY, tileX, tileY, tileZ, tileID; sf::Packet pack; pack = packetContainer[i].packet; while(!pack.endOfPacket()) { pack >> regionX >> regionY; pack >> tileX >> tileY >> tileZ; pack >> tileID; int regionXDiff = regionX - gvars::currentregionx; int regionYDiff = regionY - gvars::currentregiony; tiles[(tileX)][(tileY)][tileZ].setTilebyID(tileID); if(abs_to_index(regionXDiff) <= 1 && abs_to_index(regionYDiff) <= 1) { //tiles[(tileX+(regionXDiff*CHUNK_SIZE))][(tileY+(regionYDiff*CHUNK_SIZE))][tileZ].setTilebyID(tileID); } std::cout << "tilesUpdate: " << regionXDiff << "/" << regionYDiff << "/" << tileX << "/" << tileY << "/" << tileZ << "/" << tileID << std::endl; } } } packetContainer[i].toDelete = true; } bool DoneDeleting = false; std::vector<BoolPacket>::iterator EndLimit = packetContainer.end(); std::vector<NestClass> Nested; int DeleteAmount = 0; for(std::vector<BoolPacket>::iterator i = packetContainer.begin(); i != EndLimit; i++) { bool CatchAll = false; if(i->toDelete == true) { DeleteAmount++; NestClass NC; NC.nestIter = i; Nested.push_back(NC); //CatchAll = true; //EndLimit--; } } //packetContainer.erase(packetContainer.begin(),packetContainer.begin()+DeleteAmount); if(gvars::debug) std::cout << "Nested: " << Nested.size() << std::endl; network::packetDeletion = true; for(int i = Nested.size()-1; i != -1; i--) { if(gvars::debug) std::cout << "Removed: " << i << std::endl; packetContainer.erase( Nested[i].nestIter ); } Nested.clear(); network::packetDeletion = false; //Global.PackWait = false; /* for(std::vector<std::vector<BoolPacket>::iterator>::iterator i = Nested.end(); i != Nested.begin(); i--) { packetContainer.erase(i); } */ /* while(DoneDeleting == false) { std::vector<BoolPacket>::iterator i; DoneDeleting = true; // try{ for(i = packetContainer.begin(); i != EndLimit; i++) { bool CatchAll = false; if(i->ToDelete == true) { DoneDeleting = false; packetContainer.erase(i); Nested.push_back(i); CatchAll = true; EndLimit--; break; } if(CatchAll) { std::cout << "Caught somefin' Paul! \n"; break; } } // }catch (std::exception& e){ std::cout << "Packet Container try-fail! \n"; } } */ } void runTcpServer(unsigned short port) { // Create a server socket to accept new connections //Code ripped to Main.cpp, Code 555000999 // Wait for a connection if(TcpFirstRun) { TcpFirstRun = false; /* sf::TcpSocket* client = new sf::TcpSocket; if (servListener.accept(*client) != sf::Socket::Done) { std::cout << "Infinite? \n"; return; } //std::cout << "Client connected: " << client.getRemoteAddress() << std::endl; selector.add(*client); clients.push_back(client); */ } while(selector.wait()) { if(gvars::debug) std::cout << "Wait Successful! \n"; if(selector.isReady(servListener)) { std::cout << "Listener is ready! \n"; sf::TcpSocket* client = new sf::TcpSocket; if (servListener.accept(*client) == sf::Socket::Done) { selector.add(*client); clients.push_back(client); } else { std::cout << "Deleting a Client! Is this normal? \n"; delete client; } std::cout << "Listener is done, Moving on. \n"; } else { for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) { //std::cout << "Running through clients \n"; sf::TcpSocket& client = **it; if(selector.isReady(client)) { if(gvars::debug) std::cout << "Client is ready! \n"; sf::Packet GotPacket; if(client.receive(GotPacket) != sf::Socket::Done) { std::cout << "Not Ready"; return; } BoolPacket BP; BP.packet = GotPacket; int Delay = 0; while(network::packetDeletion == true) { std::cout << " " << Delay++; } packetContainer.push_back(BP); if(gvars::debug) std::cout << "Client is done. \n"; } else { if(gvars::debug) std::cout << "IsReady(Client) is false \n"; } } } } if(gvars::debug) std::cout << "Do we make it here? \n"; //DealPackets(); if(gvars::debug) std::cout << "And if so, How about here? \n"; //Global.ServWait = false; } void runTcpClient(unsigned short port) { // Create a socket for communicating with the server // Connect to the server if(gvars::debug) std::cout << "Waiting on Message! \n"; sf::Packet GotPacket; if (cliSocket.receive(GotPacket) != sf::Socket::Done) { network::cliWait = false; return; } std::string GotIdent; GotPacket >> GotIdent; if(gvars::debug) std::cout << "GotIdent: " << GotIdent << std::endl; if(GotIdent != "") { network::cliWait = false; cliCon.waiting = false; if(gvars::debug) std::cout << "Message received from server " << ", Type:" << GotIdent << std::endl; if(GotIdent == ident.wrongVersion) { std::string ver; GotPacket >> ver; std::cout << "You have the wrong version. \n"; std::cout << "Servers Version: " << ver << ", Your Version: " << gvars::version << std::endl; std::cout << "You should acquire the same version as the server. \n"; cliCon.connected = false; } if(GotIdent == ident.connectionSuccessful) { std::cout << "Your now connected to " << cliCon.server << std::endl; cliCon.connected = true; } if(GotIdent == ident.textMessage) { std::string Text; GotPacket >> Text; cliCon.chatHistory.push_back(Text); chatBox.addChat(Text,sf::Color::White); std::cout << Text; } if(GotIdent == ident.drawStuffs) { //NeedsToDraw = true; } if(GotIdent == ident.clientMouse) { std::string Name; GotPacket >> Name; bool Exists = false; for(int i = 0; i != peers.connected.size(); i++) { if(Name == peers.connected[i].name) Exists = true; } if(!Exists) { Peer peer; peer.name = Name; peer.mousePos = sf::Vector2f(5,5); peers.connected.push_back(peer); } for(int i = 0; i != peers.connected.size(); i++) { if(Name == peers.connected[i].name) { sf::Uint32 x; sf::Uint32 y; GotPacket >> x >> y; peers.connected[i].mousePos.x = x; peers.connected[i].mousePos.y = y; } } } if(GotIdent == ident.gridUpdate) { networkGridUpdate(GotPacket); } if(GotIdent == ident.ping) { sf::Packet toSend; toSend << ident.pong << network::name; sf::Uint32 peerTime; GotPacket >> peerTime; toSend << peerTime; cliSocket.send(toSend); } if(GotIdent == ident.peers) { peers.connected.clear(); while(!GotPacket.endOfPacket()) { Peer peer; sf::Uint32 peerPing; GotPacket >> peer.name >> peerPing; peer.ping = peerPing; peers.connected.push_back(peer); } } if(GotIdent == ident.updateRoster) { network::needTime = true; sf::Lock lock(mutex::npcList); while(!GotPacket.endOfPacket()) { std::string npcName, npcBloodContent; sf::Uint32 npcID, npcXpos, npcYpos, npcZpos; GotPacket >> npcName >> npcID >> npcXpos >> npcYpos >> npcZpos >> npcBloodContent; bool npcFound = false; for(auto &npc : npclist) { if(npc.name == npcName && npc.id == npcID) { npcFound = true; npc.xpos = npcXpos; npc.ypos = npcYpos; npc.zpos = npcZpos; npc.bloodcontent = npcBloodContent; } } if(npcFound == false) { Npc npc; npc = *getGlobalCritter("Human"); //npc.img.setTexture(texturemanager.getTexture("Human.png")); npc.xpos = npcXpos; npc.ypos = npcYpos; npc.zpos = npcZpos; npc.id = npcID; npc.name = npcName; npc.reCreateSkills(); npc.hasSpawned = true; npc.bloodcontent = npcBloodContent; npclist.push_back(npc); } } } if(GotIdent == ident.updateItems) { sf::Lock lock(mutex::itemList); while(!GotPacket.endOfPacket()) { std::string itemName; sf::Uint32 itemID, itemXpos, itemYpos, itemZpos, itemProdrate; GotPacket >> itemName >> itemID >> itemXpos >> itemYpos >> itemZpos >> itemProdrate; bool itemFound = false; for(auto &item : worlditems) { if(item.name == itemName && item.id == itemID) { itemFound = true; item.xpos = itemXpos; item.ypos = itemYpos; item.zpos = itemZpos; item.prodratetimer = itemProdrate; } } if(itemFound == false) { Item item; item = *getGlobalItem(itemName); item.xpos = itemXpos; item.ypos = itemYpos; item.zpos = itemZpos; item.id = itemID; item.name = itemName; item.prodratetimer = itemProdrate; worlditems.push_back(item); } } } } } void tcpSendtoAll(sf::Packet pack) { for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) { sf::TcpSocket& client = **it; client.send(pack); } } bool chatCommand(std::string input) { std::vector<std::string> elements; bool finished = false; sf::Color errorColor(100,100,100); sf::Color warmColor(255,150,150); sf::Color goodColor = sf::Color::White; size_t tStart = 0; size_t tEnd = 0; while(finished == false) { tEnd = input.find(" ",tStart); std::string injection; injection.append(input,tStart,tEnd-tStart); elements.push_back(injection); tStart = tEnd+1; if(tEnd == input.npos) finished = true; } std::cout << "input: " << input << std::endl; for(auto &i : elements) { std::cout << "elements: " << i << std::endl; } if(elements[0] == "/connect") { std::cout << "Connect chat command detected. \n"; if(network::connectedServer != "") { chatBox.addChat("Server: Error, You're already connected to " + network::connectedServer, errorColor); return false; } if(network::name == "") { chatBox.addChat("Server: Error, please give yourself a name with /setname before attempting to connect.", errorColor); return false; } try { int test = std::stoi(elements[2]); } catch (std::exception &e) { chatBox.addChat("Command: /connect [IP Address] [Port]", errorColor); return false; } if (cliSocket.connect(elements[1], std::stoi(elements[2])) == sf::Socket::Done) { std::cout << "Connected to server " << elements[1] << std::endl; network::connectedServer = elements[1]; sf::Packet packet; packet << ident.connection << network::name; cliSocket.send(packet); packet.clear(); packet << ident.clientMouse << network::name << gvars::mousePos.x << gvars::mousePos.y; cliSocket.send(packet); packet.clear(); packet << ident.textMessage << network::name + randomWindowName(); cliSocket.send(packet); chatBox.addChat("Server: Connected to " + elements[1] + "(" + elements[2] + ")", goodColor); return true; } chatBox.addChat("Server: Something went wrong...", goodColor); return false; } else if(elements[0] == "/setname") { chatBox.addChat("Server: " + network::name + " has changed their name to " + elements[1], goodColor); network::name = elements[1]; if(elements[1] == "Lithi" || elements[1] == "Biocava" || elements[1] == "Sneaky" || elements[1] == "SneakySnake") chatBox.addChat("Server: Ooo, Ooo, I like you!", warmColor); if(elements[1] == "Argwm" || elements[1] == "Dehaku") chatBox.addChat("Server: Hey, that's my masters name!", warmColor); return true; } else if(elements[0] == "/repeat") { try { int test = std::stoi(elements[1]); } catch (std::exception &e) { chatBox.addChat("Invalid argument: " + elements[1] + " in command " + input, errorColor); chatBox.addChat("Command: /repeat [numberoftimes] [series of words or numbers]", errorColor); return false; } std::string repeatingLine; for(int i = 0; i != elements.size(); i++) { if(i != 0 && i != 1) { repeatingLine.append(elements[i] + " "); } } for(int i = 0; i != std::stoi(elements[1]); i++) { chatBox.addChat("Server: Repeating; " + repeatingLine, goodColor); } return true; } chatBox.addChat("Unrecognized command: " + input, errorColor); return false; } void ServerController::updateClients() { if((gvars::framesPassed % 30) == 0 && gvars::sendGrid) { /* Tile Updates */ sf::Packet pack; pack << ident.gridUpdate; for(int x = 0; x != GRIDS; x++) for(int y = 0; y != GRIDS; y++) for(int z = 0; z != CHUNK_SIZE; z++) { sf::Uint32 tileID = tiles[x][y][z].id; pack << tileID; } tcpSendtoAll(pack); } if((gvars::framesPassed % 30) == 0) { sf::Packet pack; sf::Clock myClock; sf::Time theTime = myClock.getElapsedTime(); sf::Uint32 sendTime = theTime.asMicroseconds(); pack << ident.ping << sendTime; tcpSendtoAll(pack); pack.clear(); pack << ident.peers; for(auto &i : peers.connected) { sf::Uint32 peerPing = i.ping; pack << i.name << peerPing; } tcpSendtoAll(pack); } if((gvars::framesPassed % 30) == 0) { sf::Packet pack; pack << ident.updateRoster; sf::Lock lock(mutex::npcList); for(auto &npc : npclist) { sf::Uint32 npcID = npc.id, npcXpos = npc.xpos, npcYpos = npc.ypos, npcZpos = npc.zpos; pack << npc.name << npcID << npcXpos << npcYpos << npcZpos << npc.bloodcontent; } tcpSendtoAll(pack); } if((gvars::framesPassed % 30) == 0) { sf::Packet pack; pack << ident.updateItems; sf::Lock lock(mutex::itemList); for(auto &item : worlditems) { sf::Uint32 itemID = item.id, itemXpos = item.xpos, itemYpos = item.ypos, itemZpos = item.zpos, itemProdrate = item.prodratetimer; pack << item.name << itemID << itemXpos << itemYpos << itemZpos << itemProdrate; } tcpSendtoAll(pack); } }
31.501256
180
0.45324
crumblingstatue
f07413236a6a881943dacab4e29821e19995c331
323
hpp
C++
src/RadialGrid/RadialGrid.hpp
rdietric/lsms
8d0d5f01186abf9a1cc54db3f97f9934b422cf92
[ "BSD-3-Clause" ]
28
2020-01-05T20:05:31.000Z
2022-03-07T09:08:01.000Z
src/RadialGrid/RadialGrid.hpp
rdietric/lsms
8d0d5f01186abf9a1cc54db3f97f9934b422cf92
[ "BSD-3-Clause" ]
8
2019-07-30T13:59:18.000Z
2022-03-31T17:43:35.000Z
lsms/src/RadialGrid/RadialGrid.hpp
hkershaw-brown/MuST
9db4bc5061c2f2c4d7dfd92f53b4ef952602c070
[ "BSD-3-Clause" ]
13
2020-02-11T17:04:45.000Z
2022-03-28T09:23:46.000Z
#ifndef LSMS_RGRID_H #define LSMS_RGRID_H #include <vector> #include "Real.hpp" class RadialGrid { public: inline RadialGrid() : N(0), jmt(0), jws(0), h(0.0) {} int N,jmt,jws; Real h; std::vector<Real> r_mesh,x_mesh; }; void generateRadialGrid(RadialGrid * g, Real x0, Real h, int N, int jmt, int jws); #endif
17.944444
82
0.674923
rdietric
7eb581ab465752104d52238a6737e197c1a6fefd
683
cc
C++
solutions/cpp/448-find-all-numbers-disappeared-in-an-array.cc
PW486/leetcode
c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9
[ "Unlicense" ]
null
null
null
solutions/cpp/448-find-all-numbers-disappeared-in-an-array.cc
PW486/leetcode
c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9
[ "Unlicense" ]
null
null
null
solutions/cpp/448-find-all-numbers-disappeared-in-an-array.cc
PW486/leetcode
c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> findDisappearedNumbers(vector<int> &nums) { vector<int> result; int len = nums.size(); for (int i = 0; i < len; i++) { int pos = abs(nums[i]) - 1; if (nums[pos] > 0) { nums[pos] = -nums[pos]; } } for (int i = 0; i < len; i++) { if (nums[i] > 0) result.push_back(i + 1); } return result; } }; int main() { vector<int> nums = {4, 3, 2, 7, 8, 2, 3, 1}; vector<int> result = Solution().findDisappearedNumbers(nums); for (int i = 0; i < result.size(); i++) { cout << result[i] << endl; } return 0; }
18.972222
63
0.524158
PW486
7eb8391219baa3aad813314e31142d86f4cf2224
1,176
cpp
C++
src/devices/video/WXGLDevice.cpp
SolarAquarion/ffmpegyag
bb77508afd7dd30b853ff8e56a9a062c01ca8237
[ "MIT" ]
12
2017-09-24T06:27:25.000Z
2022-02-02T09:40:38.000Z
src/devices/video/WXGLDevice.cpp
SolarAquarion/ffmpegyag
bb77508afd7dd30b853ff8e56a9a062c01ca8237
[ "MIT" ]
3
2017-09-24T06:34:06.000Z
2018-06-11T05:31:21.000Z
src/devices/video/WXGLDevice.cpp
SolarAquarion/ffmpegyag
bb77508afd7dd30b853ff8e56a9a062c01ca8237
[ "MIT" ]
4
2018-03-02T15:23:12.000Z
2019-06-05T12:07:13.000Z
#include "WXGLDevice.h" WXGLDevice::WXGLDevice() { widget = NULL; } WXGLDevice::~WXGLDevice() { // } void* WXGLDevice::CreateWidget(const char* title, int width, int height, bool fullscreen) { // TODO: create wxWidgets window return NULL; } void WXGLDevice::DestroyWidget(void* Widget) { Release(); wxWindow* tmp = (wxWindow*)Widget; if(tmp) { if(tmp == widget) { // internal widget is same as widget requested for destruction widget = NULL; } wxDELETE(tmp); tmp = NULL; //Widget = NULL; // statement has no effect, pointer only valid in local scope } } bool WXGLDevice::Init(void* Widget) { widget = (wxGLCanvas*)Widget; if(widget && widget->GetContext()) { return true; } widget = NULL; return false; } void WXGLDevice::Release() { // } void WXGLDevice::MakeCurrent() { if(widget && widget->GetContext()) { widget->SetCurrent(); } } void WXGLDevice::SwapBuffers() { widget->SwapBuffers(); // SwapBuffer has no negative effect on single buffering (can always be used) GLDevice::SwapBuffers(); }
18.092308
104
0.602891
SolarAquarion
7eb87aaedd0bb95200e6b68d928558a911803211
466
hpp
C++
srcs/game/components/LimitSide.hpp
BenjaminRepingon/Nibbler-MultiLib
71ae0b374346fef63ea5280f05722b185afa793a
[ "Apache-2.0" ]
null
null
null
srcs/game/components/LimitSide.hpp
BenjaminRepingon/Nibbler-MultiLib
71ae0b374346fef63ea5280f05722b185afa793a
[ "Apache-2.0" ]
null
null
null
srcs/game/components/LimitSide.hpp
BenjaminRepingon/Nibbler-MultiLib
71ae0b374346fef63ea5280f05722b185afa793a
[ "Apache-2.0" ]
null
null
null
#ifndef LIMITSIDE_HPP # define LIMITSIDE_HPP # include "../../core/AComponent.hpp" # include "../../utils/vec.hpp" class LimitSide : public AComponent { public: // LimitSide( void ); LimitSide( Vec2i const & a, Vec2i const & b); ~LimitSide( void ); LimitSide( LimitSide const & src ); LimitSide & operator=( LimitSide const & rhs ); virtual int update( ILib const * lib, double delta ); virtual int render( ILib const * lib ) const; }; #endif
22.190476
58
0.665236
BenjaminRepingon
7eb89fa94b69a80478d0a7c23f0facb0389627e5
363
cpp
C++
recursion/jumps.cpp
heysujal/Problem-Solving-in-cpp
b5e21bc467d57d3c2050776b948e7f59daabe945
[ "Unlicense" ]
1
2021-10-04T16:24:57.000Z
2021-10-04T16:24:57.000Z
recursion/jumps.cpp
heysujal/Problem-Solving-in-cpp
b5e21bc467d57d3c2050776b948e7f59daabe945
[ "Unlicense" ]
null
null
null
recursion/jumps.cpp
heysujal/Problem-Solving-in-cpp
b5e21bc467d57d3c2050776b948e7f59daabe945
[ "Unlicense" ]
1
2021-10-04T16:25:00.000Z
2021-10-04T16:25:00.000Z
// no of ways to reach n by only jumping 1, 2 or 3 steps at a time. #include <bits/stdc++.h> using namespace std; int jump_count(int n) { if (n < 0) return 0; if (n == 0) return 1; return jump_count(n - 1) + jump_count(n - 2) + jump_count(n - 3); } int main() { int n; cin >> n; cout << jump_count(n); return 0; }
15.125
69
0.5427
heysujal
7eb9ce2ce706d6261c46377256d94ad79e1cd712
13,299
cpp
C++
src/tests/functional/plugin/cpu/subgraph_tests/src/seq_native_order.cpp
shaun95/openvino
a3d5b6501d851e604a0cd363a100f42ec4369469
[ "Apache-2.0" ]
1
2022-03-09T08:11:10.000Z
2022-03-09T08:11:10.000Z
src/tests/functional/plugin/cpu/subgraph_tests/src/seq_native_order.cpp
wgzintel/openvino
334e9e994e1e64d060edc989c77fab35919e378d
[ "Apache-2.0" ]
1
2022-02-13T09:56:15.000Z
2022-02-13T09:56:15.000Z
src/tests/functional/plugin/cpu/subgraph_tests/src/seq_native_order.cpp
AlexRogalskiy/openvino
ac2e639ff8f9a607c3c682a4c4e165c238eb817f
[ "Apache-2.0" ]
1
2020-12-13T22:16:54.000Z
2020-12-13T22:16:54.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "shared_test_classes/base/ov_subgraph.hpp" #include "ngraph_functions/builders.hpp" #include "test_utils/cpu_test_utils.hpp" #include "transformations/op_conversions/bidirectional_sequences_decomposition.hpp" #include "transformations/op_conversions/convert_sequences_to_tensor_iterator.hpp" using namespace CPUTestUtils; using namespace ov::test; namespace SubgraphTestsDefinitions { enum class SEQ_TYPE { GRU, LSTM, RNN }; using TargetShapeParams = std::tuple<size_t, // batch_size size_t>; // seq_length using InputShapeParams = std::tuple<std::vector<ov::Dimension>, // bounds for batch_size and seq_length std::vector<TargetShapeParams>>; // target batch_size and seq_length using SeqParams = std::tuple<SEQ_TYPE, // node type size_t, // hidden_size size_t, // input_size InputShapeParams, // input shapes std::vector<std::string>, // Activations float, // Clip bool, // Linear_before_reset ov::op::RecurrentSequenceDirection, // Direction ElementType>; // Network precision class SequenceCPUTest : public testing::WithParamInterface<SeqParams>, virtual public ov::test::SubgraphBaseTest, public CPUTestsBase { public: static std::string getTestCaseName(const testing::TestParamInfo<SeqParams> &obj) { SEQ_TYPE seqType; size_t hidden_size, input_size; InputShapeParams inShapeParams; std::vector<std::string> activations; float clip; bool linearBeforeReset; ov::op::RecurrentSequenceDirection direction; ElementType netPrecision; std::tie(seqType, hidden_size, input_size, inShapeParams, activations, clip, linearBeforeReset, direction, netPrecision) = obj.param; std::vector<ov::Dimension> bounds; std::vector<TargetShapeParams> targetShapes; std::tie(bounds, targetShapes) = inShapeParams; std::ostringstream result; if (seqType == SEQ_TYPE::GRU) { result << "GRU_"; } else if (seqType == SEQ_TYPE::LSTM) { result << "LSTM_"; } else if (seqType == SEQ_TYPE::RNN) { result << "RNN_"; } else { IE_THROW() << "Unsupported seq type"; } result << "hidden_size=" << hidden_size << "_input_size=" << input_size << "_"; result << "batch_size_dyn=" << bounds[0] << "_seq_length_dyn=" << bounds[1] << "_"; for (const auto &ts : targetShapes) { size_t bs, sl; std::tie(bs, sl) = ts; result << "(bs=" << bs << "_sl=" << sl << ")_"; } result << "activations=" << CommonTestUtils::vec2str(activations) << "_"; result << "clip=" << clip << "_"; result << "linear=" << linearBeforeReset << "_"; result << "direction=" << direction << "_"; result << "netPrec=" << netPrecision; return result.str(); } protected: void SetUp() override { const size_t batch_size_pos = 0; const size_t seq_length_pos = 1; SEQ_TYPE seqType; size_t hidden_size, input_size; InputShapeParams inShapeParams; std::vector<std::string> activations; float clip; bool linearBeforeReset; ov::op::RecurrentSequenceDirection direction; ElementType netPrecision; std::tie(seqType, hidden_size, input_size, inShapeParams, activations, clip, linearBeforeReset, direction, netPrecision) = this->GetParam(); std::vector<ov::Dimension> bounds; std::vector<TargetShapeParams> targetShapes; std::tie(bounds, targetShapes) = inShapeParams; targetDevice = CommonTestUtils::DEVICE_CPU; seqLengthInIdx = (seqType == SEQ_TYPE::LSTM ? 3 : 2); const size_t numDirections = direction == ov::op::RecurrentSequenceDirection::BIDIRECTIONAL ? 2 : 1; // dynamic shapes ov::PartialShape X_shape(std::vector<ov::Dimension>{bounds[seq_length_pos], bounds[batch_size_pos], ov::Dimension(input_size)}); inputDynamicShapes.push_back(X_shape); ov::PartialShape second_in_shape(std::vector<ov::Dimension>{bounds[batch_size_pos], ov::Dimension(numDirections), ov::Dimension(hidden_size)}); inputDynamicShapes.push_back(second_in_shape); if (seqType == SEQ_TYPE::LSTM) { inputDynamicShapes.push_back(second_in_shape); } ov::PartialShape seq_len_shape(std::vector<ov::Dimension>{bounds[batch_size_pos]}); inputDynamicShapes.push_back(seq_len_shape); auto hidden_size_weight = hidden_size; if (seqType == SEQ_TYPE::GRU) { hidden_size_weight *= 3; } else if (seqType == SEQ_TYPE::LSTM) { hidden_size_weight *= 4; } std::vector<ov::Shape> weightShape; ov::Shape W_shape(std::vector<size_t>{numDirections, hidden_size_weight, input_size}); weightShape.push_back(W_shape); ov::Shape R_shape(std::vector<size_t>{numDirections, hidden_size_weight, hidden_size}); weightShape.push_back(R_shape); ov::Shape B_shape; if (seqType == SEQ_TYPE::GRU) { B_shape = std::vector<size_t>{numDirections, (linearBeforeReset ? (4 * hidden_size) : (3 * hidden_size))}; } else { B_shape = std::vector<size_t>{numDirections, hidden_size_weight}; } weightShape.push_back(B_shape); // target shape for (const auto &ts : targetShapes) { std::vector<ov::Shape> currTS; size_t bs, sl; std::tie(bs, sl) = ts; currTS.emplace_back(std::vector<size_t>{sl, bs, input_size}); currTS.emplace_back(std::vector<size_t>{bs, numDirections, hidden_size}); if (seqType == SEQ_TYPE::LSTM) { currTS.emplace_back(std::vector<size_t>{bs, numDirections, hidden_size}); } currTS.emplace_back(std::vector<size_t>{bs}); targetStaticShapes.push_back(currTS); } // funciton creation std::vector<ov::element::Type> types(inputDynamicShapes.size(), netPrecision); types.back() = ElementType::i64; auto params = ngraph::builder::makeDynamicParams(types, inputDynamicShapes); std::vector<int64_t> order_ref_before = {1, 0, 2}; const auto order_before = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape({order_ref_before.size()}), order_ref_before); const auto transpose_before = std::make_shared<ov::op::v1::Transpose>(params[0], order_before); ov::OutputVector inputs; inputs.push_back(transpose_before); for (size_t i = 1; i < params.size(); i++) { inputs.push_back(params[i]); } std::shared_ptr<ov::Node> seq_node; if (seqType == SEQ_TYPE::GRU) { seq_node = ngraph::builder::makeGRU(inputs, weightShape, hidden_size, activations, {}, {}, clip, linearBeforeReset, true, direction, ngraph::helpers::SequenceTestsMode::PURE_SEQ_RAND_SEQ_LEN_PARAM); } else if (seqType == SEQ_TYPE::LSTM) { seq_node = ngraph::builder::makeLSTM(inputs, weightShape, hidden_size, activations, {}, {}, clip, true, direction, ngraph::helpers::SequenceTestsMode::PURE_SEQ_RAND_SEQ_LEN_PARAM); } else if (seqType == SEQ_TYPE::RNN) { seq_node = ngraph::builder::makeRNN(inputs, weightShape, hidden_size, activations, {}, {}, clip, true, direction, ngraph::helpers::SequenceTestsMode::PURE_SEQ_RAND_SEQ_LEN_PARAM); } else { IE_THROW() << "Unsupported seq type"; } std::vector<int64_t> order_ref_after = {2, 1, 0, 3}; const auto order_after = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape({order_ref_after.size()}), order_ref_after); const auto transpose_after = std::make_shared<ov::op::v1::Transpose>(seq_node->output(0), order_after); ov::OutputVector results; results.push_back(transpose_after->output(0)); for (size_t i = 1; i < seq_node->get_output_size(); i++) { results.push_back(seq_node->output(i)); } function = std::make_shared<ov::Model>(results, params, "SequenceCPUTest"); } void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override { SubgraphBaseTest::generate_inputs(targetInputStaticShapes); const size_t batchSize = targetInputStaticShapes[0][1]; const int64_t maxSeqLen = targetInputStaticShapes[0][0]; const auto& funcInputs = function->inputs(); const auto& seqLenInput = inputs.find(funcInputs[seqLengthInIdx].get_node_shared_ptr()); if (seqLenInput == inputs.end()) throw std::runtime_error("Could not find Sequence length input."); auto lenData = seqLenInput->second.data<ov::element_type_traits<ElementType::i64>::value_type>(); std::fill(lenData, lenData + batchSize, maxSeqLen); } private: size_t seqLengthInIdx = 2; }; TEST_P(SequenceCPUTest, CompareWithRefs) { SKIP_IF_CURRENT_TEST_IS_DISABLED() run(); CheckNumberOfNodesWithType(executableNetwork, "RNNSeq", 1); CheckNumberOfNodesWithType(executableNetwork, "Transpose", 0); } const std::vector<SEQ_TYPE> nodeType = { SEQ_TYPE::GRU, SEQ_TYPE::LSTM, SEQ_TYPE::RNN }; const std::vector<size_t> hiddenSizes = { 1, 10 }; const std::vector<size_t> inputSizes = { 1, 10 }; const std::vector<InputShapeParams> inShapeParams = { InputShapeParams{std::vector<ov::Dimension>{-1, -1}, std::vector<TargetShapeParams>{TargetShapeParams{3, 8}, TargetShapeParams{10, 2}}}, InputShapeParams{std::vector<ov::Dimension>{{1, 15}, {1, 15}}, std::vector<TargetShapeParams>{TargetShapeParams{3, 8}, TargetShapeParams{10, 2}}} }; std::vector<std::vector<std::string>> activations = { {"sigmoid", "tanh", "tanh"} }; std::vector<float> clip{0.f}; std::vector<ov::op::RecurrentSequenceDirection> direction = {ov::op::RecurrentSequenceDirection::FORWARD}; std::vector<bool> linearBeforeReset = {true, false}; std::vector<ElementType> netPrecisions = { ElementType::f32 }; INSTANTIATE_TEST_SUITE_P(smoke_SequenceCPUTest, SequenceCPUTest, ::testing::Combine(::testing::ValuesIn(nodeType), ::testing::ValuesIn(hiddenSizes), ::testing::ValuesIn(inputSizes), ::testing::ValuesIn(inShapeParams), ::testing::ValuesIn(activations), ::testing::ValuesIn(clip), ::testing::ValuesIn(linearBeforeReset), ::testing::ValuesIn(direction), ::testing::ValuesIn(netPrecisions)), SequenceCPUTest::getTestCaseName); } // namespace SubgraphTestsDefinitions
44.33
148
0.529138
shaun95
7ebbf675263b8a48bc6ce5c9c43edda6c5720677
1,472
cpp
C++
CleaningService/main.cpp
KamranMackey/cplusplusprojects
1b42afa9b530098dcb9ada8b133c1351ab4c8155
[ "MIT" ]
null
null
null
CleaningService/main.cpp
KamranMackey/cplusplusprojects
1b42afa9b530098dcb9ada8b133c1351ab4c8155
[ "MIT" ]
null
null
null
CleaningService/main.cpp
KamranMackey/cplusplusprojects
1b42afa9b530098dcb9ada8b133c1351ab4c8155
[ "MIT" ]
null
null
null
#include <iostream> int main() { std::cout << "Hello there, welcome to the Cleaning Service!\n\n"; auto small_room_count{0}; std::cout << "Please enter the amount of small rooms you would like cleaned: "; std::cin >> small_room_count; auto large_room_count{0}; std::cout << "Please enter the amount of large rooms you would like cleaned: "; std::cin >> large_room_count; const auto small_room_price{25.0}; const auto large_room_price{35.0}; const auto sales_tax{0.06}; const auto estimate_expiry{30}; std::cout << "\nEstimate for Cleaning Service:\n"; std::cout << "Number of small rooms: " << small_room_count << "\n"; std::cout << "Number of large rooms: " << large_room_count << "\n"; std::cout << "Price per small room: $" << small_room_price << "\n"; std::cout << "Price per large room: $" << large_room_price << "\n"; const auto small_room_total{small_room_price * small_room_count}; const auto large_room_total{large_room_price * large_room_count}; const auto total_cost{small_room_total + large_room_total}; std::cout << "Total Cost: $" << total_cost << "\n"; const auto total_tax{total_cost * sales_tax}; std::cout << "Total Tax: $" << total_tax << "\n"; std::cout << "\n==============================================\n"; const auto total_estimate{total_cost + total_tax}; std::cout << "Total estimate: $" << total_estimate << "\n"; std::cout << "This estimate is valid for " << estimate_expiry << " days." << "\n"; return 0; }
38.736842
83
0.658967
KamranMackey
7ebd99138b259d93d69fc7793560b665a749cdb6
374
cpp
C++
source/code/RigorPhysics/AABBox.cpp
AdamWallberg/RigorPhysics
85da20dbf1f1990f703e2be687b65987fc48386f
[ "MIT" ]
null
null
null
source/code/RigorPhysics/AABBox.cpp
AdamWallberg/RigorPhysics
85da20dbf1f1990f703e2be687b65987fc48386f
[ "MIT" ]
null
null
null
source/code/RigorPhysics/AABBox.cpp
AdamWallberg/RigorPhysics
85da20dbf1f1990f703e2be687b65987fc48386f
[ "MIT" ]
null
null
null
#include "AABBox.h" namespace rg { AABBox::AABBox() : min(ZeroVector) , max(ZeroVector) { } AABBox::AABBox(Vector3 min, Vector3 max) : min(min) , max(max) { } bool AABBox::inside(const Vector3& position) const { return position.x >= min.x && position.x <= max.x && position.y >= min.y && position.y <= max.y && position.z >= min.z && position.z <= max.z; } }
14.384615
50
0.620321
AdamWallberg
7ebdb1bf448696ebfb075de4a3ece125b9b5eb6a
394
cpp
C++
codeforces/round-294/div-2/a_and_b_and_team_training.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
codeforces/round-294/div-2/a_and_b_and_team_training.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
codeforces/round-294/div-2/a_and_b_and_team_training.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <algorithm> #include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int experienced; unsigned int newbies; cin >> experienced >> newbies; cout << min({(experienced + newbies) / 3, experienced, newbies}) << '\n'; return 0; }
15.153846
77
0.65736
Rkhoiwal
7ebf328cffea7816f7cfa0b266b4d49f275c2826
10,759
cpp
C++
esphome/components/pn532/pn532.cpp
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
249
2018-04-07T12:04:11.000Z
2019-01-25T01:11:34.000Z
esphome/components/pn532/pn532.cpp
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
243
2018-04-11T16:37:11.000Z
2019-01-25T16:50:37.000Z
esphome/components/pn532/pn532.cpp
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
40
2018-04-10T05:50:14.000Z
2019-01-25T15:20:36.000Z
#include "pn532.h" #include <memory> #include "esphome/core/log.h" #include "esphome/core/hal.h" // Based on: // - https://cdn-shop.adafruit.com/datasheets/PN532C106_Application+Note_v1.2.pdf // - https://www.nxp.com/docs/en/nxp/application-notes/AN133910.pdf // - https://www.nxp.com/docs/en/nxp/application-notes/153710.pdf namespace esphome { namespace pn532 { static const char *const TAG = "pn532"; void PN532::setup() { ESP_LOGCONFIG(TAG, "Setting up PN532..."); // Get version data if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) { ESP_LOGE(TAG, "Error sending version command"); this->mark_failed(); return; } std::vector<uint8_t> version_data; if (!this->read_response(PN532_COMMAND_VERSION_DATA, version_data)) { ESP_LOGE(TAG, "Error getting version"); this->mark_failed(); return; } ESP_LOGD(TAG, "Found chip PN5%02X", version_data[0]); ESP_LOGD(TAG, "Firmware ver. %d.%d", version_data[1], version_data[2]); if (!this->write_command_({ PN532_COMMAND_SAMCONFIGURATION, 0x01, // normal mode 0x14, // zero timeout (not in virtual card mode) 0x01, })) { ESP_LOGE(TAG, "No wakeup ack"); this->mark_failed(); return; } std::vector<uint8_t> wakeup_result; if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, wakeup_result)) { this->error_code_ = WAKEUP_FAILED; this->mark_failed(); return; } // Set up SAM (secure access module) uint8_t sam_timeout = std::min<uint8_t>(255u, this->update_interval_ / 50); if (!this->write_command_({ PN532_COMMAND_SAMCONFIGURATION, 0x01, // normal mode sam_timeout, // timeout as multiple of 50ms (actually only for virtual card mode, but shouldn't matter) 0x01, // Enable IRQ })) { this->error_code_ = SAM_COMMAND_FAILED; this->mark_failed(); return; } std::vector<uint8_t> sam_result; if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, sam_result)) { ESP_LOGV(TAG, "Invalid SAM result: (%u)", sam_result.size()); // NOLINT for (uint8_t dat : sam_result) { ESP_LOGV(TAG, " 0x%02X", dat); } this->error_code_ = SAM_COMMAND_FAILED; this->mark_failed(); return; } this->turn_off_rf_(); } void PN532::update() { for (auto *obj : this->binary_sensors_) obj->on_scan_end(); if (!this->write_command_({ PN532_COMMAND_INLISTPASSIVETARGET, 0x01, // max 1 card 0x00, // baud rate ISO14443A (106 kbit/s) })) { ESP_LOGW(TAG, "Requesting tag read failed!"); this->status_set_warning(); return; } this->status_clear_warning(); this->requested_read_ = true; } void PN532::loop() { if (!this->requested_read_) return; std::vector<uint8_t> read; bool success = this->read_response(PN532_COMMAND_INLISTPASSIVETARGET, read); this->requested_read_ = false; if (!success) { // Something failed if (!this->current_uid_.empty()) { auto tag = make_unique<nfc::NfcTag>(this->current_uid_); for (auto *trigger : this->triggers_ontagremoved_) trigger->process(tag); } this->current_uid_ = {}; this->turn_off_rf_(); return; } uint8_t num_targets = read[0]; if (num_targets != 1) { // no tags found or too many if (!this->current_uid_.empty()) { auto tag = make_unique<nfc::NfcTag>(this->current_uid_); for (auto *trigger : this->triggers_ontagremoved_) trigger->process(tag); } this->current_uid_ = {}; this->turn_off_rf_(); return; } uint8_t nfcid_length = read[5]; std::vector<uint8_t> nfcid(read.begin() + 6, read.begin() + 6 + nfcid_length); if (read.size() < 6U + nfcid_length) { // oops, pn532 returned invalid data return; } bool report = true; for (auto *bin_sens : this->binary_sensors_) { if (bin_sens->process(nfcid)) { report = false; } } if (nfcid.size() == this->current_uid_.size()) { bool same_uid = true; for (size_t i = 0; i < nfcid.size(); i++) same_uid &= nfcid[i] == this->current_uid_[i]; if (same_uid) return; } this->current_uid_ = nfcid; if (next_task_ == READ) { auto tag = this->read_tag_(nfcid); for (auto *trigger : this->triggers_ontag_) trigger->process(tag); if (report) { ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid(nfcid).c_str()); if (tag->has_ndef_message()) { const auto &message = tag->get_ndef_message(); const auto &records = message->get_records(); ESP_LOGD(TAG, " NDEF formatted records:"); for (const auto &record : records) { ESP_LOGD(TAG, " %s - %s", record->get_type().c_str(), record->get_payload().c_str()); } } } } else if (next_task_ == CLEAN) { ESP_LOGD(TAG, " Tag cleaning..."); if (!this->clean_tag_(nfcid)) { ESP_LOGE(TAG, " Tag was not fully cleaned successfully"); } ESP_LOGD(TAG, " Tag cleaned!"); } else if (next_task_ == FORMAT) { ESP_LOGD(TAG, " Tag formatting..."); if (!this->format_tag_(nfcid)) { ESP_LOGE(TAG, "Error formatting tag as NDEF"); } ESP_LOGD(TAG, " Tag formatted!"); } else if (next_task_ == WRITE) { if (this->next_task_message_to_write_ != nullptr) { ESP_LOGD(TAG, " Tag writing..."); ESP_LOGD(TAG, " Tag formatting..."); if (!this->format_tag_(nfcid)) { ESP_LOGE(TAG, " Tag could not be formatted for writing"); } else { ESP_LOGD(TAG, " Writing NDEF data"); if (!this->write_tag_(nfcid, this->next_task_message_to_write_)) { ESP_LOGE(TAG, " Failed to write message to tag"); } ESP_LOGD(TAG, " Finished writing NDEF data"); delete this->next_task_message_to_write_; this->next_task_message_to_write_ = nullptr; this->on_finished_write_callback_.call(); } } } this->read_mode(); this->turn_off_rf_(); } bool PN532::write_command_(const std::vector<uint8_t> &data) { std::vector<uint8_t> write_data; // Preamble write_data.push_back(0x00); // Start code write_data.push_back(0x00); write_data.push_back(0xFF); // Length of message, TFI + data bytes const uint8_t real_length = data.size() + 1; // LEN write_data.push_back(real_length); // LCS (Length checksum) write_data.push_back(~real_length + 1); // TFI (Frame Identifier, 0xD4 means to PN532, 0xD5 means from PN532) write_data.push_back(0xD4); // calculate checksum, TFI is part of checksum uint8_t checksum = 0xD4; // DATA for (uint8_t dat : data) { write_data.push_back(dat); checksum += dat; } // DCS (Data checksum) write_data.push_back(~checksum + 1); // Postamble write_data.push_back(0x00); this->write_data(write_data); return this->read_ack_(); } bool PN532::read_ack_() { ESP_LOGV(TAG, "Reading ACK..."); std::vector<uint8_t> data; if (!this->read_data(data, 6)) { return false; } bool matches = (data[1] == 0x00 && // preamble data[2] == 0x00 && // start of packet data[3] == 0xFF && data[4] == 0x00 && // ACK packet code data[5] == 0xFF && data[6] == 0x00); // postamble ESP_LOGV(TAG, "ACK valid: %s", YESNO(matches)); return matches; } void PN532::send_nack_() { ESP_LOGV(TAG, "Sending NACK for retransmit"); this->write_data({0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00}); delay(10); } void PN532::turn_off_rf_() { ESP_LOGV(TAG, "Turning RF field OFF"); this->write_command_({ PN532_COMMAND_RFCONFIGURATION, 0x01, // RF Field 0x00, // Off }); } std::unique_ptr<nfc::NfcTag> PN532::read_tag_(std::vector<uint8_t> &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { ESP_LOGD(TAG, "Mifare classic"); return this->read_mifare_classic_tag_(uid); } else if (type == nfc::TAG_TYPE_2) { ESP_LOGD(TAG, "Mifare ultralight"); return this->read_mifare_ultralight_tag_(uid); } else if (type == nfc::TAG_TYPE_UNKNOWN) { ESP_LOGV(TAG, "Cannot determine tag type"); return make_unique<nfc::NfcTag>(uid); } else { return make_unique<nfc::NfcTag>(uid); } } void PN532::read_mode() { this->next_task_ = READ; ESP_LOGD(TAG, "Waiting to read next tag"); } void PN532::clean_mode() { this->next_task_ = CLEAN; ESP_LOGD(TAG, "Waiting to clean next tag"); } void PN532::format_mode() { this->next_task_ = FORMAT; ESP_LOGD(TAG, "Waiting to format next tag"); } void PN532::write_mode(nfc::NdefMessage *message) { this->next_task_ = WRITE; this->next_task_message_to_write_ = message; ESP_LOGD(TAG, "Waiting to write next tag"); } bool PN532::clean_tag_(std::vector<uint8_t> &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { return this->format_mifare_classic_mifare_(uid); } else if (type == nfc::TAG_TYPE_2) { return this->clean_mifare_ultralight_(); } ESP_LOGE(TAG, "Unsupported Tag for formatting"); return false; } bool PN532::format_tag_(std::vector<uint8_t> &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { return this->format_mifare_classic_ndef_(uid); } else if (type == nfc::TAG_TYPE_2) { return this->clean_mifare_ultralight_(); } ESP_LOGE(TAG, "Unsupported Tag for formatting"); return false; } bool PN532::write_tag_(std::vector<uint8_t> &uid, nfc::NdefMessage *message) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { return this->write_mifare_classic_tag_(uid, message); } else if (type == nfc::TAG_TYPE_2) { return this->write_mifare_ultralight_tag_(uid, message); } ESP_LOGE(TAG, "Unsupported Tag for formatting"); return false; } float PN532::get_setup_priority() const { return setup_priority::DATA; } void PN532::dump_config() { ESP_LOGCONFIG(TAG, "PN532:"); switch (this->error_code_) { case NONE: break; case WAKEUP_FAILED: ESP_LOGE(TAG, "Wake Up command failed!"); break; case SAM_COMMAND_FAILED: ESP_LOGE(TAG, "SAM command failed!"); break; } LOG_UPDATE_INTERVAL(this); for (auto *child : this->binary_sensors_) { LOG_BINARY_SENSOR(" ", "Tag", child); } } bool PN532BinarySensor::process(std::vector<uint8_t> &data) { if (data.size() != this->uid_.size()) return false; for (size_t i = 0; i < data.size(); i++) { if (data[i] != this->uid_[i]) return false; } this->publish_state(true); this->found_ = true; return true; } } // namespace pn532 } // namespace esphome
28.164921
114
0.636676
OttoWinter
7ec4d9509feb5da68609c9181629b63d62a508f6
1,361
hpp
C++
modules/memory/include/shard/memory/allocators/proxy_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/memory/include/shard/memory/allocators/proxy_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/memory/include/shard/memory/allocators/proxy_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Miklos Molnar. All rights reserved. #ifndef SHARD_MEMORY_PROXY_ALLOCATOR_HPP #define SHARD_MEMORY_PROXY_ALLOCATOR_HPP #include "shard/memory/allocator.hpp" namespace shard { namespace memory { class proxy_allocator : public allocator { public: explicit proxy_allocator(allocator& a, const char* name = "") : allocator(a.size()), m_allocator(a), m_name(name) {} void* allocate(std::size_t size, std::size_t align) override { assert(size != 0); ++m_allocation_count; auto used = m_allocator.used_memory(); auto ptr = m_allocator.allocate(size, align); // calculate the actual size of the allocation, because an allocation // might allocate more memory than requested m_used_memory += m_allocator.used_memory() - used; return ptr; } void deallocate(void* ptr) override { assert(ptr); --m_allocation_count; auto used = m_allocator.used_memory(); m_allocator.deallocate(ptr); m_used_memory -= used - m_allocator.used_memory(); } const char* name() const { return m_name; } private: allocator& m_allocator; const char* m_name = nullptr; }; } // namespace memory // bring symbols into parent namespace using memory::proxy_allocator; } // namespace shard #endif // SHARD_MEMORY_PROXY_ALLOCATOR_HPP
27.22
120
0.685525
ikimol
7ec6e7ee9fa50cc4c88daa4da11ef22913527637
1,356
cc
C++
solutions/cses/graph/1192.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
4
2020-11-07T14:38:02.000Z
2022-01-03T19:02:36.000Z
solutions/cses/graph/1192.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
1
2019-04-17T06:55:14.000Z
2019-04-17T06:55:14.000Z
solutions/cses/graph/1192.cc
zwliew/ctci
871f4fc957be96c6d0749d205549b7b35dc53d9e
[ "MIT" ]
null
null
null
#include <stdio.h> #include <algorithm> #include <array> #include <bitset> #include <cassert> #include <climits> #include <cmath> #include <deque> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <numeric> #include <queue> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; using ll = long long; using ld = long double; void dfs(vector<vector<bool>> &grid, int r, int c) { const vector<pair<int, int>> edges = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (auto &[dr, dc] : edges) { int nr = r + dr; int nc = c + dc; if (nc < 0 || nr < 0 || nr >= grid.size() || nc >= grid[0].size()) continue; if (!grid[nr][nc]) continue; grid[nr][nc] = 0; dfs(grid, nr, nc); } } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); // Count the number of connected components int n, m; cin >> n >> m; vector<vector<bool>> grid(n, vector<bool>(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { char c; cin >> c; grid[i][j] = c == '.'; } } int count = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j]) { grid[i][j] = 0; ++count; dfs(grid, i, j); } } } cout << count; }
19.371429
80
0.538348
zwliew
7ec6f3bc2059f607ad2b9d87847209ad89536709
17,705
cpp
C++
svntrunk/src/pk/reactor/src/udp_reactor.cpp
Bhaskers-Blu-Org1/BlueMatter
1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e
[ "BSD-2-Clause" ]
7
2020-02-25T15:46:18.000Z
2022-02-25T07:04:47.000Z
svntrunk/src/pk/reactor/src/udp_reactor.cpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
null
null
null
svntrunk/src/pk/reactor/src/udp_reactor.cpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
5
2019-06-06T16:30:21.000Z
2020-11-16T19:43:01.000Z
/* Copyright 2001, 2019 IBM Corporation * * 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. */ /*************************************************************************** * Project: pK * * Module: mpi_reactor.cpp * * Purpose: active packet driver based on mpi * * Classification: IBM Internal Use Only * * History: 020201 BGF Createed from reactor.cpp ... 010297 BGF Created. * ***************************************************************************/ #include <pk/platform.hpp> #include <pk/fxlogger.hpp> #include "buffer.cpp" #ifndef PKTRACE_REACTOR #define PKTRACE_REACTOR (0) #endif #ifndef PKFXLOG_REACTOR #define PKFXLOG_REACTOR (0) #endif //*************************************** char BCAST_ADDR[] = "224.0.0.1"; int OUR_PORT = 8887; #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <sys/socket.h> #include <stream.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pk/platform.hpp> #include <pk/ThreadCreate.hpp> // It's a little backwards that this file gets this info from the platform header file. enum { PK_UDP_PACKET_PAYLOAD_SIZE = Platform::Reactor::BROADCAST_PAYLOAD_SIZE + 32 }; typedef double ReactorPacketAlignmentType; // Note: we use MPI Task id's for now, but would could/should map back from UDP's knowledge of the sender's IP address. typedef unsigned short MpiTaskId; typedef unsigned short SeqNoType; // Receive window needs to be a power of 2 const SeqNoType RECEIVE_WINDOW_MASK = 0x000F ; const SeqNoType RECEIVE_WINDOW_SIZE = RECEIVE_WINDOW_MASK + 1 ; struct UdpReactorPacket { struct tHeader { Platform::Reactor::FunctionPointerType mFxPtr; SeqNoType mSeqNo; MpiTaskId mSourceTaskId; } ; enum { PAYLOAD_SIZE = ( PK_UDP_PACKET_PAYLOAD_SIZE - sizeof( tHeader ) ) }; enum { PAYLOAD_ARRAY_COUNT = PAYLOAD_SIZE / (sizeof(ReactorPacketAlignmentType) ) }; tHeader Header; ReactorPacketAlignmentType mPayload[ PAYLOAD_ARRAY_COUNT ]; }; Platform::Mutex::MutexWord UdpReactorUp; void * ReactorThread( void * ) { BegLogLine(1) << "Server running on " << Platform::Topology::GetAddressSpaceId() << EndLogLine; int sockfd; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_DGRAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(OUR_PORT); int bindrc = bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); if( bindrc < 0 ) { BegLogLine(1) << "ReactorThread bind() failed. rc = " << bindrc << " errno " << errno << EndLogLine; PLATFORM_ABORT( "ReactorThread() Bind failed" ); } int n; socklen_t len; n = 1024 * 1024; int setsockoptrc = setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n)); if( setsockoptrc != 0 ) { BegLogLine(1) << "ReactorThread setsockopt() to set rcv buffers failed. rc = " << setsockoptrc << " Buffer request " << n << "kb " << " errno " << errno << EndLogLine; PLATFORM_ABORT( "ReactorThread() setsockopt failed" ); } enum { MaxUdpNodes = 256 }; SeqNoType HighestSeqNo[ MaxUdpNodes ]; for( int i = 0; i < MaxUdpNodes; i++ ) HighestSeqNo[ i ] = 0; // Prime windowing SeqNoType RecvWindow[ MaxUdpNodes ][ RECEIVE_WINDOW_SIZE ]; for( int n = 0; n < MaxUdpNodes; n++ ) for( int i = 0; i < RECEIVE_WINDOW_SIZE; i++ ) RecvWindow[ n ][ i ] = i ; struct sockaddr cliaddr; len = sizeof( cliaddr ); // NEED TO HOOK IN UNDERSTANDING ABOUT PACKET SIZE UdpReactorPacket * urppkt = (UdpReactorPacket *) Platform::Reactor::GetBuffer(); // Unlocking this mutex signals that we are ready to run Platform::Mutex::Unlock( UdpReactorUp ); for ( ; ; ) { n = recvfrom(sockfd, (void *) urppkt, sizeof( UdpReactorPacket ), 0, &cliaddr, &len); int PacketSource = urppkt->Header.mSourceTaskId; SeqNoType PacketSeqNo = urppkt->Header.mSeqNo; if( PacketSeqNo != HighestSeqNo[ PacketSource ] ) { BegLogLine(0) << "OUT OF ORDER - got " << PacketSource << ":" << PacketSeqNo << " Expected " << PacketSource << ":" << HighestSeqNo[ PacketSource ] << EndLogLine; /// PLATFORM_ABORT( "udp_reactor::ReactorThread(): LOST BROADCAST PACKET " ) } if( PacketSeqNo >= HighestSeqNo[ PacketSource ] ) HighestSeqNo[ PacketSource ] = PacketSeqNo + 1; int windex = PacketSeqNo & RECEIVE_WINDOW_MASK; if( RecvWindow[ PacketSource ][ windex ] != PacketSeqNo ) { BegLogLine(1) << "LOST A PACKET " << " windex " << windex << " PacketSource " << PacketSource << " RecvWindow[S][w] " << RecvWindow[ PacketSource ][ windex ] << " PacketSeqNo " << PacketSeqNo << " WINDOW IS " << RECEIVE_WINDOW_SIZE << EndLogLine; PLATFORM_ABORT( "udp_reactor::ReactorThread(): LOST BROADCAST PACKET " ) } RecvWindow[ PacketSource ][ windex ] = PacketSeqNo + RECEIVE_WINDOW_SIZE; int ReactorRc = urppkt->Header.mFxPtr( (void *) urppkt->mPayload ); switch( ReactorRc ) { case 0 : break; case 1 : // Replace packet buffer since the last one was kept by the application urppkt = (UdpReactorPacket *) Platform::Reactor::GetBuffer(); break; default: assert( 0 ); }; BegLogLine(0) << "Server " << Platform::Topology::GetAddressSpaceId() << " Recieved task:seqno " << PacketSource << ":" << PacketSeqNo << EndLogLine; } } int bcast_sockfd; struct sockaddr *bcast_servaddr; socklen_t bcast_servlen; void reactorInitialize() { BegLogLine(1) << "UdpReactorInitialize " << "Starting " << EndLogLine; static struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(OUR_PORT); int rc = inet_pton(AF_INET, BCAST_ADDR, &servaddr.sin_addr); assert( rc > 0 ); bcast_sockfd = socket(AF_INET, SOCK_DGRAM, 0); bcast_servaddr = (struct sockaddr *) &servaddr; bcast_servlen = sizeof( servaddr ); int n; const int on = 1; setsockopt(bcast_sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); BegLogLine(1) << "Udp bcast packet max size " << sizeof( UdpReactorPacket ) << " UdpReactorPacket::PAYLOAD_ARRAY_COUNT " << UdpReactorPacket::PAYLOAD_ARRAY_COUNT << " UdpReactorPacket::PAYLOAD_SIZE " << UdpReactorPacket::PAYLOAD_SIZE << " sizeof( ReactorPacketAlignmentType ) " << sizeof( ReactorPacketAlignmentType ) << EndLogLine; BegLogLine(1) << "UdpReactorInitialize " << "Finished " << EndLogLine; } SeqNoType BroadcastSenderSeqNo = 0; int Platform::Reactor::Trigger( Platform::Reactor::FunctionPointerType aFxPtr, void *aMsg, unsigned aMsgLen) { UdpReactorPacket urppkt; /// bzero( &urppkt, sizeof( urppkt ) ); // THIS MUST BE MADE THREAD SAFE urppkt.Header.mSeqNo = BroadcastSenderSeqNo; BroadcastSenderSeqNo++; urppkt.Header.mSourceTaskId = Platform::Topology::GetAddressSpaceId(); urppkt.Header.mFxPtr = aFxPtr; if( aMsgLen > Platform::Reactor::BROADCAST_PAYLOAD_SIZE ) { BegLogLine(1) << "Trigger() Bcast " << " aMsgLen to long " << aMsgLen << " Platform::Reactor::BROADCAST_PAYLOAD_SIZE " << Platform::Reactor::BROADCAST_PAYLOAD_SIZE << EndLogLine; PLATFORM_ABORT( "BCast Trigger aMsgLen > Platform::Reactor::BROADCAST_PAYLOAD_SIZE" ); } memcpy( (void *)(urppkt.mPayload), aMsg, aMsgLen ); int urplen = sizeof( urppkt.Header ) + aMsgLen; BegLogLine( 0 ) << "Trigger() Bcast " << "SeqNo " << urppkt.Header.mSeqNo << " Reactor @" << (void *) urppkt.Header.mFxPtr << " TMsg Len " << urplen << " Msg data: " << urppkt.mPayload[0] << EndLogLine; sendto(bcast_sockfd, &urppkt, urplen, 0, bcast_servaddr, bcast_servlen); } //****************************************** MPI_Comm REACTIVE_MESSAGE_COMM_WORLD; BufferPtr *AllBuf ; // A pointer to an array of pointers. MPI_Request *AllRequests; MPI_Status *AllStatus ; #ifndef PKREACTOR_DATAGRAMS_PER_TASK_IN_FLIGHT #define PKREACTOR_DATAGRAMS_PER_TASK_IN_FLIGHT (64) // 64 * (say)32KB == 2MB commited. #endif #define TOTAL_DATAGRAMS_IN_FLIGHT \ (PKREACTOR_DATAGRAMS_PER_TASK_IN_FLIGHT * Platform::Topology::GetAddressSpaceCount()) //----------------------------------------------------------------------------- // This constructor is called during the init of the // pk. It can be assumed to be running in all tasks. void ReactorInitialize() { BegLogLine( PKFXLOG_REACTOR ) << "ReactorInitialize() in Task [" << Platform::Topology::GetAddressSpaceId() << "]" << EndLogLine; for( int bpi = 0; bpi < FREE_BUFFER_POOL_SIZE; bpi++ ) //Initialise buffer pool FreeBufferPool[bpi] = NULL; FreeBufferPoolCount = 0; FreeBufferPoolLockWord = 0; AllBuf = new BufferPtr[TOTAL_DATAGRAMS_IN_FLIGHT ]; //Initialise an array of buffers assert( AllBuf != NULL ); // based on the maximum number of // packets being sent at once. for( int i = 0; i < (TOTAL_DATAGRAMS_IN_FLIGHT); i++ ) { AllBuf[i] = (BufferPtr) Platform::Reactor::GetBuffer(); } AllRequests = new MPI_Request [ TOTAL_DATAGRAMS_IN_FLIGHT ]; // AllStatus = new MPI_Status [ TOTAL_DATAGRAMS_IN_FLIGHT ]; // MPI_Group REACTIVE_MESSAGE_GROUP; MPI_Comm_group( MPI_COMM_WORLD, &REACTIVE_MESSAGE_GROUP); //Make REACTIVE_MESSAGE_GROUP //a group with all processes. MPI_Comm_create( MPI_COMM_WORLD, REACTIVE_MESSAGE_GROUP, //Create a new communicator called &REACTIVE_MESSAGE_COMM_WORLD); // REACTIVE_MESSAGE_COMM_WORLD that includes // all processes in REACTIVE_MESSAGE_GROUP. int t; for( t = 0; t<TOTAL_DATAGRAMS_IN_FLIGHT;t++) { int msgrc; msgrc = MPI_Irecv( (void *) AllBuf[t], //Post non-blocking receive for sizeof( Buffer ), // each request. MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, REACTIVE_MESSAGE_COMM_WORLD, &AllRequests[t]); } for( ; t < TOTAL_DATAGRAMS_IN_FLIGHT; t++ ) //Initialise requests to NULL { AllRequests[t] = MPI_REQUEST_NULL; } //NEED: might want to ponder this here even in MPI world. MPI_Barrier( REACTIVE_MESSAGE_COMM_WORLD ); //Wait for all processes to get here. // Do the udp bcast driver now reactorInitialize(); MPI_Barrier( REACTIVE_MESSAGE_COMM_WORLD ); //Wait for all processes to get here. } //----------------------------------------------------------------------------- int Platform::Reactor:: Trigger( int TaskNo, Platform::Reactor::FunctionPointerType FxPtr, void *Msg, unsigned MsgLen) { assert( MsgLen <= Platform::Reactor::PAYLOAD_SIZE ); int mpirc; assert( MsgLen <= sizeof( Buffer ) ); BegLogLine( PKFXLOG_REACTOR ) << "Trigger() Before Send ActiveMsg To Task " << TaskNo << " Reactor @" << (unsigned) FxPtr << " TMsg Len " << MsgLen << " Msg data: " << (void *) (*((int*)Msg)) << EndLogLine; mpirc = MPI_Send(Msg, MsgLen, MPI_CHAR, // Send data and function pointer to TaskNo, // specified task. (int) FxPtr, REACTIVE_MESSAGE_COMM_WORLD ); assert( mpirc == 0 ); BegLogLine( PKFXLOG_REACTOR ) << "Trigger() After Send ActiveMsg To Task " << Platform::Topology::GetAddressSpaceId() << " Reactor @" << (unsigned) FxPtr << " TMsg Len " << MsgLen << " Msg data: " << (void *) (*((int*)Msg)) << EndLogLine; if( mpirc != 0 ) { MPI_Abort( REACTIVE_MESSAGE_COMM_WORLD, mpirc ); } return( mpirc ); } extern "C" { void trcon(int) ; void trcoff(int) ; } ; //----------------------------------------------------------------------------- ///int adummyarg; void* ReactorThreadMain( void *arg ) //This goes round and round and round........... { // if( ! Platform::Mutex::TryLock( UdpReactorUp ) ) // PLATFORM_ABORT( "Unable to get UdpReactorUp lock" ); /// Platform::Thread::Create( ReactorThread, NULL ); /// ThreadCreate( -1, ReactorThread, 0, NULL ); // Platform::Mutex::YieldLock( UdpReactorUp ); int mpirc; int ReactorRc; MPI_Barrier( MPI_COMM_WORLD ); //Wait for all processes to get here. BegLogLine( PKFXLOG_REACTOR ) << " PhysicalThread ... Running ..." << "ActiveMsg Processor: " << EndLogLine; // Continuous loop for(int d = 0; (1) ; d++) { unsigned msgrc; MPI_Status Status; //Always do this int ReqIndex; BegLogLine( PKFXLOG_REACTOR ) << "ActiveMsg Processor: " << " Testany()/usleep() for incomming " << EndLogLine; int Flag = 0; //NEED to encapsulate this function as a yield function. for( int PollCount = 0; Flag == 0; PollCount++ ) //Loop until a request is complete { mpirc = MPI_Testany(TOTAL_DATAGRAMS_IN_FLIGHT, AllRequests, &ReqIndex, &Flag, &Status); assert( mpirc == 0); if( ! Flag ) { if( PollCount < (64 * 1024) ) // the reactor should be the last to sleep Platform::Thread::Yield(); else usleep( 10000 ); // and sleep less long. } } int Len; MPI_Get_count( &Status, MPI_CHAR, &Len );//Use Status retuurned above to get message length. BegLogLine( PKFXLOG_REACTOR ) << "ActiveMsg Processor: Got one! " << " Before call Fx @" << MPI_STATUS_TAG( Status ) << " Src " << MPI_STATUS_SOURCE( Status ) << " Len " << Len << " Data " << AllBuf[ReqIndex] << EndLogLine; // THIS IS THE POINT WHERE ACTIVE PACKET FUNCTIONS ARE EXECUTED ReactorRc = ((Platform::Reactor::FunctionPointerType)((MPI_STATUS_TAG( Status ))))( AllBuf[ReqIndex] ); switch( ReactorRc ) { case 0 : break; case 1 : AllBuf[ReqIndex] = Platform::Reactor::GetBuffer(); //buffer so we make a new one. break; default: assert( 0 ); }; BegLogLine( PKFXLOG_REACTOR ) << "ActiveMsg Processor: Did one! " << "After call Fx() @" << (MPI_STATUS_TAG( Status )) << " Src " << MPI_STATUS_SOURCE( Status ) << " Len " << Len << " Data " << AllBuf[ReqIndex] << EndLogLine; msgrc = MPI_Irecv( (void *) AllBuf[ReqIndex], //Post a non-blocking receive on the sizeof( Buffer ), //buffer we just used. MPI_CHAR, MPI_ANY_SOURCE, MPI_ANY_TAG, REACTIVE_MESSAGE_COMM_WORLD, &AllRequests[ReqIndex] ); assert( msgrc == 0 ); if( msgrc != 0 ) { //Pprintf("Reactive Message Subsystem: MPI_Irecv failed \n"); MPI_Abort( MPI_COMM_WORLD, -1); } } MPI_Finalize(); _exit(0); return( NULL ); // Keep compiler quiet }
29.216172
119
0.578876
Bhaskers-Blu-Org1
7eca9af2de615d15fc20145673768b53402310d4
1,182
cpp
C++
SYCL/ESIMD/api/simd_view_select_2d_fp.cpp
abuyukku/llvm-test-suite
b10bd8e733519ae0e365fc097d36a32bc1d53d62
[ "Apache-2.0" ]
null
null
null
SYCL/ESIMD/api/simd_view_select_2d_fp.cpp
abuyukku/llvm-test-suite
b10bd8e733519ae0e365fc097d36a32bc1d53d62
[ "Apache-2.0" ]
null
null
null
SYCL/ESIMD/api/simd_view_select_2d_fp.cpp
abuyukku/llvm-test-suite
b10bd8e733519ae0e365fc097d36a32bc1d53d62
[ "Apache-2.0" ]
null
null
null
//==------- simd_view_select_2d_fp.cpp - DPC++ ESIMD on-device test -------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // REQUIRES: gpu // UNSUPPORTED: cuda || hip // TODO: esimd_emulator fails due to unimplemented 'single_task()' method // XFAIL: esimd_emulator // RUN: %clangxx -fsycl %s -fsycl-device-code-split=per_kernel -o %t.out // RUN: %GPU_RUN_PLACEHOLDER %t.out // // Smoke test for 2D region select API which can be used to represent 2D tiles. // Tests FP types. #include "simd_view_select_2d.hpp" int main(int argc, char **argv) { queue q(esimd_test::ESIMDSelector{}, esimd_test::createExceptionHandler()); auto dev = q.get_device(); std::cout << "Running on " << dev.get_info<info::device::name>() << "\n"; bool passed = true; passed &= test<half>(q); passed &= test<float>(q); passed &= test<double>(q); std::cout << (passed ? "=== Test passed\n" : "=== Test FAILED\n"); return passed ? 0 : 1; }
35.818182
80
0.624365
abuyukku
7ecee9489877f779275d42e982ef16f748aa2761
4,798
cc
C++
src/media/codec/examples/use_media_decoder/in_stream_buffer.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/media/codec/examples/use_media_decoder/in_stream_buffer.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/media/codec/examples/use_media_decoder/in_stream_buffer.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2020 The Fuchsia 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 "in_stream_buffer.h" #include <algorithm> #include <atomic> #include <iostream> InStreamBuffer::InStreamBuffer(async::Loop* fidl_loop, thrd_t fidl_thread, sys::ComponentContext* component_context, std::unique_ptr<InStream> in_stream_to_wrap, uint64_t max_buffer_size) : InStream(fidl_loop, fidl_thread, component_context), in_stream_(std::move(in_stream_to_wrap)), max_buffer_size_(max_buffer_size) { ZX_DEBUG_ASSERT(in_stream_); ZX_DEBUG_ASSERT(max_buffer_size_ != 0); // InStreamFile knows the EOS from the start. PropagateEosKnown(); } InStreamBuffer::~InStreamBuffer() { // nothing to do here // ~data_ } zx_status_t InStreamBuffer::ReadBytesInternal(uint32_t max_bytes_to_read, uint32_t* bytes_read_out, uint8_t* buffer_out, zx::time just_fail_deadline) { ZX_DEBUG_ASSERT(thrd_current() != fidl_thread_); ZX_DEBUG_ASSERT(!failure_seen_); uint64_t bytes_to_read = max_bytes_to_read; if (eos_position_known_) { bytes_to_read = std::min(bytes_to_read, eos_position_ - cursor_position_); } bytes_to_read = std::min(bytes_to_read, max_buffer_size_ - valid_bytes_); if (cursor_position_ + bytes_to_read > valid_bytes_) { zx_status_t status = ReadMoreIfPossible(cursor_position_ + bytes_to_read - valid_bytes_, just_fail_deadline); if (status != ZX_OK) { ZX_DEBUG_ASSERT(failure_seen_); return status; } } bytes_to_read = std::min(bytes_to_read, valid_bytes_ - cursor_position_); ZX_DEBUG_ASSERT(cursor_position_ + bytes_to_read <= valid_bytes_); memcpy(buffer_out, data_.data() + cursor_position_, bytes_to_read); *bytes_read_out = bytes_to_read; return ZX_OK; } zx_status_t InStreamBuffer::ResetToStartInternal(zx::time just_fail_deadline) { ZX_DEBUG_ASSERT(thrd_current() != fidl_thread_); ZX_DEBUG_ASSERT(!failure_seen_); ZX_DEBUG_ASSERT(eos_position_known_ == in_stream_->eos_position_known()); ZX_DEBUG_ASSERT(!eos_position_known_ || eos_position_ == in_stream_->eos_position()); cursor_position_ = 0; return ZX_OK; } zx_status_t InStreamBuffer::ReadMoreIfPossible(uint32_t bytes_to_read_if_possible, zx::time just_fail_deadline) { ZX_DEBUG_ASSERT(thrd_current() != fidl_thread_); ZX_DEBUG_ASSERT(!failure_seen_); ZX_DEBUG_ASSERT(bytes_to_read_if_possible != 0); ZX_ASSERT(max_buffer_size_ > valid_bytes_); ZX_DEBUG_ASSERT(eos_position_known_ == in_stream_->eos_position_known()); ZX_DEBUG_ASSERT(!eos_position_known_ || eos_position_ == in_stream_->eos_position()); ZX_DEBUG_ASSERT(!eos_position_known_ || valid_bytes_ + bytes_to_read_if_possible <= eos_position_); ZX_DEBUG_ASSERT(valid_bytes_ + bytes_to_read_if_possible <= max_buffer_size_); if (in_stream_->eos_position_known() && (in_stream_->cursor_position() == in_stream_->eos_position())) { ZX_DEBUG_ASSERT(valid_bytes_ == eos_position_); // Not possible to read more because there isn't any more. Not a failure. return ZX_OK; } // Make room. if (data_.size() < valid_bytes_ + bytes_to_read_if_possible) { // Need to resize exponentially to avoid O(N^2) overall, but cap at max_buffer_size_. uint64_t new_size = std::max(data_.size() * 2, static_cast<size_t>(1)); new_size = std::max(new_size, valid_bytes_ + bytes_to_read_if_possible); new_size = std::min(new_size, max_buffer_size_); data_.resize(new_size); } uint32_t actual_bytes_read; zx_status_t status = in_stream_->ReadBytesShort(bytes_to_read_if_possible, &actual_bytes_read, data_.data() + valid_bytes_, just_fail_deadline); if (status != ZX_OK) { printf("InStreamBuffer::ReadMoreIfPossible() in_stream_->ReadBytesShort() failed status: %d\n", status); ZX_DEBUG_ASSERT(!failure_seen_); failure_seen_ = true; return status; } valid_bytes_ += actual_bytes_read; PropagateEosKnown(); return ZX_OK; } void InStreamBuffer::PropagateEosKnown() { if (in_stream_->eos_position_known()) { if (!eos_position_known_) { eos_position_ = in_stream_->eos_position(); eos_position_known_ = true; } else { ZX_DEBUG_ASSERT(eos_position_ == in_stream_->eos_position()); } } // Not intended for use in situations where whole in_stream_to_wrap doesn't fit in buffer. ZX_ASSERT(!eos_position_known_ || eos_position_ <= max_buffer_size_); ZX_ASSERT(!eos_position_known_ || valid_bytes_ <= eos_position_); }
39.327869
99
0.713839
allansrc
7ed312ce24f292fc67bf7e568395df052560d8ae
4,291
cpp
C++
src/selectappdialog.cpp
FinchX/loli_profiler
9391bb82fd0a26c5855770974ae886f42daf4266
[ "BSD-2-Clause" ]
388
2021-03-11T04:20:19.000Z
2022-03-29T05:55:07.000Z
src/selectappdialog.cpp
habbyge/loli_profiler
fc5700acd5ee034698da2fff1189e58873721711
[ "BSD-2-Clause" ]
23
2021-03-24T06:38:29.000Z
2022-03-30T06:17:17.000Z
src/selectappdialog.cpp
habbyge/loli_profiler
fc5700acd5ee034698da2fff1189e58873721711
[ "BSD-2-Clause" ]
44
2021-03-11T06:27:02.000Z
2022-03-28T03:58:09.000Z
#include "selectappdialog.h" #include <QVBoxLayout> #include <QListWidget> #include <QKeyEvent> ArrowLineEdit::ArrowLineEdit(QListWidget* listView, QWidget *parent) : QLineEdit(parent), listView_(listView) { connect(this, &QLineEdit::textChanged, this, &ArrowLineEdit::onTextChanged); } void ArrowLineEdit::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { auto selectedItems = listView_->selectedItems(); QListWidgetItem* item = nullptr; if (selectedItems.count() > 0) { auto currentRow = listView_->row(selectedItems[0]); if (event->key() == Qt::Key_Down) { while (currentRow + 1 < listView_->count()) { currentRow++; auto curItem = listView_->item(currentRow); if (!curItem->isHidden()) { item = curItem; break; } } } else { while (currentRow - 1 >= 0) { currentRow--; auto curItem = listView_->item(currentRow); if (!curItem->isHidden()) { item = curItem; break; } } } } if (item) listView_->setCurrentItem(item); } else if (event->key() == Qt::Key_Right) { auto selectedItems = listView_->selectedItems(); if (selectedItems.count() > 0) { setText(selectedItems[0]->text()); } } else { QLineEdit::keyPressEvent(event); } } void ArrowLineEdit::onTextChanged(const QString& text) { // Use regular expression to search fuzzily // "Hello\n" -> ".*H.*e.*l.*l.*o.*\\.*n" QString pattern; for (auto i = 0; i < text.size(); i++) { pattern += QRegularExpression::escape(text[i]); if (i != text.size() - 1) pattern += ".*"; } QRegularExpression re(pattern, QRegularExpression::CaseInsensitiveOption); auto first = true; for (int i = 0; i < listView_->count(); ++i) { auto item = listView_->item(i); if (item->text().contains(re)) { item->setHidden(false); item->setSelected(first); first = false; } else { item->setHidden(true); item->setSelected(false); } } } SelectAppDialog::SelectAppDialog(QWidget *parent , Qt::WindowFlags f) : QDialog(parent, f) { auto layout = new QVBoxLayout(); layout->setMargin(2); layout->setSpacing(2); listWidget_ = new QListWidget(); listWidget_->setSelectionMode(QListWidget::SelectionMode::SingleSelection); auto hbLayout = new QHBoxLayout(); searchLineEdit_ = new ArrowLineEdit(listWidget_); connect(searchLineEdit_, &QLineEdit::returnPressed, [this]() { auto selected = listWidget_->selectedItems(); if (selected.count() > 0 && callback_) callback_(selected[0]->text(), subProcessNameLineEdit_->text()); close(); }); connect(listWidget_, &QListWidget::itemClicked, [this](QListWidgetItem *item) { callback_(item->text(), subProcessNameLineEdit_->text()); close(); }); subProcessNameLineEdit_ = new QLineEdit(); subProcessNameLineEdit_->setPlaceholderText("subProcessName"); hbLayout->addWidget(searchLineEdit_); hbLayout->addWidget(subProcessNameLineEdit_); hbLayout->setStretchFactor(searchLineEdit_, 2); hbLayout->setStretchFactor(subProcessNameLineEdit_, 1); layout->addLayout(hbLayout); layout->addWidget(listWidget_); searchLineEdit_->setFocus(); setLayout(layout); setWindowModality(Qt::WindowModal); setWindowTitle("Selection Application"); setMinimumSize(400, 300); resize(400, 300); } void SelectAppDialog::SelectApp(QStringList apps, std::function<void(const QString&, const QString&)> outCallback) { listWidget_->clear(); for (auto& app : apps) { auto lineParts = app.split(':'); if (lineParts.count() > 1) { listWidget_->addItem(lineParts[1].trimmed()); } } listWidget_->setCurrentItem(listWidget_->item(0)); callback_ = outCallback; }
35.172131
116
0.582149
FinchX
7ed9f7f322642e5063a174aea77f62f59d93c87f
9,515
cpp
C++
test/inventory_test.cpp
YADRO-KNS/obmc-yadro-lsinventory
2b52c92669d35500d3ad2f0c656dab5c9bec1625
[ "Apache-2.0" ]
null
null
null
test/inventory_test.cpp
YADRO-KNS/obmc-yadro-lsinventory
2b52c92669d35500d3ad2f0c656dab5c9bec1625
[ "Apache-2.0" ]
2
2020-04-22T07:32:25.000Z
2022-03-10T09:40:32.000Z
test/inventory_test.cpp
YADRO-KNS/obmc-yadro-lsinventory
2b52c92669d35500d3ad2f0c656dab5c9bec1625
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 // Copyright (C) 2020 YADRO #include "inventory.hpp" #include <sdbusplus/test/sdbus_mock.hpp> using ::testing::_; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; /** * class InventoryTest * @brief Inventory tests. */ class InventoryTest : public ::testing::Test { protected: InventoryTest() : bus(sdbusplus::get_mocked_new(&mock)) {} testing::NiceMock<sdbusplus::SdBusMock> mock; sdbusplus::bus::bus bus; }; TEST_F(InventoryTest, EmptyList) { EXPECT_CALL(mock, sd_bus_message_at_end).WillRepeatedly(Return(1)); std::vector<InventoryItem> inventory = getInventory(bus); EXPECT_TRUE(inventory.empty()); } TEST_F(InventoryTest, FullList) { // clang-format off // ordered list of inventory items const char* orderedNames[] = { "cpu0", "cpu0/core0", "cpu0/core1", "cpu0/core5", "cpu0/core10", "cpu5", "cpu10", }; // unordered list of D-Bus objects const char* dbusPaths[] = { "/xyz/openbmc_project/inventory/system/chassis/cpu0/core1", "/xyz/openbmc_project/inventory/system/chassis/cpu10", "/xyz/openbmc_project/inventory/system/chassis/cpu0", "/xyz/openbmc_project/inventory/system/chassis/cpu0/core5", "/xyz/openbmc_project/inventory/system/chassis/cpu5", "/xyz/openbmc_project/inventory/system/chassis/cpu0/core10", "/xyz/openbmc_project/inventory/system/chassis/cpu0/core0", }; // clang-format on const size_t itemsCount = sizeof(orderedNames) / sizeof(orderedNames[0]); static_assert(itemsCount == sizeof(dbusPaths) / sizeof(dbusPaths[0])); // returns "end-of-array" flag, callback for "GetSubTree", // we need only object's path, so set "end-of-array" for every second call, // because GetSubTree wants map<string, map<string, vector<string>>> size_t counter = 0; EXPECT_CALL(mock, sd_bus_message_at_end) .WillRepeatedly(Invoke([&](sd_bus_message*, int) { const size_t index = counter / 2; const bool hasData = counter % 2 == 0 && index < itemsCount; ++counter; return hasData ? 0 : 1; })); // returns D-Bus object path, callback for "GetSubTree" size_t index = 0; EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillRepeatedly(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = index < itemsCount ? dbusPaths[index] : "<ERR>"; ++index; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), itemsCount); for (size_t i = 0; i < itemsCount; ++i) { const InventoryItem& item = inventory[i]; EXPECT_EQ(item.name, orderedNames[i]); EXPECT_TRUE(item.properties.empty()); EXPECT_TRUE(item.prettyName().empty()); EXPECT_TRUE(item.isPresent()); } } TEST_F(InventoryTest, BooleanProperty) { const char* key = "BooleanProperty"; const bool val = true; EXPECT_CALL(mock, sd_bus_message_at_end) .WillOnce(Return(0)) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetSubTree const char** s = static_cast<const char**>(p); *s = "/xyz/openbmc_project/inventory/dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = "xyz.openbmc_project.dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property name) const char** s = static_cast<const char**>(p); *s = key; return 0; })); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("s"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("x"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("t"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("u"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("q"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("y"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("b"))) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 'b', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { *static_cast<char*>(p) = val; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), 1); const InventoryItem& item = inventory[0]; EXPECT_EQ(item.properties.size(), 1); ASSERT_NE(item.properties.find(key), item.properties.end()); const auto& chkVal = item.properties.find(key)->second; ASSERT_TRUE(std::holds_alternative<bool>(chkVal)); EXPECT_EQ(std::get<bool>(chkVal), val); } TEST_F(InventoryTest, NumericProperty) { const char* key = "NumericProperty"; const int64_t val = 42; EXPECT_CALL(mock, sd_bus_message_at_end) .WillOnce(Return(0)) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetSubTree const char** s = static_cast<const char**>(p); *s = "/xyz/openbmc_project/inventory/dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = "xyz.openbmc_project.dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property name) const char** s = static_cast<const char**>(p); *s = key; return 0; })); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("x"))) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 'x', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { *static_cast<int64_t*>(p) = val; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), 1); const InventoryItem& item = inventory[0]; EXPECT_EQ(item.properties.size(), 1); ASSERT_NE(item.properties.find(key), item.properties.end()); const auto& chkVal = item.properties.find(key)->second; ASSERT_TRUE(std::holds_alternative<int64_t>(chkVal)); EXPECT_EQ(std::get<int64_t>(chkVal), val); } TEST_F(InventoryTest, StringProperty) { const char* key = "PrettyName"; const char* val = "Object pretty name \t \r\n "; const char* valResult = "Object pretty name"; EXPECT_CALL(mock, sd_bus_message_at_end) .WillOnce(Return(0)) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("x"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("t"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("u"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("q"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("y"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("s"))) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetSubTree const char** s = static_cast<const char**>(p); *s = "/xyz/openbmc_project/inventory/dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = "xyz.openbmc_project.dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property name) const char** s = static_cast<const char**>(p); *s = key; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property value) const char** s = static_cast<const char**>(p); *s = val; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), 1); const InventoryItem& item = inventory[0]; EXPECT_EQ(item.properties.size(), 1); EXPECT_EQ(item.prettyName(), valResult); }
35.240741
79
0.601051
YADRO-KNS
7edb57e849387adc7cf6c8b0ce0e2aee36d27ae1
7,210
cpp
C++
aslam_backend/src/BlockCholeskyLinearSystemSolver.cpp
ethz-asl/aslam_optimizer
8e9dd18f9f0d8af461e88e108a3beda2003daf11
[ "BSD-3-Clause" ]
33
2017-04-26T13:30:49.000Z
2022-02-25T01:52:22.000Z
aslam_backend/src/BlockCholeskyLinearSystemSolver.cpp
ethz-asl/aslam_optimizer
8e9dd18f9f0d8af461e88e108a3beda2003daf11
[ "BSD-3-Clause" ]
15
2017-02-14T16:02:31.000Z
2020-05-12T06:07:22.000Z
aslam_backend/src/BlockCholeskyLinearSystemSolver.cpp
ethz-asl/aslam_optimizer
8e9dd18f9f0d8af461e88e108a3beda2003daf11
[ "BSD-3-Clause" ]
8
2017-06-28T04:17:08.000Z
2021-04-10T04:58:36.000Z
#include <numeric> #include <aslam/backend/BlockCholeskyLinearSystemSolver.hpp> #include <sparse_block_matrix/linear_solver_cholmod.h> #include <sparse_block_matrix/linear_solver_spqr.h> #include <aslam/backend/ErrorTerm.hpp> #include <sm/PropertyTree.hpp> namespace aslam { namespace backend { BlockCholeskyLinearSystemSolver::BlockCholeskyLinearSystemSolver(const std::string & solver, const BlockCholeskyLinearSolverOptions& options) : _options(options), _solverType(solver) { initSolver(); } BlockCholeskyLinearSystemSolver::BlockCholeskyLinearSystemSolver(const sm::PropertyTree& config) { _solverType = config.getString("solverType", "cholesky"); // NO OPTIONS CURRENTLY IMPLEMENTED // USING C++11 would allow to do constructor delegation and more elegant code if(_solverType == "cholesky") { _solver.reset(new sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd>()); } else if(_solverType == "spqr") { _solver.reset(new sparse_block_matrix::LinearSolverQr<Eigen::MatrixXd>()); } else { std::cout << "Unknown block solver type " << _solverType << ". Try \"cholesky\" or \"spqr\"\nDefaulting to cholesky.\n"; _solver.reset(new sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd>()); } } BlockCholeskyLinearSystemSolver::~BlockCholeskyLinearSystemSolver() { } void BlockCholeskyLinearSystemSolver::initMatrixStructureImplementation(const std::vector<DesignVariable*>& dvs, const std::vector<ErrorTerm*>& errors, bool useDiagonalConditioner) { if(_solverType == "cholesky") { _solver.reset(new sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd>()); } else if(_solverType == "spqr") { _solver.reset(new sparse_block_matrix::LinearSolverQr<Eigen::MatrixXd>()); } else { std::cout << "Unknown block solver type " << _solverType << ". Try \"cholesky\" or \"spqr\"\nDefaulting to cholesky.\n"; _solver.reset(new sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd>()); } _solver->init(); _useDiagonalConditioner = useDiagonalConditioner; _errorTerms = errors; std::vector<int> blocks; for (size_t i = 0; i < dvs.size(); ++i) { dvs[i]->setBlockIndex(i); blocks.push_back(dvs[i]->minimalDimensions()); } std::partial_sum(blocks.begin(), blocks.end(), blocks.begin()); // Now we can initialized the sparse Hessian matrix. _H._M = SparseBlockMatrix(blocks, blocks); } void BlockCholeskyLinearSystemSolver::buildSystem(size_t /* nThreads */, bool useMEstimator) { // \todo make multithreaded. This is complicated as it requires synchronized access to the block matrix. // A little bit of effort should make this possible by initializing the structure and adding // a mutex for each block and having writers for each jacobian that have a list of mutexes. // Save it for later. _H._M.clear(false); _rhs.setZero(); std::vector<ErrorTerm*>::iterator it, it_end; it = _errorTerms.begin(); it_end = _errorTerms.end(); for (; it != it_end; ++it) { (*it)->buildHessian(_H._M, _rhs, useMEstimator); } } bool BlockCholeskyLinearSystemSolver::solveSystem(Eigen::VectorXd& outDx) { if (_useDiagonalConditioner) { Eigen::VectorXd d = _diagonalConditioner.cwiseProduct(_diagonalConditioner); // Augment the diagonal int rowBase = 0; for (int i = 0; i < _H._M.bRows(); ++i) { Eigen::MatrixXd& block = *_H._M.block(i, i, true); SM_ASSERT_EQ_DBG(Exception, block.rows(), block.cols(), "Diagonal blocks are square...right?"); block.diagonal() += d.segment(rowBase, block.rows()); rowBase += block.rows(); } } // Solve the system outDx.resize(_H._M.rows()); bool solutionSuccess = _solver->solve(_H._M, &outDx[0], &_rhs[0]); if (_useDiagonalConditioner) { // Un-augment the diagonal int rowBase = 0; for (int i = 0; i < _H._M.bRows(); ++i) { Eigen::MatrixXd& block = *_H._M.block(i, i, true); block.diagonal() -= _diagonalConditioner.segment(rowBase, block.rows()); rowBase += block.rows(); } } if( ! solutionSuccess ) { //std::cout << "Solution failed...creating a new solver\n"; // This seems to help when the CHOLMOD stuff gets into a bad state initSolver(); } return solutionSuccess; } void BlockCholeskyLinearSystemSolver::initSolver() { if(_solverType == "cholesky") { _solver.reset(new sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd>()); } else if(_solverType == "spqr") { _solver.reset(new sparse_block_matrix::LinearSolverQr<Eigen::MatrixXd>()); } else { std::cout << "Unknown block solver type " << _solverType << ". Try \"cholesky\" or \"spqr\"\nDefaulting to cholesky.\n"; _solver.reset(new sparse_block_matrix::LinearSolverCholmod<Eigen::MatrixXd>()); } } /// \brief compute only the covariance blocks associated with the block indices passed as an argument void BlockCholeskyLinearSystemSolver::computeCovarianceBlocks(const std::vector<std::pair<int, int> >& blockIndices, SparseBlockMatrix& outP) { // Not sure why I have to do this. //_solver->init(); if (_useDiagonalConditioner) { Eigen::VectorXd d = _diagonalConditioner.cwiseProduct(_diagonalConditioner); // Augment the diagonal int rowBase = 0; for (int i = 0; i < _H._M.bRows(); ++i) { Eigen::MatrixXd& block = *_H._M.block(i, i, true); SM_ASSERT_EQ_DBG(Exception, block.rows(), block.cols(), "Diagonal blocks are square...right?"); block.diagonal() += d.segment(rowBase, block.rows()); rowBase += block.rows(); } } bool success = _solver->solvePattern(outP, blockIndices, _H._M); SM_ASSERT_TRUE(Exception, success, "Unable to retrieve covariance"); if (_useDiagonalConditioner) { // Un-augment the diagonal int rowBase = 0; for (int i = 0; i < _H._M.bRows(); ++i) { Eigen::MatrixXd& block = *_H._M.block(i, i, true); block.diagonal() -= _diagonalConditioner.segment(rowBase, block.rows()); rowBase += block.rows(); } } } void BlockCholeskyLinearSystemSolver::copyHessian(SparseBlockMatrix& H) { _H._M.cloneInto(H); } const BlockCholeskyLinearSolverOptions& BlockCholeskyLinearSystemSolver::getOptions() const { return _options; } BlockCholeskyLinearSolverOptions& BlockCholeskyLinearSystemSolver::getOptions() { return _options; } void BlockCholeskyLinearSystemSolver::setOptions( const BlockCholeskyLinearSolverOptions& options) { _options = options; } double BlockCholeskyLinearSystemSolver::rhsJtJrhs() { Eigen::VectorXd JtJrhs; _H.rightMultiply(_rhs, JtJrhs); return _rhs.dot(JtJrhs); } } // namespace backend } // namespace aslam
39.398907
184
0.648821
ethz-asl
7ee0a8eaabcb5e3c5e253d93c9ea94913bdc12b8
1,308
cpp
C++
others/controller/httpcontroller.cpp
sesu089/stackoverflow
6fae69be6fa74fba9d554e6b5f387e5d3c1aad73
[ "MIT" ]
302
2017-03-04T00:05:23.000Z
2022-03-28T22:51:29.000Z
others/controller/httpcontroller.cpp
sesu089/stackoverflow
6fae69be6fa74fba9d554e6b5f387e5d3c1aad73
[ "MIT" ]
30
2017-12-02T19:26:43.000Z
2022-03-28T07:40:36.000Z
others/controller/httpcontroller.cpp
sesu089/stackoverflow
6fae69be6fa74fba9d554e6b5f387e5d3c1aad73
[ "MIT" ]
388
2017-07-04T16:53:12.000Z
2022-03-18T22:20:19.000Z
#include "httpcontroller.h" #include <QEventLoop> #include <QNetworkReply> #include <QNetworkRequest> HttpController::HttpController(QObject *parent) : QObject(parent) { cookies = new QNetworkCookieJar; manager = new QNetworkAccessManager(parent); manager->setCookieJar(cookies); } QString HttpController::Get(const QString &url) { QNetworkRequest request; request.setUrl(QUrl(url)); QNetworkReply *reply = manager->get(request); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); loop.exec(); if (reply->error()) return QString("Error"); QString response = QString(reply->readAll()); reply->deleteLater(); return response; } QString HttpController::Post(const QString &url, QHttpMultiPart *multipart) { QNetworkRequest request; request.setUrl(QUrl(url)); QNetworkReply *reply = manager->post(request, multipart); QEventLoop loop; connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), &loop, SLOT(quit())); loop.exec(); if (reply->error()) return QString("Error"); QString response = QString(reply->readAll()); reply->deleteLater(); return response; }
25.153846
77
0.702599
sesu089
7ee266dec2493da56f8108fd80c43a5700ff351d
397
cpp
C++
BeginnerLevel/Puppy_and_Sum.cpp
AkashKumarSingh11032001/CodeChef-Beginner-To-Medium
5c4a55b909ba90976099cb81374a8cecb4c3ead3
[ "MIT" ]
1
2021-05-05T04:50:26.000Z
2021-05-05T04:50:26.000Z
BeginnerLevel/Puppy_and_Sum.cpp
AkashKumarSingh11032001/CodeChef-Beginner-To-Medium
5c4a55b909ba90976099cb81374a8cecb4c3ead3
[ "MIT" ]
null
null
null
BeginnerLevel/Puppy_and_Sum.cpp
AkashKumarSingh11032001/CodeChef-Beginner-To-Medium
5c4a55b909ba90976099cb81374a8cecb4c3ead3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int sum_l(int d, int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } if (d == 1) return sum; else return sum_l(d - 1, sum); } int main() { int T; cin >> T; int d, n; while (T--) { /* code */ cin >> d >> n; cout << sum_l(d, n) << endl; } }
13.233333
36
0.387909
AkashKumarSingh11032001
7ee2bf9dc25225b64833301e070299f46c913d02
8,700
cpp
C++
test-src/suite.cpp
cslauritsen/cslhomie
e30bca41406099233e877b44186124f337a78f0b
[ "MIT" ]
null
null
null
test-src/suite.cpp
cslauritsen/cslhomie
e30bca41406099233e877b44186124f337a78f0b
[ "MIT" ]
null
null
null
test-src/suite.cpp
cslauritsen/cslhomie
e30bca41406099233e877b44186124f337a78f0b
[ "MIT" ]
null
null
null
#include "homie.hpp" #include <algorithm> #include <gtest/gtest.h> #include <list> #include <string> using Msg = homie::Message; class TestDevice : public homie::Device { public: TestDevice() : homie::Device("testdevice", "1.0", "TestDevice") { extensions.push_back("com.planetlauritsen.test:0.0.1:[4.x]"); } std::list<homie::Message> publications; int rssi = -58; int getRssi() override { return rssi; } std::vector<std::string> getExtensions() { return extensions; } protected: void publish(homie::Message m) override { std::cerr << "publishing to " << m.topic << std::endl; publications.push_back(m); } }; class PropertyTest : public ::testing::Test { protected: void SetUp() override { d = new TestDevice(); n = new homie::Node(d, "node1", "Node1", "generic"); p = new homie::Property(n, "prop1", "Prop1", homie::INTEGER, isWritable(), []() { return "s1"; }); p->setWriterFunc([this](std::string s) { this->capture.push_back(s); }); } void TearDown() override { delete d; } virtual bool isWritable() { return false; } TestDevice *d; homie::Node *n; homie::Property *p; std::list<std::string> capture; }; class WritablePropertyTest : public PropertyTest { protected: bool isWritable() override { return true; } }; TEST(HomieSuite, ToFahrenheit) { EXPECT_FLOAT_EQ(homie::to_fahrenheit(28.0), 82.4); } TEST(HomieSuite, formatMac) { EXPECT_EQ("aa:bb:cc:dd:ee:ff", homie::formatMac("aabb:ccdd:eeff")); } TEST(HomieSuite, bool_to_string) { EXPECT_EQ("false", homie::to_string(false)); EXPECT_EQ("true", homie::to_string(true)); } TEST(HomieSuite, splitString) { std::vector<std::string> res; homie::split_string("a/b/c", "/", res); EXPECT_EQ(3, res.size()); EXPECT_EQ("a", res[0]); EXPECT_EQ("b", res[1]); EXPECT_EQ("c", res[2]); } TEST(HomieSuite, f2s) { float f = 1.22222; auto x = homie::f2s(f); ASSERT_EQ("1.2", x) << f << " % %.1f => 100"; } TEST_F(WritablePropertyTest, NodeIsPresent) { EXPECT_TRUE(d->getNode("node1") == n); } TEST_F(PropertyTest, PropertyIsPresent) { EXPECT_TRUE(n->getProperty("prop1") == p); } TEST_F(PropertyTest, PropertyIsRead) { EXPECT_FALSE(p->isSettable()); EXPECT_EQ("s1", p->read()); } TEST_F(WritablePropertyTest, WritablePropertyWritesValue) { EXPECT_TRUE(p->isSettable()); EXPECT_EQ("s1", p->read()); EXPECT_EQ(1, capture.size()) << "Captured writes should have 1 member from read()"; p->setValue("wooga"); EXPECT_EQ(2, capture.size()) << "Captured writes should have 2 members after setValue()"; auto iter = capture.begin(); EXPECT_EQ("s1", *iter++) << "Captured writes first member should be from read()"; EXPECT_EQ("wooga", *iter++) << "Capture writes second member should be from setValue()"; } TEST_F(PropertyTest, NonWritablePropertyIgnoresWriterFunc) { EXPECT_FALSE(p->isSettable()); EXPECT_EQ("s1", p->read()); EXPECT_EQ(0, this->capture.size()) << "Captured writes list should be empty"; p->setValue("wooga"); EXPECT_EQ(0, this->capture.size()) << "Captured writes list should be empty, even after setValue()"; auto iter = this->capture.begin(); EXPECT_EQ(iter, this->capture.end()) << "Captured writes list should not iterate"; } TEST_F(PropertyTest, PropertyPublish) { p->publish(); EXPECT_EQ(1, d->publications.size()) << "Publication count should be " << 1; } TEST_F(PropertyTest, PropertyIntroduce) { p->introduce(); EXPECT_GT(d->publications.size(), 3) << "After introduction, publication count should be > 3"; } TEST_F(PropertyTest, PropertyIntroduceUnit) { p->setUnit("jigawatts"); p->introduce(); auto count = std::count_if( d->publications.begin(), d->publications.end(), [](homie::Message m) { return m.topic.find("$unit") != std::string::npos; }); EXPECT_EQ(1, count) << "There should be one and only one $unit topic emitted."; } TEST_F(PropertyTest, PropertyIntroduceFormat) { p->setFormat("1:9"); p->introduce(); auto l = d->publications; auto count = std::count_if(l.begin(), l.end(), [](Msg m) { return m.topic.find("$format") != std::string::npos; }); EXPECT_EQ(1, count) << "There should be one and only one $format topic emitted."; auto count2 = std::count_if(l.begin(), l.end(), [](Msg m) { return m.payload == "1:9"; }); EXPECT_EQ(1, count2) << "There should be one and only one $format payload emitted."; } TEST_F(PropertyTest, NodePropertyNotFound) { EXPECT_EQ(nullptr, n->getProperty("wooga")) << "Nonexistent property should return nullptr"; } TEST_F(PropertyTest, NodeSinglePropertyIntroduction) { n->introduce(); auto count = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.topic.find("$properties") != std::string::npos; }); auto count2 = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.payload.find(",") != std::string::npos; }); EXPECT_EQ(1, count) << "only one $properties message should be published"; EXPECT_EQ(0, count2) << "no commas in single properties"; } TEST_F(PropertyTest, NodeMultiplePropertyIntroduction) { new homie::Property(n, "prop2", "Prop2", homie::INTEGER, isWritable(), []() { return "s2"; }); n->introduce(); auto count = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.topic.find("$properties") != std::string::npos; }); auto count2 = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.payload.find(",") != std::string::npos; }); EXPECT_EQ(1, count) << "only one $properties message should be published"; EXPECT_EQ(1, count2) << "single comma in properties"; } TEST_F(PropertyTest, WifiSignalStrength) { d->rssi = -100; EXPECT_EQ(0, d->getWifiSignalStrength()); d->rssi = -49; EXPECT_EQ(100, d->getWifiSignalStrength()); d->rssi = -58; EXPECT_EQ(84, d->getWifiSignalStrength()); d->introduce(); } TEST_F(PropertyTest, PublishWifi) { d->rssi = -49; // -> signal strength "100" d->publishWifi(); EXPECT_EQ(1, std::count_if(d->publications.begin(), d->publications.end(), [this](Msg m) { return m.topic.find(homie::PROP_NM_RSSI) != std::string::npos && m.payload == std::to_string(this->d->rssi); })); EXPECT_EQ(1, std::count_if( d->publications.begin(), d->publications.end(), [](Msg m) { return m.topic.find("/signal") != std::string::npos && m.payload == "100"; })); } TEST_F(PropertyTest, PublishLocalIp) { d->setLocalIp("1.2.3.4"); d->introduce(); EXPECT_EQ(1, std::count_if(d->publications.begin(), d->publications.end(), [this](Msg m) { return m.topic.find("/localip") != std::string::npos && m.payload == this->d->getLocalIp(); })); } TEST_F(PropertyTest, PublishMac) { d->setMac("fe:ed:fa:ce:de:ad"); d->introduce(); EXPECT_EQ(1, std::count_if(d->publications.begin(), d->publications.end(), [this](Msg m) { return m.topic.find("/mac") != std::string::npos && m.payload == this->d->getMac(); })); } TEST_F(WritablePropertyTest, CheckSubTopic) { EXPECT_EQ(p->getPubTopic() + "/set", p->getSubTopic()); } TEST_F(PropertyTest, CheckMissingNodeReturnsNullPtr) { EXPECT_EQ(nullptr, d->getNode("fjdfkdlkff0dfj00-0l")); } TEST_F(PropertyTest, CheckLwtIsLost) { EXPECT_EQ("lost", d->getLwt().payload); } TEST_F(WritablePropertyTest, CheckInputMessage) { auto inputMsg = Msg("homie/" + d->getId() + "/" + n->getId() + "/" + p->getId() + "/set", "awesome new value"); d->onMessage(inputMsg); EXPECT_EQ(inputMsg.payload, p->getValue()); } TEST_F(PropertyTest, InputMessageIgnoredForNonWritableProperty) { auto inputMsg = Msg("homie/" + d->getId() + "/" + n->getId() + "/" + p->getId() + "/set", "woo-hoo"); p->setValue("previous"); d->onMessage(inputMsg); EXPECT_EQ("previous", p->getValue()); } TEST_F(PropertyTest, CheckExtensions) { EXPECT_EQ(2, d->getExtensions().size()); }
32.103321
80
0.595287
cslauritsen
7ee43efa331193d3f74507e4f2181196fe53e5b3
2,877
cpp
C++
Chapter07/Exercise7.01/EnemyCharacter.cpp
rutuja027/Game-Development-Projects-with-Unreal-Engine
e165ebd9404c76b9bdffa38d040dc640ba9b79ed
[ "MIT" ]
41
2020-11-14T07:18:27.000Z
2022-03-28T13:42:02.000Z
Chapter07/Exercise7.01/EnemyCharacter.cpp
fghaddar/Game-Development-Projects-with-Unreal-Engine
79a987c01dd672b6e8b95bdd15f1d17380044bf8
[ "MIT" ]
null
null
null
Chapter07/Exercise7.01/EnemyCharacter.cpp
fghaddar/Game-Development-Projects-with-Unreal-Engine
79a987c01dd672b6e8b95bdd15f1d17380044bf8
[ "MIT" ]
23
2021-01-20T07:05:38.000Z
2022-03-15T05:25:54.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "EnemyCharacter.h" #include "Engine/World.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/GameplayStatics.h" #include "TimerManager.h" #include "DodgeballProjectile.h" #include "DodgeballFunctionLibrary.h" #include "GameFramework/ProjectileMovementComponent.h" // Sets default values AEnemyCharacter::AEnemyCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SightSource = CreateDefaultSubobject<USceneComponent>(TEXT("Sight Source")); SightSource->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void AEnemyCharacter::BeginPlay() { Super::BeginPlay(); } // Called every frame void AEnemyCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Fetch the character currently being controlled by the player ACharacter* PlayerCharacter = UGameplayStatics::GetPlayerCharacter(this, 0); // Look at the player character every frame bCanSeePlayer = LookAtActor(PlayerCharacter); if (bCanSeePlayer != bPreviousCanSeePlayer) { if (bCanSeePlayer) { //Start throwing dodgeballs GetWorldTimerManager().SetTimer(ThrowTimerHandle, this, &AEnemyCharacter::ThrowDodgeball, ThrowingInterval, true, ThrowingDelay); } else { //Stop throwing dodgeballs GetWorldTimerManager().ClearTimer(ThrowTimerHandle); } } bPreviousCanSeePlayer = bCanSeePlayer; } bool AEnemyCharacter::LookAtActor(const AActor * TargetActor) { if (TargetActor == nullptr) return false; const TArray<const AActor*> IgnoreActors = { this, TargetActor }; if (UDodgeballFunctionLibrary::CanSeeActor(GetWorld(), SightSource->GetComponentLocation(), TargetActor, IgnoreActors)) { FVector Start = GetActorLocation(); FVector End = TargetActor->GetActorLocation(); // Calculate the necessary rotation for the Start point to face the End point FRotator LookAtRotation = UKismetMathLibrary::FindLookAtRotation(Start, End); //Set the enemy's rotation to that rotation SetActorRotation(LookAtRotation); return true; } return false; } void AEnemyCharacter::ThrowDodgeball() { if (DodgeballClass == nullptr) { return; } FVector ForwardVector = GetActorForwardVector(); float SpawnDistance = 40.f; FVector SpawnLocation = GetActorLocation() + (ForwardVector * SpawnDistance); FTransform SpawnTransform(GetActorRotation(), SpawnLocation); //Spawn new dodgeball ADodgeballProjectile* Projectile = GetWorld()->SpawnActorDeferred<ADodgeballProjectile>(DodgeballClass, SpawnTransform); Projectile->GetProjectileMovementComponent()->InitialSpeed = 2200.f; Projectile->FinishSpawning(SpawnTransform); }
27.4
121
0.748349
rutuja027
7ee54a9fdad3d6ed15d61a57eaaaffcb1f639c91
5,230
cpp
C++
TopQuarkAnalysis/TopJetCombination/bin/TtSemiLRJetComb_PurityLoop.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
TopQuarkAnalysis/TopJetCombination/bin/TtSemiLRJetComb_PurityLoop.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
TopQuarkAnalysis/TopJetCombination/bin/TtSemiLRJetComb_PurityLoop.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <iostream> #include <cassert> #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TTree.h> #include <TBranch.h> #include <TCanvas.h> #include <TH1.h> #include <TH2.h> #include <TGraph.h> #include <TF1.h> #include <TFormula.h> #include <TStyle.h> #include <TKey.h> #include <vector> #include "FWCore/FWLite/interface/FWLiteEnabler.h" #include "AnalysisDataFormats/TopObjects/interface/TtSemiEvtSolution.h" #include "TopQuarkAnalysis/TopTools/interface/LRHelpFunctions.h" /////////////////////// // Constants // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //input files const int nrFiles = 51; const TString path = "dcap://maite.iihe.ac.be:/pnfs/iihe/becms/heyninck/TtSemiMuEvents_TopRex_Juni/TtSemiMuEvents_"; //matching variables const double SumAlphaCut = 0.7; //select which observables to use const int nrJetCombObs = 7; const int JetCombObs[nrJetCombObs] = {1, 2, 3, 4, 5, 6, 7}; const TString JetCombInputFileName = "../data/TtSemiLRJetCombAllObs.root"; //likelihood histogram variables const int nrJetCombLRtotBins = 30; const double JetCombLRtotMin = -5; const double JetCombLRtotMax = 7; const char *JetCombLRtotFitFunction = "[0]/(1 + 1/exp([1]*([2] - x)))"; //output files ps/root const TString JetCombOutFileName = "../data/TtSemiLRJetCombSelObsAndPurity.root"; const TString JetCombPSfile = "../data/TtSemiLRJetCombSelObsAndPurity.ps"; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Global variables // LRHelpFunctions *myLRhelper; void doEventloop(); std::vector<int> obsNrs; // // Main analysis // int main() { gSystem->Load("libFWCoreFWLite"); FWLiteEnabler::enable(); // define all histograms & fit functions //to replace with something more elegant for (int j = 0; j < nrJetCombObs; j++) { obsNrs.push_back(JetCombObs[j]); } myLRhelper = new LRHelpFunctions(nrJetCombLRtotBins, JetCombLRtotMin, JetCombLRtotMax, JetCombLRtotFitFunction); // read in S/S+N fits of observables to use myLRhelper->readObsHistsAndFits(JetCombInputFileName, obsNrs, false); // fill calculated LR value for each signal or background contributions doEventloop(); // make Purity vs logLR and Purity vs. Efficiency plot myLRhelper->makeAndFitPurityHists(); // store histograms and fits in root-file myLRhelper->storeToROOTfile(JetCombOutFileName); // make some control plots and put them in a .ps file myLRhelper->storeControlPlots(JetCombPSfile); } // // Loop over the events (with the definition of what is considered signal and background) // void doEventloop() { std::cout << std::endl << std::endl << "**** STARTING EVENT LOOP ****" << std::endl; int totNrEv = 0; for (int nr = 1; nr <= nrFiles; nr++) { TString ft = path; ft += nr - 1; ft += ".root"; if (!gSystem->AccessPathName(ft)) { TFile *file = TFile::Open(ft); TTree *events = dynamic_cast<TTree *>(file->Get("Events")); assert(events != nullptr); TBranch *solsbranch = events->GetBranch("TtSemiEvtSolutions_solutions__TtEventReco.obj"); //TBranch * solsbranch = events->GetBranch( "TtSemiEvtSolutions_solutions__CommonBranchSel.obj" ); assert(solsbranch != nullptr); std::vector<TtSemiEvtSolution> sols; solsbranch->SetAddress(&sols); //loop over all events in a file for (int ev = 0; ev < events->GetEntries(); ++ev) { ++totNrEv; if ((double)((totNrEv * 1.) / 1000.) == (double)(totNrEv / 1000)) std::cout << " Processing event " << totNrEv << std::endl; solsbranch->GetEntry(ev); if (sols.size() == 12) { // check if good matching solution exists bool trueSolExists = false; for (int s = 0; s < 12; s++) { if (sols[s].getMCBestSumAngles() < SumAlphaCut) trueSolExists = true; } if (trueSolExists) { double maxLogLRVal = -999.; int maxLogLRSol = -999; //loop over solutions for (int s = 0; s < 12; s++) { // get observable values std::vector<double> obsVals; for (int j = 0; j < nrJetCombObs; j++) { if (myLRhelper->obsFitIncluded(obsNrs[j])) obsVals.push_back(sols[s].getLRJetCombObsVal(obsNrs[j])); } double logLR = myLRhelper->calcLRval(obsVals); if (logLR > maxLogLRVal) { maxLogLRVal = logLR; maxLogLRSol = s; }; } if (sols[maxLogLRSol].getMCBestSumAngles() < SumAlphaCut && sols[maxLogLRSol].getMCBestJetComb() == maxLogLRSol) { myLRhelper->fillLRSignalHist(maxLogLRVal); //std::cout << "mxLR " << maxLogLRVal << std::endl; } else { myLRhelper->fillLRBackgroundHist(maxLogLRVal); //std::cout << "mxLR (bg) " << maxLogLRVal << std::endl; } } } } file->Close(); } else { std::cout << ft << " doesn't exist" << std::endl; } } }
33.741935
128
0.595029
ckamtsikis
7ee7df3da333a5477cdb0454d3dcc4f4274c090f
1,493
cc
C++
fundamental/array/binary_search/binary_search.cc
geek-yang/Algorism
fc1fa544b0a21459808797cdc9287b9c6b8f5358
[ "Apache-2.0" ]
null
null
null
fundamental/array/binary_search/binary_search.cc
geek-yang/Algorism
fc1fa544b0a21459808797cdc9287b9c6b8f5358
[ "Apache-2.0" ]
null
null
null
fundamental/array/binary_search/binary_search.cc
geek-yang/Algorism
fc1fa544b0a21459808797cdc9287b9c6b8f5358
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { /* Solution for leetcode question 704. For binary search, it is a must that the given input array is sorted in ascending order and there is no repeated element. */ public: int binary_search(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; while (left <= right) { int middle = left + (right - left) / 2; if (nums[middle] > target) { right = middle - 1; } else if (nums[middle] < target) { left = middle + 1; } else { return middle; } } return -1; } void vector_print(vector<int>& nums, int size){ for (int i = 0; i < size; i++){ std::cout << nums[i] << ' '; } std::cout << "\n" << std::endl; } }; int main() { // first checker vector<int> nums {-1,0,3,5,9,12}; int target = 9; Solution solution; std::cout << "First test.\n"; std::cout << "Test data.\n"; solution.vector_print(nums, nums.size()); int result; result = solution.binary_search(nums, target); std::cout << "Output:" << result << "\n"; std::cout << "------------------------------\n"; // second checker target = 2; std::cout << "Second test.\n"; std::cout << "Output.\n"; result = solution.binary_search(nums, target); std::cout << "Output:" << result << "\n"; }
24.080645
54
0.513731
geek-yang
7ee82e3d0bdce9fd102a134ea79eba859025b141
2,297
cpp
C++
DXMPP/SASL/SASLMechanism.cpp
synergysky/dxmpp
8bd741993ee8cded5bfbc8cc739e7c7a81b3f203
[ "BSL-1.0" ]
17
2015-02-09T05:18:11.000Z
2021-10-10T04:13:11.000Z
DXMPP/SASL/SASLMechanism.cpp
synergysky/dxmpp
8bd741993ee8cded5bfbc8cc739e7c7a81b3f203
[ "BSL-1.0" ]
4
2017-04-07T13:55:10.000Z
2019-06-10T09:56:47.000Z
DXMPP/SASL/SASLMechanism.cpp
synergysky/dxmpp
8bd741993ee8cded5bfbc8cc739e7c7a81b3f203
[ "BSL-1.0" ]
24
2015-03-20T06:57:27.000Z
2020-06-18T15:29:22.000Z
// // SASLMechanism.cpp // DXMPP // // Created by Stefan Karlsson 2014 // Copyright (c) 2014 Deus ex Machinae. All rights reserved. // #include <DXMPP/SASL/SASLMechanism.hpp> #include <pugixml/pugixml.hpp> #include <DXMPP/JID.hpp> #include <boost/function.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include <boost/array.hpp> #include <boost/algorithm/string.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <cryptopp/cryptlib.h> #include <cryptopp/hex.h> #include <cryptopp/hmac.h> #include <cryptopp/sha.h> #include <cryptopp/base64.h> #include <cryptopp/queue.h> #include <sstream> #include <ostream> #include <iostream> #include "SaslChallengeParser.hpp" namespace DXMPP { namespace SASL { using namespace std; using namespace boost::asio::ip; using namespace boost::asio; using namespace pugi; using namespace boost::archive::iterators; typedef transform_width< binary_from_base64<remove_whitespace<string::const_iterator> >, 8, 6 > Base64Decode; typedef base64_from_binary<transform_width<string::const_iterator,6,8> > Base64Encode; string SASLMechanism::DecodeBase64(string Input) { unsigned int paddChars = count(Input.begin(), Input.end(), '='); std::replace(Input.begin(),Input.end(),'=','A'); string result(Base64Decode(Input.begin()), Base64Decode(Input.end())); result.erase(result.end()-paddChars,result.end()); return result; } string SASLMechanism::EncodeBase64(string Input) { unsigned int writePaddChars = (3-Input.length()%3)%3; string base64(Base64Encode(Input.begin()),Base64Encode(Input.end())); base64.append(writePaddChars,'='); return base64; } } }
30.223684
117
0.685677
synergysky
7eeb4e4e379d0b1a0d7ea46f9dd55e0a5bd079f2
2,070
hh
C++
construct/CSGNode.i.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
construct/CSGNode.i.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
construct/CSGNode.i.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
//---------------------------------*-C++-*-----------------------------------// /*! * \file construct/CSGNode.i.hh * \brief CSGNode inline method definitions * \note Copyright (c) 2021 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #pragma once namespace celeritas { //---------------------------------------------------------------------------// /*! * Construct a leaf (single surface) */ CSGNode::CSGNode(SurfaceId id) : type_(NodeType::leaf_surface), id_(id.get()) { CELER_ENSURE(this->is_surface()); } //---------------------------------------------------------------------------// /*! * Construct a node (single surface) */ CSGNode::CSGNode(Daughter daughter) : CSGNode({daughter}, CSGCell::LOGIC_AND) { CELER_ENSURE(!this->is_leaf()); } //---------------------------------------------------------------------------// /*! * \brief Surface ID */ auto CSGNode::surface_id() const -> SurfaceId { CELER_EXPECT(this->is_leaf()); return SurfaceId{id_}; } //---------------------------------------------------------------------------// /*! * \brief The daughter elements if this is a node */ auto CSGNode::daughters() const -> const VecDaughter& { CELER_EXPECT(!this->is_leaf()); return daughters_; } //---------------------------------------------------------------------------// /*! * \brief The conjunction type if this is a node */ auto CSGNode::conjunction() const -> CSGLogicToken { CELER_EXPECT(!this->is_leaf()); return (type_ == NodeType::node_and ? CSGCell::LOGIC_AND : CSGCell::LOGIC_OR); } //---------------------------------------------------------------------------// /*! * \brief Equality with another CSG node. */ bool CSGNode::operator==(const CSGNode& other) const { return type_ == other.type_ && id_ == other.id_ && daughters_ == other.daughters_; } //---------------------------------------------------------------------------// } // namespace celeritas
28.356164
79
0.423671
celeritas-project
7ef367188a456625b49bda5a02720ea64be9e6c3
154
hpp
C++
src/LevelScheduler.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
null
null
null
src/LevelScheduler.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
null
null
null
src/LevelScheduler.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
3
2019-03-05T16:46:25.000Z
2021-12-22T03:49:00.000Z
#ifndef LEVELSCHEDULER_HPP #define LEVELSCHEDULER_HPP #include "KokkosSetup.hpp" #include "SparseMatrix.hpp" int levelSchedule(SparseMatrix & A); #endif
19.25
36
0.811688
hpcg-benchmark
7ef95f706923464ac5e1417ba4876f4e19fb3860
9,520
cpp
C++
Turso3D/Resource/ResourceCache.cpp
cadaver/turso3d
5659df48b7915b95a351dfcad382b3ed653573f2
[ "Zlib" ]
29
2015-03-21T22:35:50.000Z
2022-01-25T04:13:46.000Z
Turso3D/Resource/ResourceCache.cpp
cadaver/turso3d
5659df48b7915b95a351dfcad382b3ed653573f2
[ "Zlib" ]
1
2016-10-23T16:20:14.000Z
2018-04-13T13:32:13.000Z
Turso3D/Resource/ResourceCache.cpp
cadaver/turso3d
5659df48b7915b95a351dfcad382b3ed653573f2
[ "Zlib" ]
8
2015-09-28T06:26:41.000Z
2020-12-28T14:29:51.000Z
// For conditions of distribution and use, see copyright notice in License.txt #include "../Debug/Log.h" #include "../Debug/Profiler.h" #include "../IO/File.h" #include "../IO/FileSystem.h" #include "Image.h" #include "JSONFile.h" #include "ResourceCache.h" #include "../Debug/DebugNew.h" namespace Turso3D { ResourceCache::ResourceCache() { RegisterSubsystem(this); } ResourceCache::~ResourceCache() { UnloadAllResources(true); RemoveSubsystem(this); } bool ResourceCache::AddResourceDir(const String& pathName, bool addFirst) { PROFILE(AddResourceDir); if (!DirExists(pathName)) { LOGERROR("Could not open directory " + pathName); return false; } String fixedPath = SanitateResourceDirName(pathName); // Check that the same path does not already exist for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (!resourceDirs[i].Compare(fixedPath, false)) return true; } if (addFirst) resourceDirs.Insert(0, fixedPath); else resourceDirs.Push(fixedPath); LOGINFO("Added resource path " + fixedPath); return true; } bool ResourceCache::AddManualResource(Resource* resource) { if (!resource) { LOGERROR("Null manual resource"); return false; } if (resource->Name().IsEmpty()) { LOGERROR("Manual resource with empty name, can not add"); return false; } resources[MakePair(resource->Type(), StringHash(resource->Name()))] = resource; return true; } void ResourceCache::RemoveResourceDir(const String& pathName) { // Convert path to absolute String fixedPath = SanitateResourceDirName(pathName); for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (!resourceDirs[i].Compare(fixedPath, false)) { resourceDirs.Erase(i); LOGINFO("Removed resource path " + fixedPath); return; } } } void ResourceCache::UnloadResource(StringHash type, const String& name, bool force) { auto key = MakePair(type, StringHash(name)); auto it = resources.Find(key); if (it == resources.End()) return; Resource* resource = it->second; if (resource->Refs() == 1 || force) resources.Erase(key); } void ResourceCache::UnloadResources(StringHash type, bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; if (current->first.first == type) { Resource* resource = current->second; if (resource->Refs() == 1 || force) { resources.Erase(current); ++unloaded; } } } if (!unloaded) break; } } void ResourceCache::UnloadResources(StringHash type, const String& partialName, bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; if (current->first.first == type) { Resource* resource = current->second; if (resource->Name().StartsWith(partialName) && (resource->Refs() == 1 || force)) { resources.Erase(current); ++unloaded; } } } if (!unloaded) break; } } void ResourceCache::UnloadResources(const String& partialName, bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; Resource* resource = current->second; if (resource->Name().StartsWith(partialName) && (!resource->Refs() == 1 || force)) { resources.Erase(current); ++unloaded; } } if (!unloaded) break; } } void ResourceCache::UnloadAllResources(bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; Resource* resource = current->second; if (resource->Refs() == 1 || force) { resources.Erase(current); ++unloaded; } } if (!unloaded) break; } } bool ResourceCache::ReloadResource(Resource* resource) { if (!resource) return false; AutoPtr<Stream> stream = OpenResource(resource->Name()); return stream ? resource->Load(*stream) : false; } AutoPtr<Stream> ResourceCache::OpenResource(const String& nameIn) { String name = SanitateResourceName(nameIn); AutoPtr<Stream> ret; for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (FileExists(resourceDirs[i] + name)) { // Construct the file first with full path, then rename it to not contain the resource path, // so that the file's name can be used in further OpenResource() calls (for example over the network) ret = new File(resourceDirs[i] + name); break; } } // Fallback using absolute path if (!ret) ret = new File(name); if (!ret->IsReadable()) { LOGERROR("Could not open resource file " + name); ret.Reset(); } return ret; } Resource* ResourceCache::LoadResource(StringHash type, const String& nameIn) { String name = SanitateResourceName(nameIn); // If empty name, return null pointer immediately without logging an error if (name.IsEmpty()) return nullptr; // Check for existing resource auto key = MakePair(type, StringHash(name)); auto it = resources.Find(key); if (it != resources.End()) return it->second; SharedPtr<Object> newObject = Create(type); if (!newObject) { LOGERROR("Could not load unknown resource type " + String(type)); return nullptr; } Resource* newResource = dynamic_cast<Resource*>(newObject.Get()); if (!newResource) { LOGERROR("Type " + String(type) + " is not a resource"); return nullptr; } // Attempt to load the resource AutoPtr<Stream> stream = OpenResource(name); if (!stream) return nullptr; LOGDEBUG("Loading resource " + name); newResource->SetName(name); if (!newResource->Load(*stream)) return nullptr; // Store to cache resources[key] = newResource; return newResource; } void ResourceCache::ResourcesByType(Vector<Resource*>& result, StringHash type) const { result.Clear(); for (auto it = resources.Begin(); it != resources.End(); ++it) { if (it->second->Type() == type) result.Push(it->second); } } bool ResourceCache::Exists(const String& nameIn) const { String name = SanitateResourceName(nameIn); for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (FileExists(resourceDirs[i] + name)) return true; } // Fallback using absolute path return FileExists(name); } String ResourceCache::ResourceFileName(const String& name) const { for (unsigned i = 0; i < resourceDirs.Size(); ++i) { if (FileExists(resourceDirs[i] + name)) return resourceDirs[i] + name; } return String(); } String ResourceCache::SanitateResourceName(const String& nameIn) const { // Sanitate unsupported constructs from the resource name String name = NormalizePath(nameIn); name.Replace("../", ""); name.Replace("./", ""); // If the path refers to one of the resource directories, normalize the resource name if (resourceDirs.Size()) { String namePath = Path(name); String exePath = ExecutableDir(); for (unsigned i = 0; i < resourceDirs.Size(); ++i) { String relativeResourcePath = resourceDirs[i]; if (relativeResourcePath.StartsWith(exePath)) relativeResourcePath = relativeResourcePath.Substring(exePath.Length()); if (namePath.StartsWith(resourceDirs[i], false)) namePath = namePath.Substring(resourceDirs[i].Length()); else if (namePath.StartsWith(relativeResourcePath, false)) namePath = namePath.Substring(relativeResourcePath.Length()); } name = namePath + FileNameAndExtension(name); } return name.Trimmed(); } String ResourceCache::SanitateResourceDirName(const String& nameIn) const { // Convert path to absolute String fixedPath = AddTrailingSlash(nameIn); if (!IsAbsolutePath(fixedPath)) fixedPath = CurrentDir() + fixedPath; // Sanitate away /./ construct fixedPath.Replace("/./", "/"); return fixedPath.Trimmed(); } void RegisterResourceLibrary() { static bool registered = false; if (registered) return; registered = true; Image::RegisterObject(); JSONFile::RegisterObject(); } }
25.72973
113
0.590651
cadaver
7efc798cb18550e397bb9217c27981433a263feb
2,926
cpp
C++
Nemo/RayVisualize.cpp
cyj0912/Nemo
cd242e9d17863b461ccfd768122572d979c330e3
[ "BSD-2-Clause" ]
null
null
null
Nemo/RayVisualize.cpp
cyj0912/Nemo
cd242e9d17863b461ccfd768122572d979c330e3
[ "BSD-2-Clause" ]
null
null
null
Nemo/RayVisualize.cpp
cyj0912/Nemo
cd242e9d17863b461ccfd768122572d979c330e3
[ "BSD-2-Clause" ]
null
null
null
#include "RayVisualize.h" #include "EditorMaster.h" #include "imgui/imgui.h" namespace tc { FRayRenderComponentStaticData::FRayRenderComponentStaticData() { UserCount++; } FRayRenderComponentStaticData::~FRayRenderComponentStaticData() { UserCount--; } void FRayRenderComponentStaticData::RenderStaticInit() { if (bInitialized) return; bInitialized = true; LOGDEBUG("FRayRenderComponentStaticData::RenderStaticInit called and ran\n"); glGenBuffers(1, Buffers); glGenVertexArrays(1, VertexArrays); glBindVertexArray(VertexArrays[0]); glBindBuffer(GL_ARRAY_BUFFER, Buffers[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6, nullptr, GL_DYNAMIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glEnableVertexAttribArray(0); glBindVertexArray(0); Shader = FGLSLProgram::CreateFromFiles("fgizmocolor.vert", "fgizmocolor.frag"); } void FRayRenderComponentStaticData::RenderStaticDestroy() { if (!bInitialized || UserCount > 0) return; LOGDEBUG("FRayRenderComponentStaticData::RenderStaticDestroy called and ran\n"); delete Shader; glDeleteBuffers(1, Buffers); glDeleteVertexArrays(1, VertexArrays); } int FRayRenderComponentStaticData::UserCount = 0; bool FRayRenderComponentStaticData::bInitialized = false; GLuint FRayRenderComponentStaticData::Buffers[1]; GLuint FRayRenderComponentStaticData::VertexArrays[1]; FGLSLProgram* FRayRenderComponentStaticData::Shader; bool FRayVisualizer::MousePressed(const FMouseButtonEvent& evt) { if (!bIsEnabled) return false; if (evt.button == EMouseButton::Left) { auto ray = EditorMaster->GetViewPort()->GetRayTo(evt.x, evt.y); auto rayDisp = new FRayDisplay(ray); rayDisp->RenderInit(EditorMaster->GetViewPort()); RayDisplayVector.push_back(rayDisp); } return false; } void FRayVisualizer::ImGuiUpdate() { if (ImGui::CollapsingHeader("Ray Visualizer")) { ImGui::Text("Total Rays: %d", (int)RayDisplayVector.size()); ImGui::Checkbox("Enabled", &bIsEnabled); if (ImGui::Button("Remove All Rays")) { RenderDestroy(); for (auto* ray : RayDisplayVector) delete ray; RayDisplayVector.clear(); } if (!RayDisplayVector.empty()) { auto* lastRay = RayDisplayVector[RayDisplayVector.size() - 1]; const Ray& ray = lastRay->GetRay(); ImGui::Text("Last Ray"); ImGui::Text("\tOrigin: <%s>", ray.Origin.ToString().c_str()); ImGui::Text("\tDirection: <%s>", ray.Direction.ToString().c_str()); } } } void FRayVisualizer::Render() { for (auto* ray : RayDisplayVector) ray->Render(); } void FRayVisualizer::RenderDestroy() { for (auto* ray : RayDisplayVector) ray->RenderDestroy(); } } /* namespace tc */
26.6
84
0.671565
cyj0912
7d050d496c909dcc32e10482502e4f95b26da1fd
15,667
cpp
C++
robot.cpp
gregk27/StrongholdSim
bdb121ebf68b66b4e29a9d0ea3ad072161c818fb
[ "Zlib" ]
null
null
null
robot.cpp
gregk27/StrongholdSim
bdb121ebf68b66b4e29a9d0ea3ad072161c818fb
[ "Zlib" ]
null
null
null
robot.cpp
gregk27/StrongholdSim
bdb121ebf68b66b4e29a9d0ea3ad072161c818fb
[ "Zlib" ]
null
null
null
#include <stdio.h> #include <string> #include <cstring> #include <stdlib.h> #include <math.h> #include <limits.h> #include <sstream> #include "robot.h" #include "utils/utils.h" #include "field/field.h" #include "field/Fieldnode.h" #include "utils/Heap.h" #define BUFF_SIZE 256 // Some compilers may be missing M_PI, this serves as a safety check https://stackoverflow.com/questions/14920675/is-there-a-function-in-c-language-to-calculate-degrees-radians #ifndef M_PI #define M_PI 3.1415926535 #endif Robot::Robot(){ this->id = -1; this->team = 0000; this->speed = 0; this->alliance = Alliance::NEUTRAL; this->canLowbar = false; this->defenses = 0; this->shotRange = 0; this->centreShotTime = 0; this->sideShotTime = 0; this->centreAngle = 0; this->sideAngle = 0; this->lowTime = 0; this->path = NULL; } void Robot::initGraph(){ // Initialise warning std::stringstream warning; // If the shot range is greated than the distance to defenses, there is something wrong. Warn the user and cap it if(shotRange > DEFENSE_EDGE_OFFSET-TOWER_OFFSET_X){ warning << "\tShot range of " << (int)shotRange << "\" is larger than the " << DEFENSE_EDGE_OFFSET-TOWER_OFFSET_X << "\" distance to the defenses. This will be capped to prevent issues.\n"; shotRange = DEFENSE_EDGE_OFFSET-TOWER_OFFSET_X; } // Create goal node at the centre of the tower goalNode = new Fieldnode(RED_TOWER_X, RED_TOWER_Y, Alliance::RED); // Initialise the graph with field nodes graph = Field::initGraph(); Shotnode *s; if(centreShotTime > 0){ // Middle centre s = getShotZone(shotRange, 0); s->time = centreShotTime; graph->addNode(s); shotnodes.push(s); // Connected to central courtyard and central 2 defenses graph->addEdge(s, &Field::redCourtyard[1]); graph->addDefenseEdge(s, &Field::redDefenses[2], false); graph->addDefenseEdge(s, &Field::redDefenses[3], false); // Add angled nodes if applicable if(centreAngle > 0){ // Top centre s = getShotZone(shotRange, -centreAngle); shotnodes.push(s); s->time = centreShotTime; graph->addNode(s); // Connected to upper/central courtyard and upper 2 defenses graph->addEdge(s, &Field::redCourtyard[2]); graph->addEdge(s, &Field::redCourtyard[1]); graph->addDefenseEdge(s, &Field::redDefenses[3], false); graph->addDefenseEdge(s, &Field::redDefenses[4], false); // Bottom centre s = getShotZone(shotRange, centreAngle); shotnodes.push(s); s->time = centreShotTime; graph->addNode(s); // Connected to lower courtyard and central 2 defenses graph->addEdge(s, &Field::redCourtyard[0]); graph->addEdge(s, &Field::redCourtyard[1]); graph->addDefenseEdge(s, &Field::redDefenses[0], false); graph->addDefenseEdge(s, &Field::redDefenses[1], false); graph->addDefenseEdge(s, &Field::redDefenses[2], false); // If the centre angle is higher than 40deg soft limit if(centreAngle > 40){ warning << "\tCentre angle of " << (int)centreAngle << "deg exceeds recommended limit of 40deg\n"; } } // If the cetre shot time is more than 20 seconds, there may be input issues if(centreShotTime > 20){ warning << "\tCentre shot time of " << (int)centreShotTime << "s is quite high, there may be broken input\n"; } } if(sideShotTime > 0){ // Upper side s = getShotZone(shotRange, -(90-sideAngle)); shotnodes.push(s); s->time = sideShotTime; graph->addNode(s); // Connect to upper courtyard and upper 2 defenses graph->addEdge(s, &Field::redCourtyard[2]); graph->addDefenseEdge(s, &Field::redDefenses[3], false); graph->addDefenseEdge(s, &Field::redDefenses[4], false); // Lower side s = getShotZone(shotRange, 90-sideAngle); shotnodes.push(s); s->time = sideShotTime; graph->addNode(s); // Connect to lower courtyard and lower 2 defenses graph->addEdge(s, &Field::redCourtyard[0]); graph->addDefenseEdge(s, &Field::redDefenses[0], false); graph->addDefenseEdge(s, &Field::redDefenses[1], false); // If the side angle is higher than 40deg soft limit if(sideAngle > 40){ warning << "\tSide angle of " << (int)sideAngle << "deg exceeds recommended limit of 40deg\n"; } // If the side shot time is more than 20 seconds, there may be input issues if(sideShotTime > 20){ warning << "\tSide shot time of " << (int)sideShotTime << "s is quite high, there may be broken input\n"; } } // If the warning string has content, then there are warnings to report if(warning.str().length() > 0){ printf("The following shot parameters exceed recommended tolerance:\n"); printf(warning.str().c_str()); // Allow the user to continue, as these warnings don't stop functionality printf("Do you wish to continue with the simulation? [y/n] "); char c; scanf("%c", &c); if(c != 'Y' && c != 'y'){ throw(invalid_parameter_exception("Shot configuration warnings not accepted")); } } // Connect tower and shotnodes to goal node with 0 distance graph->addNode(goalNode); // If the low time is 0 then the bot can't score there if(lowTime != 0){ graph->addDirectedEdge(&Field::redTowerTop, goalNode, 0); graph->addDirectedEdge(&Field::redTowerBottom, goalNode, 0); } for(auto i : shotnodes) { this->graph->addDirectedEdge(i.data, goalNode, 0); } // graph->printAdj(); } Shotnode *Robot::getShotZone(int range, int angle){ int x, y; float angleRad = angle*(M_PI/180); if(alliance == Alliance::RED){ x = goalNode->x + range*cos(angleRad); y = goalNode->y + range*sin(angleRad); } else if(alliance == Alliance::BLUE){ x = goalNode->x - range*cos(angleRad); y = goalNode->y + range*sin(angleRad); } else { x = 0; y = 0; } return new Shotnode(x, y, Alliance::NEUTRAL, Fieldnode::Type::SHOTNODE); } int Robot::crossTime(int id){ // If it's the low bar, then it is impossible or 1 second if(id == Defense::LOW_BAR){ return canLowbar; } //Shift the current defense into lower 4 bits, then mask return (defenses >> (id*4)) & 0xF; } int Robot::crossTime(Defense *d){ return crossTime(d->defType); } Event Robot::getEvent(){ Event e; e.location = location; e.path = path; e.r = this; e.time = wakeTime; switch(location->type){ case Fieldnode::Type::TOWER: e.type = Event::Type::SCORE_LOW; e.points = LOW_POINTS; break; case Fieldnode::Type::SHOTNODE: e.type = Event::Type::SCORE_HIGH; e.points = HIGH_POINTS; break; case Fieldnode::Type::DEFENSE: e.type = Event::Type::CROSS; e.points = ((Defense *) location)->cross(); break; default: e.type = Event::Type::PASSTHROUGH; e.points = 0; break; } if(e.location == intakeNode){ e.type == Event::Type::INTAKE; } return e; } void Robot::navUpdate(LinkedList<Event> *events){ // Add completed event to queue events->push(getEvent()); // If the robot has scored a ball, it now needs to get another if(location->type == Fieldnode::Type::TOWER || location->type == Fieldnode::Type::SHOTNODE){ hasBall = false; cyclesCompleted ++; } else if(location == intakeNode){ hasBall = true; } Graph::DijkstraNode *n; // If the robot has the ball, go to the tower, otherwise go back to pickup node if(hasBall){ n = getPath(goalNode); } else { n = getPath(&Field::redPassage[0]); } path = n; // Cycle back to find next node while(n->prev != NULL && n->prev->node!=location){ n = n->prev; } // Move the robot to the next node location = n->node; // Update the wake time, because point value is deducted from time, re-add it wakeTime += n->time; } Graph::DijkstraNode *Robot::getPath(Fieldnode *target){ Heap<Graph::DijkstraNode*> todo = Heap<Graph::DijkstraNode*>([](Graph::DijkstraNode *n1, Graph::DijkstraNode *n2)->bool{return n1->weight < n2->weight;}, [](Graph::DijkstraNode *d)->const char*{ if(d == NULL) return "N,N"; std::stringstream s; s << d->weight << "," << d->node->index; return s.str().c_str(); }); LinkedList<Graph::DijkstraNode*> completed; // Initialise the TODO array with inifinty // TODO: Don't add nodes which shouldn't be visited (eg other alliance, uncrossable defense) for(auto i : graph->nodes){ Graph::DijkstraNode *n = new Graph::DijkstraNode(); n->node = i.data; n->prev = NULL; n->weight = (i.data == location ? 0 : INT_MAX); n->time = 0; todo.push(n); } Graph::DijkstraNode *n; LinkedList<Graph::Edge> *adj; while(todo.pop(&n, 0)){ //Get the adjacency matrix for this node and iterate over it adj = graph->adjacency[n->node->index]; for(auto i : *adj){ Graph::Edge e = i.data; // If it's not in the list, then it has already been visited int todoIdx = todo.indexOf([e](Graph::DijkstraNode *n)->bool{return e.end == n->node;}); if(todoIdx == -1) continue; // Get weight of the edge Robot::EdgeData edgeData = getWeight(n, e); float weight = n->weight + edgeData.weight; float time = n->time + edgeData.time; if(edgeData.weight == INT_MAX){ weight = INT_MAX; } // If we have a new shorter path, update it if((*todo.peek(todoIdx))->weight > weight){ Graph::DijkstraNode *n2; // Get the node and remove it todo.pop(&n2, todoIdx); // Update the node n2->prev = n; n2->weight = weight; n2->time += time; // Reinsert it todo.push(n2); } // If we've reached the target if(e.end == target){ printf("DONE!\n"); Graph::DijkstraNode *returnNode = new Graph::DijkstraNode(); returnNode->node = e.end; returnNode->prev = n; returnNode->weight = weight; returnNode->time = time; return returnNode; } } // Add n to the completed list. This is done first so we can pop off the target node once reached printf("Completed %d\n", n->node->index); completed.push_front(n); } return NULL; } Robot::EdgeData Robot::getWeight(Graph::DijkstraNode *n, Graph::Edge e){ Robot::EdgeData out; // Base weight is time in seconds, measure by previous plus d*v out.weight = e.distance/speed; out.time = out.weight; // Don't go to nodes which are for the other alliance if(e.end->alliance != alliance && e.end->alliance != Alliance::NEUTRAL){ out.weight = INT_MAX; return out; } // Don't pathfind through shotnodes if(n->node->type == Fieldnode::Type::SHOTNODE && location != n->node){ out.weight = INT_MAX; return out; } if(e.end->type == Fieldnode::Type::DEFENSE){ int cTime = crossTime((Defense *) e.end); if(cTime != 0){ // Add cross time, subtract points for crossing out.weight += cTime - ((Defense *) e.end)->value*pointValue; out.time += cTime; } else { out.weight = INT_MAX; return out; } } else if (e.end->type == Fieldnode::Type::SHOTNODE && hasBall){ // Add time taken to shoot ball out.weight += ((Shotnode *) e.end)->time - HIGH_POINTS*pointValue; out.time += ((Shotnode *) e.end)->time;; } else if (e.end->type == Fieldnode::Type::TOWER && hasBall){ out.weight += lowTime - LOW_POINTS*pointValue; out.time += lowTime; } return out; } LinkedList<Robot *> Robot::parseCSV(std::string filename){ LinkedList<Robot *> bots; // Open the file FILE *f = fopen(filename.c_str(), "r"); if(f == NULL){ std::stringstream s; s << "Could not open file " << filename; throw file_open_exception(s.str()); } // Buffer for read lines. No line following the correct format will exceed 64 characters char line[BUFF_SIZE]; // Remove header line fgets (line, BUFF_SIZE, f); // Read all robots in file while(fgets (line, BUFF_SIZE, f) != NULL){ Robot *bot = new Robot(); // Read robot line // Data order: team,can_low,shot_range,centre_shot_time,side_shot_time,centre_angle,side_angle,low_time,defenses,speed int result = sscanf(line, "%d,%d,%d,%d,%d,%d,%d,%d,%lx,%f,%f", &(bot->team), &(bot->canLowbar), &(bot->shotRange), &(bot->centreShotTime), &(bot->sideShotTime), &(bot->centreAngle), &(bot->sideAngle), &(bot->lowTime), &(bot->defenses), &(bot->speed), &(bot->pointValue)); // Validate input // If less values are read than expected, something went wrong if(result != 11){ std::stringstream s; s << "Error while parsing robot " << bot->team << ". Read " << result << " values of 11."; throw csv_parsing_exception(s.str()); } // Check that team number is unique for(auto r : bots){ if(r.data->team == bot->team){ std::stringstream s; s << "Duplicate team number " << bot->team << ". Please change one."; throw invalid_parameter_exception(s.str()); } } // If the bot's speed is 0, then it can't go anywhere and there is no point in simulating if(bot->speed <= 0) throw invalid_parameter_exception("Robot's speed is negative or zero, this would prevent any motion. Speed must be a positive nonzero number."); // If the bot cannot cross any defenses, then there is no point in simulating if(!bot->defenses && !bot->canLowbar) throw invalid_parameter_exception("Robot cannot cross any defenses, this would prevent any gameplay. Robot must be able to cross at least one defense"); // If the bot can't score, then tehre is no point in simulating if(!bot->centreShotTime && !bot->sideShotTime && !bot->lowTime) throw invalid_parameter_exception("Robot cannot score, this prevents any gameplay. One scoring time must be nonzero"); // Finish setup // Convert from the fps input to ips for internal use bot->speed *= 12; // Set the bot's alliance. Currently this is hardcoded to red but may change in the future bot->alliance = Alliance::RED; // Set the bot's id. Currently hardcoded but this may change in the future bot->id = 0; bots.push(bot); } return bots; }
36.776995
198
0.579754
gregk27
7d0875a96111d7f90e98fb0e728852abd88e8cd9
26,348
hpp
C++
ccore/include/pyclustering/nnet/hhn.hpp
JosephChataignon/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
1,013
2015-01-26T19:50:14.000Z
2022-03-31T07:38:48.000Z
ccore/include/pyclustering/nnet/hhn.hpp
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
542
2015-01-20T16:44:32.000Z
2022-01-29T14:57:20.000Z
ccore/include/pyclustering/nnet/hhn.hpp
peterlau0626/pyclustering
bf4f51a472622292627ec8c294eb205585e50f52
[ "BSD-3-Clause" ]
262
2015-03-19T07:28:12.000Z
2022-03-30T07:28:24.000Z
/*! @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause */ #pragma once #include <fstream> #include <memory> #include <ostream> #include <set> #include <sstream> #include <tuple> #include <vector> #include <unordered_map> #include <pyclustering/utils/metric.hpp> #include <pyclustering/utils/random.hpp> #include <pyclustering/differential/differ_state.hpp> using namespace pyclustering::differential; using namespace pyclustering::utils::random; namespace pyclustering { namespace nnet { /*! @class hnn_parameters hhn.hpp pyclustering/nnet/hhn.hpp @brief Defines parameters of Hodgkin-Hixley Oscillatory Network. */ struct hnn_parameters { public: double m_nu = generate_uniform_random(-1.0, 1.0); /**< Intrinsic noise. */ double m_gNa = 120.0 * (1.0 + 0.02 * m_nu); /**< Maximal conductivity for sodium current. */ double m_gK = 36.0 * (1.0 + 0.02 * m_nu); /**< Maximal conductivity for potassium current. */ double m_gL = 0.3 * (1.0 + 0.02 * m_nu); /**< Maximal conductivity for leakage current. */ double m_vNa = 50.0; /**< Reverse potential of sodium current [mV]. */ double m_vK = -77.0; /**< Reverse potential of potassium current [mV]. */ double m_vL = -54.4; /**< Reverse potantial of leakage current [mV]. */ double m_vRest = -65.0; /**< Rest potential [mV]. */ double m_Icn1 = 5.0; /**< External current [mV] for central element 1. */ double m_Icn2 = 30.0; /**< External current [mV] for central element 2. */ double m_Vsyninh = -80.0; /**< Synaptic reversal potential [mV] for inhibitory effects. */ double m_Vsynexc = 0.0; /**< Synaptic reversal potential [mV] for exciting effects. */ double m_alfa_inhibitory = 6.0; /**< Alfa-parameter for alfa-function for inhibitory effect. */ double m_betta_inhibitory = 0.3; /**< Betta-parameter for alfa-function for inhibitory effect. */ double m_alfa_excitatory = 40.0; /**< Alfa-parameter for alfa-function for excitatoty effect. */ double m_betta_excitatory = 2.0; /**< Betta-parameter for alfa-function for excitatoty effect. */ double m_w1 = 0.1; /**< Strength of the synaptic connection from PN to CN1. */ double m_w2 = 9.0; /**< Strength of the synaptic connection from CN1 to PN. */ double m_w3 = 5.0; /**< Strength of the synaptic connection from CN2 to PN. */ double m_deltah = 650.0; /**< Period of time [ms] when high strength value of synaptic connection exists from CN2 to PN. */ double m_threshold = -10; /**< Threshold of the membrane potential that should exceeded by oscillator to be considered as an active. */ double m_eps = 0.16; /**< Devider of pulse threshold counter `1.0 / eps`. */ }; /*! @class basic_neuron_state hhn.hpp pyclustering/nnet/hhn.hpp @brief Basic state (applicable for central and peripheral oscillators) of a neuron in Hodgkin-Hixley Oscillatory Network. */ struct basic_neuron_state { public: double m_membrane_potential = 0.0; /**< Membrane potential of cenral neuron (V). */ double m_active_cond_sodium = 0.0; /**< Activation conductance of the sodium channel (m). */ double m_inactive_cond_sodium = 0.0; /**< Inactivaton conductance of the sodium channel (h). */ double m_active_cond_potassium = 0.0; /**< Activaton conductance of the sodium channel (h). */ bool m_pulse_generation = false; /**< Spike generation of central neuron. */ std::vector<double> m_pulse_generation_time = { }; /**< Timestamps of generated pulses. */ double m_Iext = 0.0; /**< External current [mV] for neuron. */ }; /*! @class central_element hhn.hpp pyclustering/nnet/hhn.hpp @brief Defines a state of the central neuron that is based on Hodgkin-Huxley model. */ struct central_element : public basic_neuron_state { }; /*! @class hhn_oscillator hhn.hpp pyclustering/nnet/hhn.hpp @brief Defines a state of the peripheral neuron that is based on Hodgkin-Huxley model. */ struct hhn_oscillator : public basic_neuron_state { double m_link_activation_time = 0.0; /**< The onset time of plasticity. */ double m_link_pulse_counter = 0.0; /**< The iteration counter of the spike duration. */ double m_link_weight3 = 0.0; /**< The modifiable GABAergic connection strength from Central Neuron 2 to the i-th peripheral neuron, representing the short-term plasticity. */ }; /*! @class hhn_dynamic hhn.hpp pyclustering/nnet/hhn.hpp @brief Output dynamic of the oscillatory network based on HHN. @details The output dynamic is a container that stores state of each neuron in the network on each simulation step. */ class hhn_dynamic { public: /*! @brief Defines what kind of information can be collected and stored by the dynamic. */ enum class collect { MEMBRANE_POTENTIAL, /**< Neuron's membrane potential. */ ACTIVE_COND_SODIUM, /**< Activation conductance of the sodium channel. */ INACTIVE_COND_SODIUM, /**< Inactivaton conductance of the sodium channel. */ ACTIVE_COND_POTASSIUM, /**< Activaton conductance of the sodium channel. */ }; /*! @brief Defines hash calculation for `hhn_dynamic::collect` type. @see hhn_dynamic::collect */ struct collect_hash { /*! @brief Calculates hash of the output dynamic component (membrane potential, conductance of the sodium channel, etc.). @param[in] t: output dynamic component value for that hash should be calculated. @returns Hash value of the output dynamic component. */ std::size_t operator()(hhn_dynamic::collect t) const { return static_cast<std::size_t>(t); } }; public: /*! @brief Defines shared pointer to the output dynamic of the HHN. */ using ptr = std::shared_ptr<hhn_dynamic>; /*! @brief Defines container to store specific state of each neuron of the HHN. */ using value_dynamic = std::vector<double>; /*! @brief Defines shared pointer to the container to store state of each neuron of the HHN. */ using value_dynamic_ptr = std::shared_ptr<value_dynamic>; /*! @brief Defines containers to store simulation process where specific state of each neuron on each iteration is stored. */ using evolution_dynamic = std::vector<value_dynamic>; /*! @brief Filter that defines what kind of states should be collected (membrane potential, conductance of the sodium channel, etc.). */ using network_collector = std::unordered_map<hhn_dynamic::collect, bool, hhn_dynamic::collect_hash>; /*! @brief Defines container to store the evolution of neurons per state type. @details The container is represented by a associative container where the key is a state that is collected and the value is a evolution of neurons that corresponds to the state. */ using network_dynamic = std::unordered_map<hhn_dynamic::collect, evolution_dynamic, hhn_dynamic::collect_hash>; /*! @brief Defines shared pointer to the network dynamic - container to store the evolution of neurons per state type. */ using network_dynamic_ptr = std::shared_ptr<network_dynamic>; private: network_collector m_enable = { { collect::MEMBRANE_POTENTIAL, true }, { collect::ACTIVE_COND_SODIUM, false }, { collect::INACTIVE_COND_SODIUM, false }, { collect::ACTIVE_COND_POTASSIUM, false } }; std::size_t m_amount_collections = 1; std::size_t m_size_dynamic = 0; std::size_t m_size_network = 0; network_dynamic_ptr m_peripheral_dynamic = std::make_shared<network_dynamic>(); network_dynamic_ptr m_central_dynamic = std::make_shared<network_dynamic>(); value_dynamic_ptr m_time = std::make_shared<value_dynamic>(); public: /*! @brief Default constructor of the output dynamic of the HHN. */ hhn_dynamic(); /*! @brief Default destructor of the output dynamic of the HHN. */ ~hhn_dynamic() = default; public: /*! @brief Returns amount of stored simulation steps (iterations). @return Amount of stored simulation steps (iterations). */ std::size_t size_dynamic() const; /*! @brief Returns amount of neurons in the network whose output dynamic was stored in the current output dynamic object. @return Amount of neurons in the HHN network. */ std::size_t size_network() const; /*! @brief Enable collecting of the specific output dynamic component for each neuron (membrane potential, conductance of the sodium channel, etc.). @param[in] p_state: output dynamic component that should be collected for each neuron. */ void enable(const hhn_dynamic::collect p_state); /*! @brief Enable collecting of a set of output dynamic components for each neuron (membrane potential, conductance of the sodium channel, etc.). @param[in] p_types: iterable container that contains output dynamic components that should be collected for each neuron. */ template <class ContainerType> void enable(const ContainerType & p_types); /*! @brief Enable collecting of all possible output dynamic components for each neuron (membrane potential, conductance of the sodium channel, etc.). */ void enable_all(); /*! @brief Disable collecting of the specific output dynamic component for each neuron (membrane potential, conductance of the sodium channel, etc.). @param[in] p_state: output dynamic component that should not be collected for each neuron. */ void disable(const hhn_dynamic::collect p_state); /*! @brief Disable collecting of a set of output dynamic components for each neuron (membrane potential, conductance of the sodium channel, etc.). @param[in] p_types: iterable container that contains output dynamic components that should not be collected for each neuron. */ template <class ContainerType> void disable(const ContainerType & p_types); /*! @brief Disable collecting of all possible output dynamic components for each neuron (membrane potential, conductance of the sodium channel, etc.). */ void disable_all(); /*! @brief Returns collecting neuron states (membrane potential, conductance of the sodium channel, etc.). @param[out] p_enabled: a container where collecting states are going to be placed. */ void get_enabled(std::set<hhn_dynamic::collect> & p_enabled) const; /*! @brief Returns neurons states that are not collected (membrane potential, conductance of the sodium channel, etc.). @param[out] p_disabled: a container where non-collecting states are going to be placed. */ void get_disabled(std::set<hhn_dynamic::collect> & p_disabled) const; /*! @brief Stores current state of the oscillatory network that is defined by timestamp, peripheral and central neurons. @param[in] p_time: current simulation time. @param[in] p_peripheral: container with states of peripheral neurons. @param[in] p_central: container with states of central neurons. */ void store(const double p_time, const std::vector<hhn_oscillator> & p_peripheral, const std::vector<central_element> & p_central); /*! @brief Reserves memory for the evolution that is defined by amount of iterations for simulation. @param[in] p_dynamic_size: size of the dynamic evolution. */ void reserve(const std::size_t p_dynamic_size); /*! @brief Returns dynamic of peripheral neurons for the specified state (membrane potential, conductance of the sodium channel, etc.). @param[in] p_type: state of neuron for which evolution is required. @return Dynamic of peripheral neurons for the specified state. */ evolution_dynamic & get_peripheral_dynamic(const hhn_dynamic::collect & p_type); /*! @brief Returns full dynamic of peripheral neurons. @return Full dynamic of peripheral neurons. */ network_dynamic_ptr get_peripheral_dynamic() const; /*! @brief Returns full dynamic of central neurons. @returns Full dynamic of central neurons. */ network_dynamic_ptr get_central_dynamic() const; /*! @brief Returns all timestamps of simulation process of the oscillatory network. @return All timestamps of simulation process of the oscillatory network. */ value_dynamic_ptr get_time() const; /*! @brief Returns dynamic of central neurons for the specified state (membrane potential, conductance of the sodium channel, etc.). @param[in] p_type: neuron state for which evolution is required. @return Dynamic of central neurons for the specified state. */ evolution_dynamic & get_central_dynamic(const hhn_dynamic::collect & p_type); /*! @brief Returns state value for specific peripheral neuron on specified iteration. @param[in] p_iteration: iteration of simulation process of the oscillatory network. @param[in] p_index: neuron index in the oscillatory network. @param[in] p_type: neuron state value type (membrane potential, conductance of the sodium channel, etc.). @return State value for specific peripheral neuron on specified iteration. */ double get_peripheral_value(const std::size_t p_iteration, const std::size_t p_index, const hhn_dynamic::collect p_type) const; /*! @brief Returns state value for specific central neuron on specified iteration. @details The oscillatory network always has only two central neurons that forms central unit. Thus there are two possible indexes could be: 0 and 1. @param[in] p_iteration: iteration of simulation process of the oscillatory network. @param[in] p_index: neuron index in the oscillatory network. @param[in] p_type: neuron state value type (membrane potential, conductance of the sodium channel, etc.). @return State value for specific central neuron on specified iteration. */ double get_central_value(const std::size_t p_iteration, const std::size_t p_index, const hhn_dynamic::collect p_type) const; private: void get_collected_types(const bool p_enabled, std::set<hhn_dynamic::collect> & p_types) const; void reserve_collection(const hhn_dynamic::collect p_state, const std::size_t p_size); void store_membrane_potential(const std::vector<hhn_oscillator> & p_peripheral, const std::vector<central_element> & p_central); void store_active_cond_sodium(const std::vector<hhn_oscillator> & p_peripheral, const std::vector<central_element> & p_central); void store_inactive_cond_sodium(const std::vector<hhn_oscillator> & p_peripheral, const std::vector<central_element> & p_central); void store_active_cond_potassium(const std::vector<hhn_oscillator> & p_peripheral, const std::vector<central_element> & p_central); static void reserve_dynamic_collection(const hhn_dynamic::collect p_state, const std::size_t p_size, network_dynamic & p_dynamic); static void initialize_collection(network_dynamic & p_dynamic); public: /*! @brief Comparison operator `==` to compare output dynamics. @param[in] p_other: another output dynamic that should be compared with current. @return `true` if output dynamic objects are equal, otherwise `false`. */ bool operator==(const hhn_dynamic & p_other) const; /*! @brief Writes to an output stream output dynamic of the oscillatory network. @param[in] p_stream: output stream for writing. @param[in] p_dynamic: output dynamic of the network that should be written. */ friend std::ostream& operator<<(std::ostream & p_stream, const hhn_dynamic & p_dynamic); }; template <class ContainerType> void hhn_dynamic::enable(const ContainerType & p_types) { for (auto & type : p_types) { enable(type); } } template <class ContainerType> void hhn_dynamic::disable(const ContainerType & p_types) { for (auto & type : p_types) { disable(type); } } /*! @class hhn_dynamic_reader hhn.hpp pyclustering/nnet/hhn.hpp @brief Reader of the output dynamic of the oscillatory network based on Hodgkin-Huxley neurons. @details The dynamic reader reads the output dynamic from a text file with the specific format. */ class hhn_dynamic_reader { private: std::string m_filename; hhn_dynamic * m_dynamic = nullptr; std::ifstream m_file_stream; std::vector<hhn_dynamic::collect> m_order = { }; std::size_t m_size_network = 0; public: /*! @brief Default constructor of the dynamic reader of HHN. */ hhn_dynamic_reader() = default; /*! @brief Constructor of the dynamic reader of HHN where path to a file where output dynamic of the network is stored. */ explicit hhn_dynamic_reader(const std::string & p_filename); /*! @brief Default destructor of the dynamic reader of HHN. */ ~hhn_dynamic_reader(); public: /*! @brief Reads output dynamic of the network to the specified output dynamic container. @param[in] p_dynamic: output dynamic container to which output dynamic from the file should be placed. */ void read(hhn_dynamic & p_dynamic); private: void parse_size_header(); void parse_enable_header(); void parse_dynamic(); void extract_dynamic(const std::string & p_line, double & p_time, std::vector<hhn_oscillator> & p_peripheral, std::vector<central_element> & p_central); void extract_state(std::istringstream & p_stream, basic_neuron_state & p_state) const; static void extract_size_header(const std::string & p_line, std::size_t & p_size_dynamic, std::size_t & p_size_network); static void extract_enable_header(const std::string & p_line, std::vector<hhn_dynamic::collect> & p_collect); }; /*! @brief Defines external input (stimulus) to the oscillatory network. @details External input type is represented by a container with a random access to its elements. */ using hhn_stimulus = std::vector<double>; /*! @class hhn_network hhn.hpp pyclustering/nnet/hhn.hpp @brief The two-layer oscillatory network that is based on Hodgkin-Huxley neurons. @details The oscillatory network consists of two types of neurons: peripheral neurons and central neurons. Peripheral neurons represent feature detectors in the primary areas of the neocortex that are activated by external stimuli. It assumed that the external input to peripheral neurons is sufficiently large to cause their firing at some particular frequency. Considering image segmentation problem and visual attention modelling, the peripheral neurons are located on another grid of the same size as the an image, with each peripheral neuron receiving a signal from the pixel whose location on the grid is identical to the location of the peripheral neuron. The oscillatory network has two central neurons that forms so-called the central unit. The central unit is an extremely simplified version of the central executive. The 1st central neuron enables attention to be focused on a selected subset of peripheral neurons. The 2nd central neuron controls the shift of attention from one stimulus to another. The architecture of the oscillatory network is presented on figure 1. @image html hhn_architecture.png "Fig. 1. The architecture of the oscillatory network based on Hodgkin-Huxley neurons." The Implementation is based on paper @cite article::nnet::hnn::1. */ class hhn_network { private: enum: std::size_t { POSITION_MEMBRAN_POTENTIAL = 0, POSITION_ACTIVE_COND_SODIUM, POSITION_INACTIVE_COND_SODIUM, POSITION_ACTIVE_COND_POTASSIUM, POSITION_AMOUNT }; private: using hhn_state = differ_result<double>; using hhn_states = std::vector< hhn_state >; private: std::vector<hhn_oscillator> m_peripheral = { }; std::vector<central_element> m_central = { }; hhn_stimulus * m_stimulus = nullptr; hnn_parameters m_params; public: /*! @brief Default constructor of the oscillatory network based on Hodgkin-Huxley network. */ hhn_network() = default; /*! @brief Constructor of the oscillatory network based on Hodgkin-Huxley network that creates the network with specified size and parameters. @param[in] p_size: amount of neurons in the oscillatory network. @param[in] p_parameters: parameters of the oscillatory network that defines its behaviour. */ hhn_network(const std::size_t p_size, const hnn_parameters & p_parameters); /*! @brief Default destructor of the oscillatory network based on Hodgkin-Huxley network. */ ~hhn_network() = default; public: /*! @brief Runs oscillatory network simulation for the specific time with specified external inputs. @param[in] p_steps: number steps of simulations during simulation. @param[in] p_time: time of simulation. @param[in] p_solver: type of the solver for the simulation. @param[in] p_stimulus: external inputs (stimulus) to the network. @param[in] p_output_dynamic: output dynamic of the network. @return Amount of neurons that are in the oscillatory network. */ void simulate(const std::size_t p_steps, const double p_time, const solve_type p_solver, const hhn_stimulus & p_stimulus, hhn_dynamic & p_output_dynamic); /*! @brief Returns size of the oscillatory network. @details Size of the network is defined by amount of neurons (oscillators) in it. @return Amount of neurons that are in the oscillatory network. */ std::size_t size() const; private: void store_dynamic(const double p_time, hhn_dynamic & p_dynamic); void calculate_states(const solve_type p_solver, const double p_time, const double p_step, const double p_int_step); void calculate_peripheral_states(const solve_type p_solver, const double p_time, const double p_step, const double p_int_step, hhn_states & p_next_states); void calculate_central_states(const solve_type p_solver, const double p_time, const double p_step, const double p_int_step, hhn_states & p_next_states); void perform_calculation(const solve_type p_solver, const double p_time, const double p_step, const double p_int_step, const differ_state<double> & p_inputs, const differ_extra<> & p_extra, hhn_state & p_next_states); void neuron_states(const double t, const differ_state<double> & inputs, const differ_extra<void *> & argv, differ_state<double> & outputs) const; double peripheral_external_current(const std::size_t p_index) const; double peripheral_synaptic_current(const std::size_t p_index, const double p_time, const double p_membrane) const; double central_first_synaptic_current(const double p_time, const double p_membrane) const; void initialize_current(); void update_peripheral_current(); void assign_neuron_states(const double p_time, const double p_step, const hhn_states & p_next_peripheral, const hhn_states & p_next_central); static double alpha_function(const double p_time, const double p_alfa, const double p_betta); template <class NeuronType> static void pack_equation_input(const NeuronType & p_neuron, differ_state<double> & p_inputs); template <class NeuronType> static void unpack_equation_output(const hhn_state & p_outputs, NeuronType & p_neuron); }; template <class NeuronType> void hhn_network::pack_equation_input(const NeuronType & p_neuron, differ_state<double> & p_inputs) { p_inputs.resize(POSITION_AMOUNT); p_inputs[POSITION_MEMBRAN_POTENTIAL] = p_neuron.m_membrane_potential; p_inputs[POSITION_ACTIVE_COND_SODIUM] = p_neuron.m_active_cond_sodium; p_inputs[POSITION_INACTIVE_COND_SODIUM] = p_neuron.m_inactive_cond_sodium; p_inputs[POSITION_ACTIVE_COND_POTASSIUM] = p_neuron.m_active_cond_potassium; } template <class NeuronType> void hhn_network::unpack_equation_output(const hhn_state & p_outputs, NeuronType & p_neuron) { p_neuron.m_membrane_potential = p_outputs[0].state[POSITION_MEMBRAN_POTENTIAL]; p_neuron.m_active_cond_sodium = p_outputs[0].state[POSITION_ACTIVE_COND_SODIUM]; p_neuron.m_inactive_cond_sodium = p_outputs[0].state[POSITION_INACTIVE_COND_SODIUM]; p_neuron.m_active_cond_potassium = p_outputs[0].state[POSITION_ACTIVE_COND_POTASSIUM]; } } }
35.847619
222
0.670981
JosephChataignon
7d08b77c8a8b9574512877ad3a2afc49d0029fda
8,399
cpp
C++
src/tracker/TrackerSystem_simulate.cpp
bitbloop/KalmanFilter
f1616134d6eeeab05afc56bb6b0a921fad106d7f
[ "MIT" ]
1
2022-03-29T15:55:01.000Z
2022-03-29T15:55:01.000Z
src/tracker/TrackerSystem_simulate.cpp
bitbloop/KalmanFilter
f1616134d6eeeab05afc56bb6b0a921fad106d7f
[ "MIT" ]
null
null
null
src/tracker/TrackerSystem_simulate.cpp
bitbloop/KalmanFilter
f1616134d6eeeab05afc56bb6b0a921fad106d7f
[ "MIT" ]
1
2022-03-18T07:29:55.000Z
2022-03-18T07:29:55.000Z
#include "TrackerSystem.h" #include "TrackerSystemInputHandler.h" /** Do the simulation loop. */ void TrackerSystem::Loop() { { // Fast forward the simulation at the start. math::time::Timer fast_forward_timer; FastForward(TIME_TO_FAST_FORWARD, FAST_FORWARD_STEP); double fast_forward_end_time{ fast_forward_timer.elapsed() }; std::cout << "Fast forward for " << TIME_TO_FAST_FORWARD << "s took " << fast_forward_end_time << "s." << std::endl; } // Rest the global simulation time. global_timer.reset(); double last_frame_time{ global_timer.elapsed() }; // Until we signal for the window to close while (!::renderer::window::should_window_close()) { const auto global_t{ global_timer.elapsed() }; const auto delta_t{ global_t - last_frame_time }; last_frame_time = global_t; Update(global_t, delta_t); Render(); glFinish(); ::renderer::window::pool_events_and_swap_buffers(); } } /** Perform the simulation update step. */ void TrackerSystem::Update(const double& global_t, const double& delta_t) { // Upate the world objects object_X->Update(global_t, delta_t); object_C->Update(global_t, delta_t); // ----------------------------------------------------------------------------------- // Give the sensors the new ground truth variable. object_X_acceleration_sensor.SetGroundTruth(object_X->GetAcceleration()); object_X_acceleration_sensor.QueryForSensorValueChangedEvent(global_t); object_C_acceleration_sensor.SetGroundTruth(object_C->GetAcceleration()); object_C_acceleration_sensor.QueryForSensorValueChangedEvent(global_t); // Only set the sensor ground truth if the object is within the 3m range const auto dXC{ glm::pow(object_X->GetPosition() - object_C->GetPosition(),{ 2, 2, 2 }) }; if (dXC.x + dXC.y + dXC.z <= 9) { object_X_position_sensor.SetGroundTruth(object_X->GetPosition()); object_X_position_sensor.QueryForSensorValueChangedEvent(global_t); } // ----------------------------------------------------------------------------------- // If the interval to update the filter is here, update the filter with the new sensor values. if (next_filter_update_t <= global_t && next_filter_update_t != -1) { next_filter_update_t = global_t + filter_update_interval_t; { const auto estimate_X_position{ object_X_position_sensor.GetEstimate(global_t) }; const auto estimate_X_acceleration{ object_X_acceleration_sensor.GetEstimate(global_t) }; const auto estimate_C_acceleration{ object_C_acceleration_sensor.GetEstimate(global_t) }; // convert the measurements to camera space const auto estimate_position{ estimate_X_position - object_C->GetPosition() }; const auto estimate_acceleration{ estimate_X_acceleration - estimate_C_acceleration }; // The code below will get and set proper filter values depending on the chosen model. #ifdef DATA_3D { Eigen::VectorXd measurementv3d(3); measurementv3d << estimate_position.x, estimate_position.y, estimate_position.z; object_X_filter_pos_xyz.Update(measurementv3d); } { Eigen::VectorXd measurementv3d(6); measurementv3d << estimate_position.x, estimate_position.y, estimate_position.z, estimate_acceleration.x, estimate_acceleration.y, estimate_acceleration.z; object_X_filter_pos_acc_xyz.Update(measurementv3d); } #else { Eigen::VectorXd measurementv2d(4); measurementv2d << estimate_position.x, estimate_position.y, estimate_acceleration.x, estimate_acceleration.y; object_X_filter_xy.Update(measurementv2d); } #endif } #ifdef DATA_3D { // Update the dead reckoning algorithm #ifdef TRACK_KALMAN_FILTER_POSITION_ONLY const auto filter_estimate{ object_X_filter_pos_xyz.GetEstimate() }; const auto glm_filter_estimate_pos{ glm::dvec3({ filter_estimate[0], filter_estimate[1], filter_estimate[2] }) }; object_X_filter_dead_reckoning.SetSensorReading(glm_filter_estimate_pos, glm::dvec3(0), global_t); #else const auto filter_estimate{ object_X_filter_pos_acc_xyz.GetEstimate() }; const auto glm_filter_estimate_pos{ glm::dvec3({ filter_estimate[0], filter_estimate[1], filter_estimate[2] }) }; const auto glm_filter_estimate_acc{ glm::dvec3({ filter_estimate[3], filter_estimate[4], filter_estimate[5] }) }; object_X_filter_dead_reckoning.SetSensorReading(glm_filter_estimate_pos, glm_filter_estimate_acc, global_t); #endif } #else // Update the dead reckoning algorithm const auto filter_estimate{ object_X_filter_xy.GetEstimate() }; const auto glm_filter_estimate_pos{ glm::dvec3({ filter_estimate[0], filter_estimate[1], 0 }) }; const auto glm_filter_estimate_acc{ glm::dvec3({ filter_estimate[4], filter_estimate[5], 0 }) }; object_X_filter_dead_reckoning.SetSensorReading(glm_filter_estimate_pos, glm_filter_estimate_acc, global_t); #endif } // ----------------------------------------------------------------------------------- // Update and bake the graphs // Mark the next filter update interval if it is the first iteration of the loop if (next_graph_bake_update_t == 0) next_graph_bake_update_t = global_t + GRAPH_DATA_COLLECTION_DURATION; // Add more measurements to the graphs if the graphs were not baked and it is the allowed time to record a new measurement. if (!analysis.IsBaked() && (global_t < next_graph_bake_update_t || continuous_graph_data_capture) && !stop_graph_data_capture) { const auto ground_truth_position_X{ object_X->GetPosition() }; const auto ground_truth_position_C{ object_C->GetPosition() }; const auto sensor_read_position{ object_X_position_sensor.GetEstimate(global_t) - object_C->GetPosition() }; const auto dead_reckoning_position{ object_X_filter_dead_reckoning.GetPositionEstimate(global_t) }; const auto sensor_read_acceleration{ object_X_acceleration_sensor.GetEstimate(global_t) - object_C_acceleration_sensor.GetEstimate(global_t) }; const auto dead_reckoning_acceleration{ object_X_filter_dead_reckoning.GetAccelerationEstimate(global_t) }; // Future position estimation if (global_t >= future_resolution_time) { const glm::dvec3 d{ (ground_truth_position_X - ground_truth_position_C) - future_position }; last_future_prediction_error = { (d.x*d.x + d.y*d.y + d.z*d.z) }; future_resolution_time = global_t + FUTURE_PREDICTION_TIME; future_position = object_X_filter_dead_reckoning.GetPositionEstimate(global_t + FUTURE_PREDICTION_TIME); } analysis.AddPoint(ground_truth_position_X, ground_truth_position_C, sensor_read_position, sensor_read_acceleration, dead_reckoning_position, dead_reckoning_acceleration, last_future_prediction_error); } // If we are not capturing, and also the graphs are not baked, bake them. else if (!analysis.IsBaked()) { analysis.BakeGraphs(pointcloud_shader_id); } } /** Fast forward the soimulation */ void TrackerSystem::FastForward(const double & total_time, const double& time_step) { double ff_global_t{ 0 }; // The global time relative to the fast forward state // Pause the sensor threads object_X_position_sensor.SetPauseThread(true); object_X_acceleration_sensor.SetPauseThread(true); object_C_acceleration_sensor.SetPauseThread(true); // Set the states to start collecting data StartContinousCapture(); // Update the world Update(0, time_step); while (ff_global_t < total_time) { // Advance the total time elapsed ff_global_t += time_step; // Simulate sensors firing object_X_position_sensor.SimulateSensorReading(ff_global_t); object_X_position_sensor.QueryForSensorValueChangedEvent(ff_global_t); object_X_acceleration_sensor.SimulateSensorReading(ff_global_t); object_X_acceleration_sensor.QueryForSensorValueChangedEvent(ff_global_t); object_C_acceleration_sensor.SimulateSensorReading(ff_global_t); object_C_acceleration_sensor.QueryForSensorValueChangedEvent(ff_global_t); // Update the world Update(ff_global_t, time_step); } // Set the states to finish collecting data StopContinuousCapture(); // Reset to factory settings object_X_position_sensor.Reset(); object_X_acceleration_sensor.Reset(); object_C_acceleration_sensor.Reset(); object_X->Reset(); object_C->Reset(); // Disable further filter updating, since we are not collecting data next_filter_update_t = -1; // Resume the sensor threads object_X_position_sensor.SetPauseThread(false); object_X_acceleration_sensor.SetPauseThread(false); object_C_acceleration_sensor.SetPauseThread(false); }
40.970732
202
0.761162
bitbloop
7d09026a7e4deac6cb531e1c2eaef6b98de179d9
426
hxx
C++
include/configuration.hxx
nshcat/fractal
6be4c9684c25520b231375006a51428e37cf56bc
[ "MIT" ]
null
null
null
include/configuration.hxx
nshcat/fractal
6be4c9684c25520b231375006a51428e37cf56bc
[ "MIT" ]
null
null
null
include/configuration.hxx
nshcat/fractal
6be4c9684c25520b231375006a51428e37cf56bc
[ "MIT" ]
null
null
null
#pragma once #include <thread> #include <string> #include <types.hxx> namespace fractal { // Stores information that is configurable by the user struct configuration { dimension_type m_WindowSize{ 600, 400 }; ::std::size_t m_ThreadCount{ std::thread::hardware_concurrency() }; ::std::size_t m_Iterations{ 500 }; ::std::size_t m_Divisions{ 1 }; ::std::string m_ImagePath{ }; bool m_NoGraphics{ false }; }; }
20.285714
69
0.701878
nshcat
7d09f2089f6e0d9e664cbc5d6eff9fb32246f7da
1,077
cpp
C++
tests/specs/verboseRunnerTests.cpp
stephengaito/cUtils
635be6eaf989e474337d0384bde4a7faca7a69aa
[ "MIT" ]
null
null
null
tests/specs/verboseRunnerTests.cpp
stephengaito/cUtils
635be6eaf989e474337d0384bde4a7faca7a69aa
[ "MIT" ]
null
null
null
tests/specs/verboseRunnerTests.cpp
stephengaito/cUtils
635be6eaf989e474337d0384bde4a7faca7a69aa
[ "MIT" ]
null
null
null
#ifndef protected #define protected public #endif #include <cUtils/specs/verboseRunner.h> class SimpleTestClass { public: bool invariant(void) { throw AssertionFailure("invariant failed"); return false; } SimpleTestClass(void) { testInt = 1; }; ~SimpleTestClass(void) { ASSERT_INSIDE_DELETE(invariant()); ASSERT_INSIDE_DELETE(false); testInt = 0; }; int testInt; }; describeMM(VerboseRunner, "should have four assertion failures") { specSize(VerboseRunner); it("simple AssertionFailure", "SHOULD FAIL") { throw AssertionFailure("simple assertion failure"); } endIt(); it("simple ASSERT failure", "SHOULD FAIL", "WITH Recent call stack") { ASSERT_MESSAGE(false, "this is an assert with message"); } endIt(); it("ASSERT failure inside delete", "SHOULD FAIL twice", "BUT throwing exceptions inside destructors is not supported", "AND results in immediate program termination") { SimpleTestClass *testClass = new SimpleTestClass(); delete testClass; } endIt(); } endDescribe(VerboseRunner);
21.979592
72
0.70195
stephengaito
7d0a1d436efbf4f8ef8ccd9bf1a9c61fab3bce51
3,136
hpp
C++
src/backends/reference/workloads/Lstm.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
856
2018-03-09T17:26:23.000Z
2022-03-24T21:31:33.000Z
src/backends/reference/workloads/Lstm.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
623
2018-03-13T04:40:42.000Z
2022-03-31T09:45:17.000Z
src/backends/reference/workloads/Lstm.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
284
2018-03-09T23:05:28.000Z
2022-03-29T14:42:28.000Z
// // Copyright © 2021 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <armnn/TypesUtils.hpp> #include <backendsCommon/WorkloadData.hpp> #include "Encoders.hpp" #include "Decoders.hpp" namespace armnn { void LstmImpl(const LstmDescriptor& descriptor, const TensorInfo& inputInfo, const TensorInfo& outputInfo, const TensorShape& inputToOutputWeightsShape, const TensorShape& recurrentToOutputWeightsShape, std::unique_ptr<Decoder<float>>& inputData, std::unique_ptr<Decoder<float>>& outputStateIn, std::unique_ptr<Decoder<float>>& cellStateIn, std::unique_ptr<Encoder<float>>& outputStateOut, std::unique_ptr<Encoder<float>>& cellStateOut, std::unique_ptr<Encoder<float>>& output, std::unique_ptr<Decoder<float>>& cellStateOutDecoder, std::unique_ptr<Decoder<float>>& outputDecoder, std::unique_ptr<Decoder<float>>& inputToInputWeightsTensor, std::unique_ptr<Decoder<float>>& inputToForgetWeightsTensor, std::unique_ptr<Decoder<float>>& inputToCellWeightsTensor, std::unique_ptr<Decoder<float>>& inputToOutputWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToInputWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToForgetWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToCellWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToOutputWeightsTensor, std::unique_ptr<Decoder<float>>& cellToInputWeightsTensor, std::unique_ptr<Decoder<float>>& cellToForgetWeightsTensor, std::unique_ptr<Decoder<float>>& cellToOutputWeightsTensor, std::unique_ptr<Decoder<float>>& inputGateBiasTensor, std::unique_ptr<Decoder<float>>& forgetGateBiasTensor, std::unique_ptr<Decoder<float>>& cellBiasTensor, std::unique_ptr<Decoder<float>>& outputGateBiasTensor, std::unique_ptr<Decoder<float>>& projectionWeightsTensor, std::unique_ptr<Decoder<float>>& projectionBiasTensor, std::unique_ptr<Decoder<float>>& inputLayerNormWeights, std::unique_ptr<Decoder<float>>& forgetLayerNormWeights, std::unique_ptr<Decoder<float>>& cellLayerNormWeights, std::unique_ptr<Decoder<float>>& outputLayerNormWeights, std::unique_ptr<Encoder<float>>& inputGateScratch, std::unique_ptr<Encoder<float>>& cellScratch, std::unique_ptr<Encoder<float>>& forgetGateScratch, std::unique_ptr<Encoder<float>>& outputGateScratch, std::unique_ptr<Decoder<float>>& inputGateScratchDecoder, std::unique_ptr<Decoder<float>>& cellScratchDecoder, std::unique_ptr<Decoder<float>>& forgetGateScratchDecoder, std::unique_ptr<Decoder<float>>& outputGateScratchDecoder, float layerNormEpsilon); } //namespace armnn
50.580645
78
0.660714
sahilbandar
7d0a62159844187c30c4387853782473f2295c65
2,889
cpp
C++
modules/itmx/src/imagesources/DepthCorruptingImageSourceEngine.cpp
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
197
2015-10-01T07:23:01.000Z
2022-03-23T03:02:31.000Z
modules/itmx/src/imagesources/DepthCorruptingImageSourceEngine.cpp
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
16
2016-03-26T13:01:08.000Z
2020-09-02T09:13:49.000Z
modules/itmx/src/imagesources/DepthCorruptingImageSourceEngine.cpp
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
62
2015-10-03T07:14:59.000Z
2021-08-31T08:58:18.000Z
/** * itmx: DepthCorruptingImageSourceEngine.cpp * Copyright (c) Torr Vision Group, University of Oxford, 2019. All rights reserved. */ #include "imagesources/DepthCorruptingImageSourceEngine.h" #include <ITMLib/Engines/ViewBuilding/Shared/ITMViewBuilder_Shared.h> using namespace ITMLib; namespace itmx { //#################### CONSTRUCTORS #################### DepthCorruptingImageSourceEngine::DepthCorruptingImageSourceEngine(ImageSourceEngine *innerSource, double missingDepthFraction, float depthNoiseSigma) : m_depthNoiseSigma(depthNoiseSigma), m_innerSource(innerSource), m_rng(12345) { if(missingDepthFraction > 0.0) { m_missingDepthMask.reset(new ORBoolImage(innerSource->getDepthImageSize(), true, false)); bool *missingDepthMask = m_missingDepthMask->GetData(MEMORYDEVICE_CPU); for(size_t i = 0, size = m_missingDepthMask->dataSize; i < size; ++i) { missingDepthMask[i] = m_rng.generate_real_from_uniform<double>(0.0, 1.0) <= missingDepthFraction; } } } //#################### PUBLIC MEMBER FUNCTIONS #################### ITMRGBDCalib DepthCorruptingImageSourceEngine::getCalib() const { return m_innerSource->getCalib(); } Vector2i DepthCorruptingImageSourceEngine::getDepthImageSize() const { return m_innerSource->getDepthImageSize(); } void DepthCorruptingImageSourceEngine::getImages(ORUChar4Image *rgb, ORShortImage *rawDepth) { const Vector2f depthCalibParams = getCalib().disparityCalib.GetParams(); // Get the uncorrupted images. m_innerSource->getImages(rgb, rawDepth); #ifdef WITH_OPENMP #pragma omp parallel for #endif for(int y = 0; y < rawDepth->noDims.y; ++y) { for(int x = 0; x < rawDepth->noDims.x; ++x) { const int offset = y * rawDepth->noDims.x + x; short& rawDepthValue = rawDepth->GetData(MEMORYDEVICE_CPU)[offset]; // If desired, zero out any depth values that should be missing. if(m_missingDepthMask && m_missingDepthMask->GetData(MEMORYDEVICE_CPU)[offset]) { rawDepthValue = 0; } // If desired, corrupt any depth values that still exist with zero-mean, depth-dependent Gaussian noise. if(m_depthNoiseSigma > 0.0f && rawDepthValue != 0) { float depth = 0.0f; convertDepthAffineToFloat(&depth, 0, 0, &rawDepthValue, rawDepth->noDims, depthCalibParams); #ifdef WITH_OPENMP #pragma omp critical #endif depth += m_rng.generate_from_gaussian(0.0f, m_depthNoiseSigma) * depth; rawDepthValue = CLAMP(static_cast<short>(ROUND((depth - depthCalibParams.y) / depthCalibParams.x)), 1, 32000); } } } rawDepth->UpdateDeviceFromHost(); } Vector2i DepthCorruptingImageSourceEngine::getRGBImageSize() const { return m_innerSource->getRGBImageSize(); } bool DepthCorruptingImageSourceEngine::hasMoreImages() const { return m_innerSource->hasMoreImages(); } }
30.734043
150
0.709242
torrvision
7d0a8f4b0c580058655d52745c5c9355d8295677
1,077
hpp
C++
Nacro/SDK/FN_AssetRegistry_structs.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_AssetRegistry_structs.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_AssetRegistry_structs.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Script Structs //--------------------------------------------------------------------------- // ScriptStruct AssetRegistry.AssetBundleEntry // 0x0028 struct FAssetBundleEntry { struct FPrimaryAssetId BundleScope; // 0x0000(0x0010) struct FName BundleName; // 0x0010(0x0008) (ZeroConstructor, IsPlainOldData) TArray<struct FStringAssetReference> BundleAssets; // 0x0018(0x0010) (ZeroConstructor) }; // ScriptStruct AssetRegistry.AssetBundleData // 0x0010 struct FAssetBundleData { TArray<struct FAssetBundleEntry> Bundles; // 0x0000(0x0010) (ZeroConstructor) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
29.916667
161
0.457753
Milxnor
7d0d89f6393eaa16a5a92f1444eb5c9a73ae4abf
5,433
cpp
C++
src/HADemoService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
src/HADemoService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
src/HADemoService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
/** * @copyright (c) 2017 Mark R. Jenkins. All rights reserved. * @file HADemoService.cpp * * @author MJenkins, ENPM 808X Spring 2017 * @date May 10, 2017 - Creation * * @brief Provides a Home Automation "demo" service (sends HBBehavior goals to bot_actor action server) * * This service provides a way to manually activate Home Automation system requests * for BotBehaviors by accepting a service request containing a behavior name and * a number of repetitions, then using an action client to send the same behavior * name and repetitions to the bot_actor action server, which executes the behavior * (if present in its repertoire). When the BotBehavior action ends, the service * call will return to the requestor with an outcome (reached the goal, or not). * * * * * BSD 3-Clause License * * Copyright (c) 2017, Mark Jenkins * 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 "homebot/HADemoService.hpp" /** * @brief Constructor for HADemoService that creates a demonstration service object populated with a service client and callback to use when service requests are received * @param pHAClients */ HADemoService::HADemoService(HAClients& pHAClients) : haClients(pHAClients), nh() { // Set the service server object using the node handle's advertiseService method, // the service name, and the callback method from this object ss = nh.advertiseService("ha_demo", &HADemoService::callback, this); ROS_INFO_STREAM( "HomeBot-HADemoService(constructor): Initialized ha_demo service"); } HADemoService::~HADemoService() { } /** * @brief Service callback for the Home Automation Demo service - handles service calls * @param [in] req data specifying the request details (behavior, repetitions) * @param [out] rsp data going back to the service requestor (result) * @return boolean success or failure of the service call */ bool HADemoService::callback(homebot::HADemo::Request& req, homebot::HADemo::Response& rsp) { // Validate that the repetition count is between 1 and 10 (to prevent mistaken invocations) if (req.repetitions < 1 || req.repetitions > 10) { ROS_WARN_STREAM( "HomeBot-HADemoService(callback): Invalid number of repetitions '" << static_cast<int>(req.repetitions) << "' requested, no action initiated"); rsp.result = "Rejected: Invalid number of repetitions requested"; return false; } // Validate that the behavior requested is not null if (req.behavior == "") { ROS_WARN_STREAM( "Null behavior requested, no action taken"); rsp.result = "Rejected: Null behavior requested"; return false; } // Check whether the action is still available if (!haClients.acHBBehavior.isServerConnected()) { ROS_WARN_STREAM( "HomeBot-HADemoService(callback): bot_actor action server not ready when trying to activate behavior '" << req.behavior << "' with " << static_cast<int>(req.repetitions) << " repetitions"); rsp.result = "Failed: action server not ready"; return false; } ROS_INFO_STREAM( "HomeBot-HADemoService(callback): sending goal to bot_actor action server (behavior '" << req.behavior << "' with " << static_cast<int>(req.repetitions) << " repetitions)"); // Send goal to move_base action server, then wait for result homebot::HBBehaviorGoal goal; goal.behavior = req.behavior; goal.repetitions = req.repetitions; haClients.acHBBehavior.sendGoal(goal); haClients.acHBBehavior.waitForResult(); if (haClients.acHBBehavior.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO_STREAM("HomeBot-HADemoService(callback): Behavior goal reached"); rsp.result = "Joy: Behavior completed successfully"; return true; } else { ROS_WARN_STREAM( "HomeBot-HADemoService(callback): Failed to reach behavior goal"); rsp.result = "Sadness: Behavior did not complete successfully"; return false; } }
45.655462
197
0.735689
mark1-umd
7d0dafd27bd571aad05a2041e55204df0ba0530f
1,033
cpp
C++
lintcode/maxproductsubarray.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode/maxproductsubarray.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode/maxproductsubarray.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * @param nums: a vector of integers * @return: an integer */ int maxProduct(vector<int>& nums) { // write your code here int n=nums.size(); if(n==0){ return 0; } //maintain a mintemp incase negative * negative got a large positive int mintemp=nums[0]; int maxtemp=nums[0]; int res=nums[0]; //traversal every element to update minc and maxc for(int i=1; i<n; i++){ // not sure mintemp*nums[i] is small, it can be large baecause negative // not sure maxtemp*nums[i] is large, it can be small since negative int tempmin=min(mintemp*nums[i],maxtemp*nums[i]); int tempmax=max(mintemp*nums[i],maxtemp*nums[i]); mintemp=min(tempmin,nums[i]); maxtemp=max(tempmax,nums[i]); res=max(maxtemp,res); } return res; } };
27.918919
83
0.504356
WIZARD-CXY
7d14fd45738791225df985e91d6006f6f9a6b859
506
cpp
C++
LibSFML/SFText.cpp
Gotatang/FrameWorkIA
347b3b400a706427ecf7d5401e19ba4bd2bf18c3
[ "MIT" ]
null
null
null
LibSFML/SFText.cpp
Gotatang/FrameWorkIA
347b3b400a706427ecf7d5401e19ba4bd2bf18c3
[ "MIT" ]
null
null
null
LibSFML/SFText.cpp
Gotatang/FrameWorkIA
347b3b400a706427ecf7d5401e19ba4bd2bf18c3
[ "MIT" ]
null
null
null
/*Documentation */ /*@author : Quentin Ladevie */ /*@file : SFText.cpp */ /*@date : 29/12/2015 */ /*@brief : Fichier source des textes SFML */ #include "stdafx.h" #include "SFText.hpp" namespace DadEngine { SFText::SFText() { } SFText::~SFText() { } // Get/Set sf::Text& SFText::GetText() { return m_text; } void SFText::SetText(const sf::Text& _newText) { m_text = _newText; } // Get a copy Text* SFText::GetClone() { return new SFText (*this); } }
12.65
47
0.579051
Gotatang
7d18a518d116a68731c9290c5e73dbc3da4a6e63
4,271
cpp
C++
sqsgenerator/core/python/iteration.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
14
2019-11-16T10:34:04.000Z
2022-03-28T09:32:42.000Z
sqsgenerator/core/python/iteration.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
5
2019-11-21T05:54:07.000Z
2022-03-29T07:56:34.000Z
sqsgenerator/core/python/iteration.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
4
2020-09-28T14:28:23.000Z
2021-03-05T14:11:44.000Z
// // Created by dominik on 14.07.21. // #include "iteration.hpp" #include "helpers.hpp" namespace sqsgenerator::python { shuffling_bounds_t convert_bound_list(py::list &list) { shuffling_bounds_t bounds; if (list.is_none()) return bounds; for (int i = 0; i < len(list); i++) { auto bound = list[i]; bounds.push_back(std::forward_as_tuple(py::extract<size_t>(bound[0]), py::extract<size_t>(bound[1]))); } return bounds; } IterationSettingsPythonWrapper::IterationSettingsPythonWrapper( StructurePythonWrapper structure, py::dict composition, np::ndarray target_objective, np::ndarray parameter_weights, py::dict shell_weights, int iterations, int output_configurations, py::list threads_per_rank, double atol, double rtol, iteration_mode iteration_mode) : m_structure(structure), m_handle(new IterationSettings( *structure.handle(), helpers::convert_composition(composition), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(target_objective), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(parameter_weights), helpers::dict_to_map<shell_t, double>(shell_weights), iterations, output_configurations, helpers::list_to_vector<int>(threads_per_rank), atol, rtol, iteration_mode )) {} IterationSettingsPythonWrapper::IterationSettingsPythonWrapper( StructurePythonWrapper structure, py::dict composition, np::ndarray target_objective, np::ndarray parameter_weights, py::dict shell_weights, int iterations, int output_configurations, py::list distances, py::list threads_per_rank, double atol, double rtol, iteration_mode iteration_mode) : m_structure(structure), m_handle(new IterationSettings( *structure.handle(), helpers::convert_composition(composition), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(target_objective), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(parameter_weights), helpers::dict_to_map<shell_t, double>(shell_weights), iterations, output_configurations, helpers::list_to_vector<double>(distances), helpers::list_to_vector<int>(threads_per_rank), atol, rtol, iteration_mode )) {} double IterationSettingsPythonWrapper::atol() const { return m_handle->atol(); } double IterationSettingsPythonWrapper::rtol() const { return m_handle->rtol(); } size_t IterationSettingsPythonWrapper::num_atoms() const { return m_handle->num_atoms(); } size_t IterationSettingsPythonWrapper::num_shells() const { return m_handle->num_shells(); } int IterationSettingsPythonWrapper::num_iterations() const { return m_handle->num_iterations(); } size_t IterationSettingsPythonWrapper::num_species() const { return m_handle->num_species(); } iteration_mode IterationSettingsPythonWrapper::mode() const { return m_handle->mode(); } np::ndarray IterationSettingsPythonWrapper::target_objective() const { return helpers::multi_array_to_ndarray(m_handle->target_objective()); } StructurePythonWrapper IterationSettingsPythonWrapper::structure() const { return m_structure; } int IterationSettingsPythonWrapper::num_output_configurations() const { return m_handle->num_output_configurations(); } py::dict IterationSettingsPythonWrapper::shell_weights() const { return helpers::map_to_dict(m_handle->shell_weights()); } np::ndarray IterationSettingsPythonWrapper::parameter_weights() const { return helpers::multi_array_to_ndarray(m_handle->parameter_weights()); } std::shared_ptr<IterationSettings> IterationSettingsPythonWrapper::handle() const { return m_handle; } }
33.367188
114
0.648326
dgehringer
7d19f23c2faf5b3f9d71b6af1d29c7ceb6e27617
231
cxx
C++
Basic Programs/Some CP Problems/Watermelon4A.cxx
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/Some CP Problems/Watermelon4A.cxx
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
Basic Programs/Some CP Problems/Watermelon4A.cxx
PrajaktaSathe/HacktoberFest2020
e84fc7a513afe3dd75c7c28db1866d7f5e6a8147
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main(){ int w; cin >> w; if(w<=0) cout << "NO"; else if (w==2) cout << "NO"; else if(w%2==0) cout << "YES"; else cout << "NO"; return 0; }
16.5
31
0.575758
PrajaktaSathe
7d1b7ce2c254fa06311a95711a688e74733c4026
12,836
cpp
C++
code_reading/oceanbase-master/src/storage/memtable/mvcc/ob_mvcc_ctx.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/storage/memtable/mvcc/ob_mvcc_ctx.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/storage/memtable/mvcc/ob_mvcc_ctx.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #include "storage/memtable/mvcc/ob_mvcc_ctx.h" #include "storage/memtable/ob_memtable_key.h" #include "storage/memtable/ob_memtable_data.h" #include "storage/memtable/ob_memtable.h" namespace oceanbase { using namespace common; using namespace storage; namespace memtable { int ObIMvccCtx::after_link_trans_node(const void* key, ObMvccRow* value) { int ret = OB_SUCCESS; UNUSED(key); UNUSED(value); return ret; } void ObIMvccCtx::before_prepare() { #ifdef TRANS_ERROR const int random = (int)ObRandom::rand(1, 1000); usleep(random); #endif set_trans_version(0); } bool ObIMvccCtx::is_prepared() const { const int64_t prepare_version = ATOMIC_LOAD(&trans_version_); return (prepare_version >= 0 && INT64_MAX != prepare_version); } int ObIMvccCtx::register_row_lock_release_cb( const ObMemtableKey* key, ObMvccRow* value, bool is_replay, ObMemtable* memtable, const int32_t sql_no) { int ret = OB_SUCCESS; ObMvccRowCallback* cb = NULL; if (OB_ISNULL(key) || OB_ISNULL(value) || OB_ISNULL(memtable)) { ret = OB_INVALID_ARGUMENT; TRANS_LOG(WARN, "invalid argument", K(key), K(value), K(memtable)); } else if (OB_ISNULL(cb = alloc_row_callback(*this, *value, memtable, false))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc row callback failed", K(ret)); } else { cb->set(key, NULL, 0, NULL, is_replay, false, sql_no); if (!is_replay) { cb->set_write_locked(); } if (OB_FAIL(append_callback(cb))) { callback_free(cb); TRANS_LOG(WARN, "append callback failed", K(ret)); } } return ret; } int ObIMvccCtx::register_row_commit_cb(const ObMemtableKey* key, ObMvccRow* value, ObMvccTransNode* node, const int64_t data_size, const ObRowData* old_row, const bool is_stmt_committed, const bool need_fill_redo, ObMemtable* memtable, const int32_t sql_no, const bool is_sequential_relocate) { int ret = OB_SUCCESS; const bool is_replay = false; ObMvccRowCallback* cb = NULL; common::ObTimeGuard tg("ObIMvccCtx::register_row_commit_cb", 1000 * 1000); if (OB_ISNULL(key) || OB_ISNULL(value) || OB_ISNULL(node) || data_size <= 0 || OB_ISNULL(memtable)) { ret = OB_INVALID_ARGUMENT; TRANS_LOG(WARN, "invalid argument", K(key), K(value), K(node), K(data_size), K(memtable)); } else if (OB_ISNULL(cb = alloc_row_callback(*this, *value, memtable, false))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc row callback failed", K(ret)); } else { tg.click(); // count up memory size of current transaction node add_trans_mem_total_size(data_size); node->set_mvcc_row_cb(cb); cb->set(key, node, data_size, old_row, is_replay, need_fill_redo, sql_no); if (is_sequential_relocate) { { ObRowLatchGuard guard(value->latch_); tg.click(); cb->link_trans_node(); } // set stmt_committed flag of callback // set stmt_committed true only if data relocation cb->set_stmt_committed(is_stmt_committed); if (OB_FAIL(append_callback(cb))) { ObRowLatchGuard guard(value->latch_); cb->unlink_trans_node(); } } else { if (value->latch_.try_lock()) { tg.click(); cb->link_trans_node(); // set stmt_committed flag of callback // set stmt_committed true only if data relocation cb->set_stmt_committed(is_stmt_committed); if (OB_FAIL(append_callback(cb))) { cb->unlink_trans_node(); TRANS_LOG(WARN, "append callback failed", K(ret)); } } else { ret = OB_TRY_LOCK_ROW_CONFLICT; TRANS_LOG(DEBUG, "register_row_commit_cb try lock fail, need to retry", K(*key), K(*value), K(memtable), K(is_sequential_relocate)); } } tg.click(); if (OB_FAIL(ret)) { callback_free(cb); TRANS_LOG(WARN, "append callback failed", K(ret), K(is_sequential_relocate)); } } return ret; } int ObIMvccCtx::register_row_replay_cb(const ObMemtableKey* key, ObMvccRow* value, ObMvccTransNode* node, const int64_t data_size, ObMemtable* memtable, const int32_t sql_no, const bool is_sequential_relocate, const int64_t log_ts) { int ret = OB_SUCCESS; const bool is_replay = true; const bool need_fill_redo = false; const ObRowData* old_row = NULL; ObMvccRowCallback* cb = NULL; common::ObTimeGuard tg("ObIMvccCtx::register_row_replay_cb", 1000 * 1000); if (OB_ISNULL(key) || OB_ISNULL(value) || OB_ISNULL(node) || data_size <= 0 || OB_ISNULL(memtable)) { ret = OB_INVALID_ARGUMENT; TRANS_LOG(WARN, "invalid argument", K(key), K(value), K(node), K(data_size), K(memtable)); } else if (OB_ISNULL(cb = alloc_row_callback(*this, *value, memtable, false))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc row callback failed", K(ret)); } else { tg.click(); node->set_mvcc_row_cb(cb); cb->set(key, node, data_size, old_row, is_replay, need_fill_redo, sql_no); if (is_sequential_relocate) { { ObRowLatchGuard guard(value->latch_); tg.click(); cb->link_trans_node(); } // all statement is finished when replaying log cb->set_stmt_committed(true); cb->set_log_ts(log_ts); if (OB_FAIL(append_callback(cb))) { { ObRowLatchGuard guard(value->latch_); cb->unlink_trans_node(); } TRANS_LOG(WARN, "append callback failed", K(ret)); } else { update_max_durable_sql_no(sql_no); // TODO: defense inspection int64_t redo_log_ts = (0 == lob_start_log_ts_ ? log_ts : lob_start_log_ts_); if (redo_log_ts > memtable->get_freeze_log_ts()) { ret = OB_ERR_UNEXPECTED; TRANS_LOG(ERROR, "replay should not overflow", K(ret), K(redo_log_ts), K(*memtable)); } } } else { // try lock destination memstore row when relocating data from active memstore to frozen memstore if (value->latch_.try_lock()) { tg.click(); cb->link_trans_node(); // all statement is finished when replaying log cb->set_stmt_committed(true); cb->set_log_ts(log_ts); if (OB_FAIL(append_callback(cb))) { cb->unlink_trans_node(); } value->latch_.unlock(); } else { ret = OB_TRY_LOCK_ROW_CONFLICT; TRANS_LOG(DEBUG, "register_row_replay_cb try lock fail, need to retry", K(*key), K(*value), K(memtable), K(is_sequential_relocate)); } } if (OB_FAIL(ret)) { callback_free(cb); TRANS_LOG(WARN, "append callback failed", K(ret), K(is_sequential_relocate)); } tg.click(); } return ret; } int ObIMvccCtx::register_savepoint_cb(const ObMemtableKey* key, ObMvccRow* value, ObMvccTransNode* node, const int64_t data_size, const ObRowData* old_row, const int32_t sql_no) { int ret = OB_SUCCESS; const bool is_replay = false; const bool need_fill_redo = true; const bool is_stmt_committed = false; ObMvccRowCallback* cb = NULL; if (OB_ISNULL(key) || OB_ISNULL(value) || OB_ISNULL(node) || data_size < 0) { ret = OB_INVALID_ARGUMENT; TRANS_LOG(WARN, "invalid argument", K(key), K(value), K(node), K(data_size)); } else if (OB_ISNULL(cb = alloc_row_callback(*this, *value, NULL, true))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc row callback failed", K(ret)); } else { // count up memory size of transaction node add_trans_mem_total_size(data_size); cb->set(key, node, data_size, old_row, is_replay, need_fill_redo, sql_no); cb->set_stmt_committed(is_stmt_committed); cb->set_savepoint(); cb->set_is_link(); if (OB_FAIL(append_callback(cb))) { TRANS_LOG(WARN, "append savepoint callback failed", K(ret), K(*cb)); } else { TRANS_LOG(INFO, "append savepoint callback", K(*cb)); } } return ret; } int ObIMvccCtx::register_savepoint_cb(ObMvccRowCallback& cb, ObMemtable* memtable) { int ret = OB_SUCCESS; ObMvccRowCallback* new_cb = NULL; if (OB_ISNULL(new_cb = alloc_row_callback(cb, memtable, true))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc row callback failed", K(ret)); } else { if (OB_FAIL(append_callback(new_cb))) { TRANS_LOG(WARN, "append savepoint callback failed", K(ret), K(*new_cb)); } else { TRANS_LOG(INFO, "append savepoint callback", K(*new_cb)); } } return ret; } ObMvccRowCallback* ObIMvccCtx::alloc_row_callback( ObIMvccCtx& ctx, ObMvccRow& value, ObMemtable* memtable, const bool is_savepoint) { int ret = OB_SUCCESS; void* cb_buffer = NULL; ObMvccRowCallback* cb = NULL; if (!is_savepoint) { if (NULL == (cb_buffer = callback_alloc(sizeof(*cb)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc ObRowCB cb_buffer fail", K(ret)); } } else { if (NULL == (cb_buffer = arena_alloc(sizeof(*cb)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc ObRowCB cb_buffer fail", K(ret)); } } if (NULL != cb_buffer) { if (NULL == (cb = new (cb_buffer) ObMvccRowCallback(ctx, value, memtable))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "construct ObRowCB object fail", K(ret), "cb_buffer", cb_buffer); } } return cb; } ObMvccRowCallback* ObIMvccCtx::alloc_row_callback(ObMvccRowCallback& cb, ObMemtable* memtable, const bool is_savepoint) { int ret = OB_SUCCESS; void* cb_buffer = NULL; ObMvccRowCallback* new_cb = NULL; if (!is_savepoint) { if (NULL == (cb_buffer = callback_alloc(sizeof(*new_cb)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc ObRowCB cb_buffer fail", K(ret)); } } else { if (NULL == (cb_buffer = arena_alloc(sizeof(*new_cb)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc ObRowCB cb_buffer fail", K(ret)); } } if (NULL != cb_buffer) { if (NULL == (new_cb = new (cb_buffer) ObMvccRowCallback(cb, memtable))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "construct ObRowCB object fail", K(ret), "cb_buffer", cb_buffer); } } return new_cb; } ObMemtableKey* ObIMvccCtx::alloc_memtable_key() { int ret = OB_SUCCESS; void* buffer = NULL; ObMemtableKey* mt_key = NULL; if (NULL == (buffer = arena_alloc(sizeof(*mt_key)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc memtable key fail", K(ret)); } else if (NULL == (mt_key = new (buffer) ObMemtableKey())) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "construct memtable key fail", K(ret), KP(buffer)); } else { // do nothing } return mt_key; } ObMvccRow* ObIMvccCtx::alloc_mvcc_row() { int ret = OB_SUCCESS; void* buffer = NULL; ObMvccRow* row = NULL; if (NULL == (buffer = arena_alloc(sizeof(*row)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc mvcc row fail", K(ret)); } else if (NULL == (row = new (buffer) ObMvccRow())) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "construct mvcc row fail", K(ret), KP(buffer)); } else { // do nothing } return row; } ObMvccTransNode* ObIMvccCtx::alloc_trans_node() { int ret = OB_SUCCESS; char* buffer = NULL; ObMvccTransNode* node = NULL; ObMemtableData* data = NULL; if (NULL == (buffer = (char*)arena_alloc(sizeof(*node) + sizeof(*data)))) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "alloc trans node fail", K(ret)); } else if (NULL == (node = new (buffer) ObMvccTransNode())) { ret = OB_ALLOCATE_MEMORY_FAILED; TRANS_LOG(WARN, "construct trans node fail", K(ret), KP(buffer)); } else { data = reinterpret_cast<ObMemtableData*>(node->buf_); new (data) ObMemtableData(T_DML_UNKNOWN, 0, NULL); } return node; } int ObIMvccCtx::append_callback(ObITransCallback* cb) { return trans_mgr_.append(cb); } int64_t ObIMvccCtx::get_query_abs_lock_wait_timeout(const int64_t lock_wait_start_ts) const { int64_t abs_timeout = 0; if (trx_lock_timeout_ < 0) { abs_timeout = abs_lock_wait_timeout_; } else { abs_timeout = MIN(abs_lock_wait_timeout_, trx_lock_timeout_ + lock_wait_start_ts); } return abs_timeout; } } // namespace memtable } // namespace oceanbase
33.868074
119
0.666874
wangcy6
7d1de2aa82658c1e9d7885b09bef962c94c361a3
13,908
cpp
C++
src/loss_functions.cpp
vishalbelsare/slise
a1917bcbea3e642c59977e7d3634c2a5b4d7cf39
[ "MIT" ]
5
2019-09-14T14:37:16.000Z
2022-01-28T16:55:40.000Z
src/loss_functions.cpp
vishalbelsare/slise
a1917bcbea3e642c59977e7d3634c2a5b4d7cf39
[ "MIT" ]
1
2022-01-31T11:31:12.000Z
2022-01-31T11:31:12.000Z
src/loss_functions.cpp
vishalbelsare/slise
a1917bcbea3e642c59977e7d3634c2a5b4d7cf39
[ "MIT" ]
1
2021-08-20T13:47:07.000Z
2021-08-20T13:47:07.000Z
/* Loss and gradient functions in Rcpp / RcppArmadillo. Usage in R: library(Rcpp) sourceCpp("loss_functions.cpp") Classes: (1) DataContainer - Contains the following fields: * data (matrix) * response (vector) * beta, epsilon, lambda (doubles) - Each field has a getter / setter: getData(), setData() etc. - To use this in R: dc <- new(DataContainer, data = matrix(runif(50), nrow = 10), response = runif(10), beta = 1, epsilon = 0.4, lambda = 0.3) dc$getBeta() ## returns 1 dc$setBeta(5) ## set the value of beta to 5 dc$getBeta() ## returns 5 Functions: (1) loss_smooth_c(vec alpha, mat data, vec response, double beta, double epsilon, double lambda) - This function returns the value of the loss function (double). - Call from R by giving the appropriate parameters. (2) loss_smooth_grad_c(vec alpha, mat data, vec response, double beta, double epsilon, double lambda) - This function returns the gradient of the loss function (vector). - Call from R by giving the appropriate parameters. (3) loss_smooth_c_dc(vec alpha, DataContainer dc) - This function returns the value of the loss function (double). - This is a wrapper for loss_smooth_c. - To use this function, first create a DataContainer in R: dc <- new(DataContainer, data = matrix(runif(50), nrow = 10), response = runif(10), beta = 1, epsilon = 0.4, lambda = 0.3) loss_smooth_c_dc(xs = runif(5), dcptr = dc$.pointer) (4) loss_smooth_grad_c_dc(vec alpha, DataContainer dc) - This function returns the gradient of the loss function (vector). - This is a wrapper for loss_smooth_grad_c. - To use this function, first create a DataContainer in R: dc <- new(DataContainer, data = matrix(runif(50), nrow = 10), response = runif(10), beta = 1, epsilon = 0.4, lambda = 0.3) loss_smooth_c_dc(xs = runif(5), dcptr = dc$.pointer) (5) lg_combined_smooth_c_dc(vec alpha, DataContainer dc) - This function calculates both the loss and the gradient at the same time - The loss (double) is returned and both the loss (double) and gradient (vector) are stored in the DataContainer. - To use this function, first create a DataContainer in R: dc <- new(DataContainer, data = matrix(runif(50), nrow = 10), response = runif(10), beta = 1, epsilon = 0.4, lambda = 0.3) lg_combined_smooth_c_dc(xs = runif(5), dcptr = dc$.pointer) ## returns the loss dc$getLoss() # get the loss value dc$getGrad() # get the gradient (6) lg_getgrad_c_dc(vec alpha, DataContainer dc) - This function only returns the gradient found in dc (similar to dc$getGrad()) - This is to be used with LBFGS. Usage with LBFGS: dc <- new(DataContainer, data = matrix(runif(50), nrow = 10), response = runif(10), beta = 1, epsilon = 0.4, lambda = 0.3) alpha <- runif(5) lbfgs(loss_smooth_c_ptr(), loss_smooth_grad_c_ptr(), alpha, dc$.pointer, max_iterations = 100, invisible = TRUE, orthantwise_c = dc$getLambda()), */ // [[Rcpp::plugins(cpp14)]] // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> /* -------------------------------------------------- Class for holding the data -------------------------------------------------- */ class DataContainer; //_' @export DataContainer class DataContainer { public: arma::mat data; arma::vec response; double beta, epsilon, lambda; double loss; arma::vec grad; DataContainer(Rcpp::NumericMatrix data_, Rcpp::NumericVector response_, double beta_, double epsilon_, double lambda_) : data ( Rcpp::as<arma::mat>(data_) ), response ( Rcpp::as<arma::colvec>(response_) ), beta( beta_ ), epsilon( epsilon_ ), lambda( lambda_ ) {}; DataContainer(Rcpp::NumericMatrix data_, Rcpp::NumericVector response_, double beta_, double epsilon_) : DataContainer(data_, response_, beta_, epsilon_, 0) {}; DataContainer(const DataContainer & i) : data( i.data ), response( i.response), beta( i.beta), epsilon( i.epsilon ), lambda( i.lambda) {} Rcpp::NumericMatrix getData() { return Rcpp::wrap(data); } Rcpp::NumericVector getResponse() { return Rcpp::wrap(response); } double getBeta() { return beta; } double getEpsilon() { return epsilon; } double getLambda () { return lambda; } double getLoss() { return loss; } Rcpp::NumericVector getGrad() { return Rcpp::wrap(grad); } void setData(Rcpp::NumericMatrix M) { data = Rcpp::as<arma::mat>(M); } void setResponse(Rcpp::NumericVector v) { response = Rcpp::as<arma::colvec>(v); } void setBeta(double x) { beta = x; } void setEpsilon(double x) { epsilon = x; } void setLambda(double x) { lambda = x; } void setGrad(Rcpp::NumericVector v) { grad = Rcpp::as<arma::colvec>(v); } }; RCPP_EXPOSED_CLASS(DataContainer) RCPP_MODULE(slise_mod) { Rcpp::class_<DataContainer>("DataContainer") .constructor< Rcpp::NumericMatrix, Rcpp::NumericVector, double, double, double >() .constructor< Rcpp::NumericMatrix, Rcpp::NumericVector, double, double >() .constructor< DataContainer >() .method("getData", &DataContainer::getData) .method("getResponse", &DataContainer::getResponse) .method("getBeta", &DataContainer::getBeta) .method("getEpsilon", &DataContainer::getEpsilon) .method("getLambda", &DataContainer::getLambda) .method("getLoss", &DataContainer::getLoss) .method("getGrad", &DataContainer::getGrad) .method("setData", &DataContainer::setData) .method("setResponse", &DataContainer::setResponse) .method("setBeta", &DataContainer::setBeta) .method("setEpsilon", &DataContainer::setEpsilon) .method("setLambda", &DataContainer::setLambda) .method("setGrad", &DataContainer::setGrad) ; } /* -------------------------------------------------- Sigmoid function written in c++. -------------------------------------------------- */ // [[Rcpp::export]] arma::vec sigmoidc(const arma::vec& x) { return (1 / (1 + arma::exp(-x))); // return (arma::exp(x) / (arma::exp(x) + 1)); } inline arma::vec i_sigmoidc(const arma::vec& x) { return (1 / (1 + arma::exp(-x))); } /* -------------------------------------------------- Dot product. -------------------------------------------------- */ double dotprod(const arma::vec& a, const arma::vec& b) { double res = 0; for (int i = 0; i < a.size(); i++) res += a[i] * b[i]; return res; } /* -------------------------------------------------- Clamp max. -------------------------------------------------- */ inline arma::vec clamp_max(const arma::vec& a, double b) { arma::vec res(a.size()); for(int i = 0; i < a.size(); i++) res[i] = a[i] < b ? a[i] : b; return res; } /* -------------------------------------------------- Clamp min. -------------------------------------------------- */ inline arma::vec clamp_min(const arma::vec& a, double b) { arma::vec res(a.size()); for(int i = 0; i < a.size(); i++) res[i] = a[i] > b ? a[i] : b; return res; } /* -------------------------------------------------- Clamp min according to another vector. -------------------------------------------------- */ inline arma::vec clamp_max_other(const arma::vec& a, const arma::vec& b, double c) { arma::vec res(a.size()); for(int i = 0; i < a.size(); i++) res[i] = b[i] < c ? a[i] : c; return res; } /* -------------------------------------------------- Smooth loss function. alpha : alpha vector data : data matrix response : response vector beta : beta (double) epsilon : epsilon (double) lambda : lambda (double) -------------------------------------------------- */ // [[Rcpp::export]] double loss_smooth_c(const arma::vec& alpha, const arma::mat& data, const arma::vec& response, const double& beta, const double& epsilon, const double& lambda = 0) { // calculate loss double epsilonx = pow(epsilon, 2); double epsilony = epsilonx * response.size(); double betax = beta / epsilonx; arma::vec distances = arma::pow(data * alpha - response, 2); arma::vec subsize = i_sigmoidc(betax * (epsilonx - distances)); arma::vec loss = clamp_max(distances - epsilony, 0); //phi(x) ~ clamp_max(x, 0) double out = arma::accu(subsize % loss) / distances.size(); if (lambda > 0) out += (lambda * arma::accu(arma::abs(alpha))); return out; } /* -------------------------------------------------- Smooth loss function using a DataContainer. The DataContainer contains the parameters (data, response, beta, epsilon, lambda) which are then used to call loss_smooth_c(). xs : alpha vector dcptr : pointer to a DataContainer (from R) -------------------------------------------------- */ // [[Rcpp::export]] Rcpp::NumericVector loss_smooth_c_dc(const SEXP xs, const SEXP dcptr) { const Rcpp::XPtr<DataContainer> dc(dcptr); Rcpp::NumericVector out(1); out[0] = loss_smooth_c(Rcpp::as<arma::vec>(xs), dc->data, dc->response, dc->beta, dc->epsilon, dc->lambda); return out; } /* -------------------------------------------------- Gradient of the smooth loss function. alpha : alpha vector data : data matrix response : response vector beta : beta (double) epsilon : epsilon (double) lambda : lambda (double) -------------------------------------------------- */ // [[Rcpp::export]] Rcpp::NumericVector loss_smooth_grad_c(const arma::vec& alpha, const arma::mat& data, const arma::vec& response, const double& beta, const double& epsilon, const double& lambda = 0) { double epsilonx = pow(epsilon, 2); double betax = beta / epsilonx; arma::vec distances = data * alpha - response; arma::colvec distances2 = arma::pow(distances, 2); arma::colvec f = distances2 / data.n_rows - epsilonx; arma::colvec s = i_sigmoidc(betax * (epsilonx - distances2)); double k1 = 2.0 / data.n_rows; arma::colvec k2 = -2.0 * betax * (s - pow(s, 2)); distances = clamp_max_other(distances, f, 0); //phi(x) ~ clamp_max(x, 0) arma::vec out = (data.each_col() % distances).t() * ((s * k1) + (f % k2)); if (lambda > 0) out += (lambda * arma::sign(alpha)); return Rcpp::wrap(out); } /* -------------------------------------------------- Gradient of smooth loss function using a DataContainer. The DataContainer contains the parameters data, response, beta, epsilon, lambda) which are then used to call loss_smooth_c(). xs : alpha vector dcptr : pointer to a DataContainer (from R) -------------------------------------------------- */ // [[Rcpp::export]] Rcpp::NumericVector loss_smooth_grad_c_dc(const SEXP xs, const SEXP dcptr) { const Rcpp::XPtr<DataContainer> dc(dcptr); return loss_smooth_grad_c(Rcpp::as<arma::vec>(xs), dc->data, dc->response, dc->beta, dc->epsilon, dc->lambda); } /* -------------------------------------------------- Calculate loss and gradient simultaneously, using a data container. xs : alpha vector dcptr : pointer to a DataContainer (from R) -------------------------------------------------- */ // [[Rcpp::export]] Rcpp::NumericVector lg_combined_smooth_c_dc(SEXP xs, SEXP dcptr) { const arma::vec alpha = Rcpp::as<arma::vec>(xs); const Rcpp::XPtr<DataContainer> dc(dcptr); // calculate loss double epsilonx = pow(dc->epsilon, 2); double betax = dc->beta / epsilonx; arma::colvec distances = dc->data * alpha - dc->response; arma::colvec distances2 = arma::pow(distances, 2); arma::colvec subsize = i_sigmoidc(betax * (epsilonx - distances2)); arma::colvec loss = distances2 / dc->data.n_rows - epsilonx; dc->loss = arma::accu(subsize % clamp_max(loss, 0)); //phi(x) ~ clamp_max(x, 0) // calculate gradient double k1 = 2.0 / dc->data.n_rows; arma::colvec k2 = -2.0 * betax * (subsize - pow(subsize, 2)); distances = clamp_max_other(distances, loss, 0); //phi(x) ~ clamp_max(x, 0) dc->grad = (dc->data.each_col() % distances).t() * ((subsize * k1) + (loss % k2)); // check lambda if (dc->lambda > 0) { dc->loss += (dc->lambda * arma::accu(arma::abs(alpha))); dc->grad += (dc->lambda * arma::sign(alpha)); } Rcpp::NumericVector out(1); out[0] = dc->loss; return out; } /* -------------------------------------------------- Return gradient. This assumes that the gradient has first been calculated and stored in the DataContainer. xs : alpha vector dcptr : pointer to a DataContainer (from R) -------------------------------------------------- */ // [[Rcpp::export]] Rcpp::NumericVector lg_getgrad_c_dc(SEXP xs, SEXP dcptr) { const Rcpp::XPtr<DataContainer> dc(dcptr); return Rcpp::wrap(dc->grad); } /* -------------------------------------------------- Return function pointers to the loss and gradient functions for use with lbfgs. -------------------------------------------------- */ typedef Rcpp::NumericVector (*funcPtr)(const SEXP, const SEXP); // [[Rcpp::export]] Rcpp::XPtr<funcPtr> loss_smooth_c_ptr() { // return(XPtr<funcPtr>(new funcPtr(&loss_smooth_c_dc))); return(Rcpp::XPtr<funcPtr>(new funcPtr(&lg_combined_smooth_c_dc))); } // [[Rcpp::export]] Rcpp::XPtr<funcPtr> loss_smooth_grad_c_ptr() { // return(XPtr<funcPtr>(new funcPtr(&loss_smooth_grad_c_dc))); return(Rcpp::XPtr<funcPtr>(new funcPtr(&lg_getgrad_c_dc))); }
34.944724
267
0.56845
vishalbelsare
7d1df48aacc2edd0b2dace2583a02e4ad527144d
10,603
cpp
C++
Cpp/SDK/BP_WeatherSystem_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
1
2020-08-15T08:31:55.000Z
2020-08-15T08:31:55.000Z
Cpp/SDK/BP_WeatherSystem_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-15T08:43:56.000Z
2021-01-15T05:04:48.000Z
Cpp/SDK/BP_WeatherSystem_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-10T12:05:42.000Z
2021-02-12T19:56:10.000Z
// Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_WeatherSystem.BP_WeatherSystem_C.SetupGlobalWind // (Public, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetupGlobalWind() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetupGlobalWind"); ABP_WeatherSystem_C_SetupGlobalWind_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SetupWindMaterial // (Public, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetupWindMaterial() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetupWindMaterial"); ABP_WeatherSystem_C_SetupWindMaterial_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.drawRoom // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // float CeilingHeight (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // float RoomWidth (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // float RoomLenght (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // TEnumAsByte<EPhysicalSurface> FloorType (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_WeatherSystem_C::drawRoom(float* CeilingHeight, float* RoomWidth, float* RoomLenght, TEnumAsByte<EPhysicalSurface>* FloorType) { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.drawRoom"); ABP_WeatherSystem_C_drawRoom_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (CeilingHeight != nullptr) *CeilingHeight = params.CeilingHeight; if (RoomWidth != nullptr) *RoomWidth = params.RoomWidth; if (RoomLenght != nullptr) *RoomLenght = params.RoomLenght; if (FloorType != nullptr) *FloorType = params.FloorType; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnParticleSystem // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SpawnParticleSystem() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnParticleSystem"); ABP_WeatherSystem_C_SpawnParticleSystem_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.WeatherSystemDirection // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::WeatherSystemDirection() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.WeatherSystemDirection"); ABP_WeatherSystem_C_WeatherSystemDirection_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnDistantParticleSystem // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SpawnDistantParticleSystem() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnDistantParticleSystem"); ABP_WeatherSystem_C_SpawnDistantParticleSystem_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SetRadius // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetRadius() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetRadius"); ABP_WeatherSystem_C_SetRadius_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.UserConstructionScript"); ABP_WeatherSystem_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoomType // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::CheckRoomType() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoomType"); ABP_WeatherSystem_C_CheckRoomType_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoofMaterial // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::CheckRoofMaterial() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoofMaterial"); ABP_WeatherSystem_C_CheckRoofMaterial_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ResetSpawningParticles // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::ResetSpawningParticles() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ResetSpawningParticles"); ABP_WeatherSystem_C_ResetSpawningParticles_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.LeaveNegativeArea // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::LeaveNegativeArea() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.LeaveNegativeArea"); ABP_WeatherSystem_C_LeaveNegativeArea_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.EnterNegativeArea // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::EnterNegativeArea() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.EnterNegativeArea"); ABP_WeatherSystem_C_EnterNegativeArea_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ApplyWeatherToMap // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::ApplyWeatherToMap() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ApplyWeatherToMap"); ABP_WeatherSystem_C_ApplyWeatherToMap_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SetEffectLocation // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetEffectLocation() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetEffectLocation"); ABP_WeatherSystem_C_SetEffectLocation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.CheckPlayerProximity // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::CheckPlayerProximity() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.CheckPlayerProximity"); ABP_WeatherSystem_C_CheckPlayerProximity_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.UpdateWeatherDirection // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::UpdateWeatherDirection() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.UpdateWeatherDirection"); ABP_WeatherSystem_C_UpdateWeatherDirection_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveBeginPlay // (Event, Protected, BlueprintEvent) void ABP_WeatherSystem_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveBeginPlay"); ABP_WeatherSystem_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveTick // (Event, Public, BlueprintEvent) // Parameters: // float DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_WeatherSystem_C::ReceiveTick(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveTick"); ABP_WeatherSystem_C_ReceiveTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ExecuteUbergraph_BP_WeatherSystem // (Final, HasDefaults) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_WeatherSystem_C::ExecuteUbergraph_BP_WeatherSystem(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ExecuteUbergraph_BP_WeatherSystem"); ABP_WeatherSystem_C_ExecuteUbergraph_BP_WeatherSystem_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.129121
176
0.776761
MrManiak
7d1f4e81493991f0d241d267b3cd1944e8a0ff85
1,799
cpp
C++
devices/GNSS/NMEA/testsuite/src/RMCProcessorTest.cpp
acnagy/test-macchina.io
2b8d79d87d6cbd967ccbc9167ea583cbe78ad1b9
[ "Apache-2.0" ]
null
null
null
devices/GNSS/NMEA/testsuite/src/RMCProcessorTest.cpp
acnagy/test-macchina.io
2b8d79d87d6cbd967ccbc9167ea583cbe78ad1b9
[ "Apache-2.0" ]
null
null
null
devices/GNSS/NMEA/testsuite/src/RMCProcessorTest.cpp
acnagy/test-macchina.io
2b8d79d87d6cbd967ccbc9167ea583cbe78ad1b9
[ "Apache-2.0" ]
null
null
null
// // RMCProcessorTest.cpp // // $Id$ // // Copyright (c) 2010-2015, Applied Informatics Software Engineering GmbH. // All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // #include "RMCProcessorTest.h" #include "IoT/GNSS/NMEA/SentenceDecoder.h" #include "Poco/DateTime.h" #include "Poco/Delegate.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" using namespace Poco::Geo; using namespace IoT::GNSS::NMEA; RMCProcessorTest::RMCProcessorTest(const std::string& name): CppUnit::TestCase(name) { } RMCProcessorTest::~RMCProcessorTest() { } void RMCProcessorTest::testRMCProcessor() { const std::string sentences = "$GPGGA,163026.489,,,,,0,00,,,M,0.0,M,,0000*53\r\n" "$GPGSA,A,3,15,24,09,17,05,,,,,,,,4.3,2.6,3.4*3E\r\n" "$GPRMC,163030.186,A,4729.6845,N,00941.3582,E,1.30,213.65,100313,,,A*60\r\n"; RMCProcessor rmcp; SentenceDecoder sc; sc.sentenceReceived += Poco::delegate(&rmcp, &RMCProcessor::processSentence); rmcp.rmcReceived += Poco::delegate(this, &RMCProcessorTest::onRMCReceived); sc.processBuffer(sentences.data(), sentences.size()); Poco::DateTime dt(2013, 03, 10, 16, 30, 30, 186); assert (_rmc.timestamp == dt.timestamp()); assertEquals (47.4947, _rmc.position.latitude().degrees(), 0.0001); assertEquals (9.6893, _rmc.position.longitude().degrees(), 0.0001); assertEquals (213.65, _rmc.heading.degrees(), 0.001); assertEquals (1.3, _rmc.speed, 0.01); } void RMCProcessorTest::setUp() { } void RMCProcessorTest::tearDown() { } void RMCProcessorTest::onRMCReceived(const RMCProcessor::RMC& rmc) { _rmc = rmc; } CppUnit::Test* RMCProcessorTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("RMCProcessorTest"); CppUnit_addTest(pSuite, RMCProcessorTest, testRMCProcessor); return pSuite; }
21.416667
84
0.710951
acnagy
7d24153e72beb069099d37518c6f00579d1007e1
5,736
cpp
C++
Source/Pineapple/Engine/Platform/FileSystem.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
11
2017-04-15T14:44:19.000Z
2022-02-04T13:16:04.000Z
Source/Pineapple/Engine/Platform/FileSystem.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
25
2017-04-19T12:48:42.000Z
2020-05-09T05:28:29.000Z
Source/Pineapple/Engine/Platform/FileSystem.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
1
2019-04-21T21:14:04.000Z
2019-04-21T21:14:04.000Z
#include <Pineapple/Engine/Platform/FileSystem.h> #include <Pineapple/Engine/Platform/Memory.h> #include <Pineapple/Engine/Util/Macro.h> #include <cstdio> #include <sys/stat.h> namespace { pa::FileResult openFile(FILE** file, const char* path, const char* mode) { #ifdef _MSC_VER fopen_s(file, path, mode); #else *file = fopen(path, mode); #endif if (!*file) { switch (errno) { case ENOENT: // No such file or directory return pa::FileResult::NotFound; break; case EIO: // I/O Error return pa::FileResult::ReadError; break; case EACCES: // Permissions return pa::FileResult::AccessDenied; break; case ENAMETOOLONG: // File name is too long return pa::FileResult::NameTooLong; break; default: // Cannot find error return pa::FileResult::NotFound; break; } } return pa::FileResult::Success; } } void pa::FileBuffer::allocate(std::size_t size) { PA_ASSERTF(m_size == 0, "Buffer has already been allocated"); m_buffer = std::make_unique<unsigned char[]>(size); m_size = size; } std::unique_ptr<unsigned char[]>& pa::FileBuffer::getBuffer() { return m_buffer; } const std::unique_ptr<unsigned char[]>& pa::FileBuffer::getBuffer() const { return m_buffer; } std::size_t pa::FileBuffer::getSize() const { return m_size; } std::string pa::FileBuffer::createString() const { std::string string((char*)m_buffer.get(), m_size); return string; } void pa::FileBuffer::copyFromString(std::string string) { clear(); allocate(string.size()); memcpy(getBuffer().get(), string.c_str(), getSize()); } void pa::FileBuffer::clear() { m_buffer = nullptr; m_size = 0; } namespace { std::string combinePaths(const std::string& path1, const std::string& path2) { // <todo> make work with all path types std::string result = path1; if (!result.empty() && result[result.size() - 1] != '/') { result += '/'; } result += path2; return result; } std::string makeFilePath(const pa::FileSystem& fileSystem, pa::FileStorage storage, const std::string& path) { // <todo> add directory separators when building paths switch (storage) { case pa::FileStorage::EngineAsset: return combinePaths(fileSystem.getSettings().engineAssetPath, path); case pa::FileStorage::UserAsset: return combinePaths(fileSystem.getSettings().userAssetPath, path); case pa::FileStorage::Internal: return combinePaths(fileSystem.getSettings().internalPath, path); default: PA_ASSERTF(false, "Unknown FileStorage value"); return ""; } } } pa::FilePath::FilePath(const pa::FileSystem& fileSystem, pa::FileStorage storage, const std::string& path) : m_fileSystem(fileSystem) , m_path(makeFilePath(fileSystem, storage, path)) , m_storage(storage) { } const std::string& pa::FilePath::asString() const { return m_path; } pa::FileResult pa::FilePath::read(FileBuffer& buffer) const { return m_fileSystem.read(*this, buffer); } pa::FileResult pa::FilePath::write(const FileBuffer& buffer) const { return m_fileSystem.write(*this, buffer); } pa::FileResult pa::FilePath::getModificationTime(std::chrono::system_clock::time_point& modificationTime) const { return m_fileSystem.getModificationTime(*this, modificationTime); } pa::FileStorage pa::FilePath::getStorage() const { return m_storage; } pa::FileSystem::FileSystem(pa::PlatformSettings::FileSystem settings) : m_settings(settings) { } /*static*/ const char* pa::FileSystem::getResultString(pa::FileResult result) { switch (result) { case pa::FileResult::Success: return "Success"; case pa::FileResult::NotFound: return "File not found"; case pa::FileResult::ReadError: return "File read error"; case pa::FileResult::IOError: return "File I/O error"; case pa::FileResult::AccessDenied: return "Access denied"; case pa::FileResult::NameTooLong: return "File name too long"; case pa::FileResult::WriteError: return "File write error"; default: PA_ASSERTF(false, "Result string not implemented"); return ""; } } const pa::PlatformSettings::FileSystem& pa::FileSystem::getSettings() const { return m_settings; } pa::FileResult pa::FileSystem::read(const pa::FilePath& path, pa::FileBuffer& buffer) const { FILE* file; { auto result = openFile(&file, path.asString().c_str(), "rb"); if (result != pa::FileResult::Success) { // Cannot open the file so return error code return result; } } // Obtain the file size fseek(file, 0, SEEK_END); auto length = ftell(file); rewind(file); buffer.allocate(length); // Copy the file into the buffer pa::FileResult result = pa::FileResult::Success; auto readLength = fread(buffer.getBuffer().get(), sizeof(unsigned char), length, file); if (readLength != length) { result = pa::FileResult::ReadError; } fclose(file); return result; } pa::FileResult pa::FileSystem::write(const pa::FilePath& path, const pa::FileBuffer& buffer) const { FILE* file; { pa::FileResult result = openFile(&file, path.asString().c_str(), "wb"); if (result != pa::FileResult::Success) { // Cannot open the file so return error code return result; } } auto result = pa::FileResult::Success; auto count = fwrite(buffer.getBuffer().get(), sizeof(unsigned char), buffer.getSize(), file); if (count != buffer.getSize()) { result = pa::FileResult::WriteError; } fclose(file); return result; } pa::FileResult pa::FileSystem::getModificationTime(const pa::FilePath& path, std::chrono::system_clock::time_point& modificationTime) const { struct stat st; int ret = stat(path.asString().c_str(), &st); if (ret == -1) { return pa::FileResult::ReadError; } else { modificationTime = std::chrono::system_clock::from_time_t(st.st_mtime); return pa::FileResult::Success; } }
23.508197
139
0.699965
JoshYaxley
7d26bf1357b6c0628786f1e9d3f6754960393458
959
cpp
C++
c++/Functor/Argument.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Functor/Argument.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Functor/Argument.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #define TRUE 1 #define FALSE 0 template<typename Container, typename Functor> void for_each(Container container_, Functor functor_) { for (typename Container::iterator ite = container_.begin(); ite != container_.end(); ++ite) { functor_(*ite); } } class Out { public: static const int isNULL = FALSE; template<typename Type> void operator()(const Type& data_) { std::cout << "Out::" << data_ << std::endl; } }; class NULLType { public: static const int isNULL = TRUE; }; template<typename Type1, typename Type2 = NULLType, typename Type3 = NULLType> class Printer { public: void print(std::vector<int> container_) { for_each(container_, Type1()); } }; int main() { std::vector<int> container; for (int i = 0; i < 5; ++i) { container.push_back(i); } Printer<Out, Out, Out> printer; printer.print(container); return 0; }
15.983333
95
0.632951
taku-xhift
7d2757e58b1c08c4fb66aafd0eef56b1bafaa302
1,139
cc
C++
runtime/onert/core/src/util/GeneralConfigSource.cc
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
runtime/onert/core/src/util/GeneralConfigSource.cc
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
runtime/onert/core/src/util/GeneralConfigSource.cc
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 "util/GeneralConfigSource.h" #include "util/logging.h" namespace onert { namespace util { std::string GeneralConfigSource::get(const std::string &key) const { auto itr = _map.find(key); if (itr == _map.end()) { return ""; } else { return itr->second; } } void GeneralConfigSource::set(const std::string &key, const std::string &val) { VERBOSE(GeneralConfigSource) << key << " : " << val << std::endl; _map[key] = val; } } // namespace util } // namespace onert
24.76087
77
0.694469
periannath
7d2a71dd1670cd90b80409cf45bfba5f895e52d9
1,640
hpp
C++
src/neural_network/optimizer/Dropout.hpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
14
2019-08-29T07:20:19.000Z
2022-03-22T12:51:02.000Z
src/neural_network/optimizer/Dropout.hpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
7
2020-08-07T11:08:45.000Z
2021-05-08T17:11:12.000Z
src/neural_network/optimizer/Dropout.hpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
3
2020-08-07T10:53:52.000Z
2021-02-16T22:13:22.000Z
#pragma once #include <vector> #include <boost/serialization/unique_ptr.hpp> #include <boost/serialization/access.hpp> #include "LayerOptimizer.hpp" namespace snn::internal { class Dropout final : public LayerOptimizer { private: friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, unsigned version); float value; float reverseValue; std::vector<bool> presenceProbabilities; bool randomProbability() const; public: Dropout() = default; // use restricted to Boost library only Dropout(float value, BaseLayer* layer); Dropout(const Dropout& dropout, const BaseLayer* layer); ~Dropout() override = default; std::unique_ptr<LayerOptimizer> clone(const BaseLayer* newLayer) const override; void applyAfterOutputForTraining(std::vector<float>& outputs, bool temporalReset) override; void applyAfterOutputForTesting(std::vector<float>& outputs) override; void applyBeforeBackpropagation(std::vector<float>& inputErrors) override; bool operator==(const LayerOptimizer& optimizer) const override; bool operator!=(const LayerOptimizer& optimizer) const override; }; template <class Archive> void Dropout::serialize(Archive& ar, [[maybe_unused]] const unsigned version) { boost::serialization::void_cast_register<Dropout, LayerOptimizer>(); ar & boost::serialization::base_object<LayerOptimizer>(*this); ar & this->value; ar & this->reverseValue; ar & this->presenceProbabilities; } }
33.469388
99
0.686585
MatthieuHernandez
7d2aa9ccfbd1a966035a894fed92406364c154c9
204
cpp
C++
LixTalk-client/main.cpp
ZingLix/LixTalk-client
593ebf74ce64dedbc9eb109825e9abf864a5aaeb
[ "MIT" ]
null
null
null
LixTalk-client/main.cpp
ZingLix/LixTalk-client
593ebf74ce64dedbc9eb109825e9abf864a5aaeb
[ "MIT" ]
null
null
null
LixTalk-client/main.cpp
ZingLix/LixTalk-client
593ebf74ce64dedbc9eb109825e9abf864a5aaeb
[ "MIT" ]
null
null
null
#include "LixTalk.h" #include <QtWidgets/QApplication> #include <chrono> #include <iostream> int main(int argc, char *argv[]) { QApplication a(argc, argv); LixTalk w; w.show(); return a.exec(); }
12.75
33
0.676471
ZingLix
7d2ca683b07ed1e1b027d5368b418bded3002057
8,880
cpp
C++
src/display.cpp
milleniumbug/river_raid
992a6c85f838eb7e527b43cb54c6a5f2e6dc3c32
[ "MIT" ]
null
null
null
src/display.cpp
milleniumbug/river_raid
992a6c85f838eb7e527b43cb54c6a5f2e6dc3c32
[ "MIT" ]
null
null
null
src/display.cpp
milleniumbug/river_raid
992a6c85f838eb7e527b43cb54c6a5f2e6dc3c32
[ "MIT" ]
null
null
null
#include "stdafx.hpp" #include "utilities.hpp" #include "display.hpp" void Display::render(const Game& game) { SDL_Rect upper_rect = { 0, 0, static_cast<Uint16>(game_display_window_width), static_cast<Uint16>(game_display_window_height-80) }; SDL_Rect lower_rect = { 0, static_cast<Sint16>(game_display_window_height-80), static_cast<Uint16>(game_display_window_width), 80 }; SDL_FillRect(screen, &upper_rect, SDL_MapRGB(screen->format, 0,0,170)); current_view = 130 - game.pozycja_gracza().imag(); for(auto& entity : game.active_entities()) draw_action.at(typeid(*entity))(*this, *entity); SDL_FillRect(screen, &lower_rect, SDL_MapRGB(screen->format, 170,170,170)); SDL_Rect zycie_tekst_poz = { 30, static_cast<Sint16>(game_display_window_height-60) }; std::stringstream ilosc_zyc_tekst; ilosc_zyc_tekst << "Pozosta\xB3o \xBFyc: " << game.lives(); put_text_on_screen(ilosc_zyc_tekst.str().c_str(), zycie_tekst_poz); SDL_Rect paliwo_tekst_poz = { 200, static_cast<Sint16>(game_display_window_height-60) }; std::stringstream ilosc_paliwa_tekst; ilosc_paliwa_tekst << "Paliwo: " << game.paliwo_gracza_w_procentach() << "%"; put_text_on_screen(ilosc_paliwa_tekst.str().c_str(), paliwo_tekst_poz); SDL_Rect wynik_tekst_poz = { 30, static_cast<Sint16>(game_display_window_height-40) }; std::stringstream wynik_tekst; wynik_tekst << "Ilo\xB6\xE6 punkt\xF3w: " << game.score(); put_text_on_screen(wynik_tekst.str().c_str(), wynik_tekst_poz); SDL_Rect help_text_poz = { 400, static_cast<Sint16>(game_display_window_height-70) }; put_text_on_screen("River Raid Remake", help_text_poz); help_text_poz.y += 10; put_text_on_screen("Strzalki - steruj samolotem", help_text_poz); help_text_poz.y += 10; put_text_on_screen("Spacja - strzel", help_text_poz); help_text_poz.y += 10; SDL_Rect game_over_tekst_poz = { 30, static_cast<Sint16>(game_display_window_height-20) }; if(game.game_state() == Game::game_over) put_text_on_screen("GAME OVER, naci\xB6nij R by zagra\xE6 od nowa lub naci\xB6nij Esc by wyj\xB6\xE6.", game_over_tekst_poz); SDL_Flip(screen); current_frame = (current_frame+1)%frames_per_second; } Display::Display(int w, int h) : game_display_window_width(w), game_display_window_height(h), current_view(40), czcionka(raw_get_sprite("czcionka.bmp"), SDL_FreeSurface), current_frame(0) { screen = SDL_SetVideoMode(game_display_window_width, game_display_window_height, 32, 0); SDL_WM_SetCaption("River Raid", nullptr); graphical_timer = SDL_AddTimer(1000/frames_per_second, timer_callback, &graphical_timer); typedef draw_action_type::value_type action; draw_action.insert(action(typeid(Samolot), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("samolot.bmp"); disp.put_sprite_on_screen(s.get(), poz); })); draw_action.insert(action(typeid(NormalLand), [](Display& disp, Entity& e) { auto& land = dynamic_cast<NormalLand&>(e); auto trapez = land.granice(); std::transform(trapez.begin(), trapez.end(), trapez.begin(), [&disp](Zespolona z){ return disp.logical_position_to_graphical_position(z); }); SDL_Rect r = { std::min(trapez[0].real(), trapez[3].real()), std::min(disp.game_display_window_height - trapez[0].imag(), disp.game_display_window_height - trapez[3].imag()), std::abs(trapez[0].real() - trapez[3].real()), std::abs(trapez[0].imag() - trapez[3].imag()) }; disp.put_rectangle_on_screen(r, 34, 177, 76); })); draw_action.insert(action(typeid(House), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("dom.bmp"); disp.put_sprite_on_screen(s.get(), poz); })); draw_action.insert(action(typeid(Tree), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("drzewo.bmp"); disp.put_sprite_on_screen(s.get(), poz); })); auto draw_boat = [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("boat.bmp"); auto kierunek = dynamic_cast<EntityWithDirection&>(e).direction(); disp.put_sprite_on_screen(s.get(), poz, 2, (kierunek.real() < 0 ? 1 : 0)); }; draw_action.insert(action(typeid(StaticBoat), draw_boat)); draw_action.insert(action(typeid(DynamicBoat), draw_boat)); draw_action.insert(action(typeid(Fighter), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("mysliwiec.bmp"); auto kierunek = dynamic_cast<EntityWithDirection&>(e).direction(); disp.put_sprite_on_screen(s.get(), poz, 2, (kierunek.real() > 0 ? 1 : 0)); })); draw_action.insert(action(typeid(Heli), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("helikopter.bmp"); auto kierunek = dynamic_cast<EntityWithDirection&>(e).direction(); disp.put_sprite_on_screen(s.get(), poz, 8, (kierunek.real() < 0 ? 4 : 0) + disp.current_frame * 3 / 15 % 4); })); auto draw_bridge = [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("bridge.bmp"); disp.put_sprite_on_screen(s.get(), poz); }; draw_action.insert(action(typeid(Bridge), draw_bridge)); draw_action.insert(action(typeid(ImportantBridge), draw_bridge)); draw_action.insert(action(typeid(Bullet), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto bv = get_sprite("bulletv.bmp"); static auto bh = get_sprite("bulleth.bmp"); auto& projectile = dynamic_cast<Projectile&>(e); auto k = projectile.direction(); disp.put_sprite_on_screen(k.imag() == 0 ? bh.get() : bv.get(), poz, 2, k.real() > 0 ? 1 : 0); })); draw_action.insert(action(typeid(TankShell), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("czolg_shell.bmp"); disp.put_sprite_on_screen(s.get(), poz); })); draw_action.insert(action(typeid(FuelStation), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("fuel_station.bmp"); disp.put_sprite_on_screen(s.get(), poz); })); draw_action.insert(action(typeid(SmallExplosion), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("explosion_small.bmp"); auto& explosion = dynamic_cast<Explosion&>(e); int frame = 4 - explosion.time_to_live() / static_cast<double>(explosion.initial_time_to_live()) * 4; disp.put_sprite_on_screen(s.get(), poz, 4, frame); })); draw_action.insert(action(typeid(MediumExplosion), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("explosion_medium.bmp"); auto& explosion = dynamic_cast<Explosion&>(e); int frame = 4 - explosion.time_to_live() / static_cast<double>(explosion.initial_time_to_live()) * 4; disp.put_sprite_on_screen(s.get(), poz, 4, frame); })); draw_action.insert(action(typeid(LargeExplosion), [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("explosion_large.bmp"); auto& explosion = dynamic_cast<Explosion&>(e); int frame = 4 - explosion.time_to_live() / static_cast<double>(explosion.initial_time_to_live()) * 4; disp.put_sprite_on_screen(s.get(), poz, 4, frame); })); auto draw_tank = [](Display& disp, Entity& e) { auto poz = disp.logical_position_to_graphical_position(e.pozycja()); static auto s = get_sprite("czolg_body.bmp"); static auto t = get_sprite("czolg_turret.bmp"); auto& tank = dynamic_cast<Tank&>(e); disp.put_sprite_on_screen(s.get(), poz); double kat = std::arg(tank.turret_direction()); if(kat < 0) kat += 2*pi; disp.put_sprite_on_screen(t.get(), poz, 32, kat / (2*pi) * 32); }; draw_action.insert(action(typeid(StaticTank), draw_tank)); draw_action.insert(action(typeid(DynamicTank), draw_tank)); } Display::~Display() { SDL_RemoveTimer(graphical_timer); } void Display::put_text_on_screen(const std::string& str, SDL_Rect pozycja) { put_text_on_screen(str, pozycja, czcionka.get()); } void Display::put_text_on_screen(const std::string& str, SDL_Rect pozycja, SDL_Surface* font) { int px, py, c; SDL_Rect s, d; s.w = 8; s.h = 8; d.w = 8; d.h = 8; for(auto it = str.begin(); it != str.end(); ++it) { c = *it & 255; px = (c % 16) * 8; py = (c / 16) * 8; s.x = px; s.y = py; d.x = pozycja.x; d.y = pozycja.y; SDL_BlitSurface(czcionka.get(), &s, screen, &d); pozycja.x += 8; } }
40
130
0.715878
milleniumbug
7d2d7a43208e54bd51d3146d3f07b2a737c8db7c
1,745
cc
C++
test_hash.cc
pallas/libace
62477c78bd8848c80d91ffb311ad1c7708b655d7
[ "Zlib" ]
null
null
null
test_hash.cc
pallas/libace
62477c78bd8848c80d91ffb311ad1c7708b655d7
[ "Zlib" ]
null
null
null
test_hash.cc
pallas/libace
62477c78bd8848c80d91ffb311ad1c7708b655d7
[ "Zlib" ]
3
2018-06-04T12:52:51.000Z
2021-07-14T09:20:45.000Z
#include "hash.h" #include <cassert> #include <cstdlib> #include <string> #include <algorithm> int main(int, char*[]) { assert(lace::hash(0) == lace::hash(0)); assert(lace::hash<uint8_t>(1) == lace::hash<uint8_t>(1)); assert(lace::hash<uint16_t>(1) == lace::hash<uint16_t>(1)); assert(lace::hash<uint32_t>(1) == lace::hash<uint32_t>(1)); assert(lace::hash<uint64_t>(1) == lace::hash<uint64_t>(1)); assert(lace::hash<uint8_t>(1) != lace::hash<uint16_t>(1)); assert(lace::hash<uint16_t>(1) != lace::hash<uint32_t>(1)); assert(lace::hash<uint32_t>(1) != lace::hash<uint64_t>(1)); assert(lace::hash<uint8_t>(1) != lace::hash<uint8_t>(2)); assert(lace::hash<uint16_t>(1) != lace::hash<uint16_t>(2)); assert(lace::hash<uint32_t>(1) != lace::hash<uint32_t>(2)); assert(lace::hash<uint64_t>(1) != lace::hash<uint64_t>(2)); assert(lace::hash<const char *>("a") == lace::hash<const char *>("a")); assert(lace::hash<const char *>("a") != lace::hash<const char *>("b")); char c[] = "a"; assert(lace::hash<const char *>("a") == lace::hash<char *>(c)); assert(lace::hash("a") == lace::hash("a")); assert(lace::hash(L"a") == lace::hash(L"a")); assert(lace::hash(L"a") != lace::hash("a")); assert(lace::hash<const char *>("a") == lace::hash(std::string("a"))); assert(lace::hash<const char *>("a") != lace::hash(std::string("b"))); assert(lace::hash<std::string>(std::string("a")) == lace::hash<const std::string>(std::string("a"))); assert(lace::hash<std::string>(std::string("a")) != lace::hash<std::string>(("b"))); std::string A("A"); std::string aa("aa"); std::transform(A.begin(), A.end(), A.begin(), ::tolower); assert(lace::hash(A) == lace::hash(aa.substr(1))); return EXIT_SUCCESS; }
37.12766
103
0.603438
pallas
7d2ff077104f78ba5534f12a271add9d483f72e7
4,377
cpp
C++
NGS_testing/uParser/uTagTests.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
3
2015-11-23T14:24:06.000Z
2017-11-21T21:04:06.000Z
NGS_testing/uParser/uTagTests.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
null
null
null
NGS_testing/uParser/uTagTests.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
null
null
null
#include "uFormats.h" #include "uTags.h" #include "uRegion.h" #include <iostream> #include <string> #include <fstream> #include <vector> #include <time.h> #include <thread> #include <random> #include <string.h> #include "utility/utility.h" #include <time.h> #include <gtest/gtest.h> using namespace NGS; /**< Testing our unitary Tag */ TEST(uTagsTest, DefaultCTR){ uTags uTest; EXPECT_EQ(StrandDir::FORWARD,uTest.getStrand()); EXPECT_FALSE(uTest.isPE()); EXPECT_EQ(0,uTest.getStart()); EXPECT_EQ(0,uTest.getEnd()); } TEST(uTagsTest, 3ParCTR){ uTags Utest("chr1", 100, 200); EXPECT_EQ("chr1",Utest.getChr()); EXPECT_EQ(StrandDir::FORWARD,Utest.getStrand()); EXPECT_FALSE(Utest.isPE()); EXPECT_EQ(100,Utest.getStart()); EXPECT_EQ(200,Utest.getEnd()); } TEST(uTagsTest, 3ParCTRMinus){ EXPECT_ANY_THROW(uTags Utest("chr1", 200, 100)); // EXPECT_EQ("chr1",Utest.getChr()); // EXPECT_EQ(StrandDir::REVERSE,Utest.getStrand()); // EXPECT_FALSE(Utest.isPE()); // EXPECT_EQ(100,Utest.getStart()); // EXPECT_EQ(200,Utest.getEnd()); } TEST(uTagsTest, SetGet){ uTags Utest("chr1", 100, 200); uTags copyTag; Utest.setName("My Name is"); EXPECT_EQ("My Name is", Utest.getName()); EXPECT_EQ("", copyTag.getName()); Utest.setPhred("My Phred is"); EXPECT_EQ("My Phred is", Utest.getPhred()); Utest.setPhred("Now it is yar ar ar"); EXPECT_EQ("Now it is yar ar ar", Utest.getPhred()); copyTag=Utest; EXPECT_EQ("Now it is yar ar ar", Utest.getPhred()); Utest.setCigar("Hohoho"); EXPECT_EQ("Hohoho", Utest.getCigar()); } TEST(uTagsTest, CopyCTR){ uTags copyFrom("chr1", 100, 200); uTags copyTo; uTags copyFilled("chr4", 100000, 2000000); copyFrom.setName("My Name is"); copyFrom.setPhred("My Phred is"); copyFrom.setCigar("Hohoho"); copyFrom.setPELength(10); copyFrom.setMapQual(33); copyFrom.setSequence("LalaBonjourPatate"); copyTo.setChr("chr22"); copyTo.setMapped(true); copyTo=copyFrom; EXPECT_EQ(copyFrom.getPeLength(), copyTo.getPeLength()); EXPECT_EQ(copyFrom.getSequence(), copyTo.getSequence()); EXPECT_EQ(copyFrom.getMapQual(), copyTo.getMapQual()); EXPECT_EQ(copyFrom.getStrand(), copyTo.getStrand()); EXPECT_EQ(copyFrom.getName(), copyTo.getName()); EXPECT_EQ(copyFrom.getPhred(), copyTo.getPhred()); EXPECT_EQ(copyFrom.getSequence(), copyTo.getSequence()); EXPECT_EQ(copyFrom.getStart(), copyTo.getStart()); EXPECT_EQ(copyFrom.getChr(), copyTo.getChr()); EXPECT_EQ(copyFrom.getEnd(), copyTo.getEnd()); EXPECT_EQ(copyFrom.getCigar(), copyTo.getCigar()); copyTo.setChr("chr21"); EXPECT_NE(copyTo.getChr(),copyFrom.getChr()); copyFilled = copyFrom; EXPECT_EQ(copyFrom.getName(), copyFilled.getName()); EXPECT_EQ(copyFrom.getPhred(), copyFilled.getPhred()); EXPECT_EQ(copyFrom.getSequence(), copyFilled.getSequence()); EXPECT_EQ(copyFrom.getStart(), copyFilled.getStart()); EXPECT_EQ(copyFrom.getChr(), copyFilled.getChr()); EXPECT_EQ(copyFrom.getEnd(), copyFilled.getEnd()); } TEST(factoryTest, uTagsTest){ EXPECT_NO_THROW(uTags ourTest=factory::makeTagfromSamString("HWI-ST333_0111_FC:6:2202:20769:154221#TAGTCG/3 163 chr21 9719905 15 40M = 9719985 120 AGCAATTATCTTCACATAAAAACTACACAGAAACTTTCTG aaacceeegggggiiiiiiiiiihiihihiiiiiiiiiih X0:i:2 X1:i:57 MD:Z:2G2A27T6 XG:i:0 AM:i:0 NM:i:3 SM:i:0 XM:i:3 XO:i:0 XT:A:R")); uTags ourTest=factory::makeTagfromSamString("HWI-ST333_0111_FC:6:2202:20769:154221#TAGTCG/3 163 chr21 9719905 15 40M = 9719985 120 AGCAATTATCTTCACATAAAAACTACACAGAAACTTTCTG aaacceeegggggiiiiiiiiiihiihihiiiiiiiiiih X0:i:2 X1:i:57 MD:Z:2G2A27T6 XG:i:0 AM:i:0 NM:i:3 SM:i:0 XM:i:3 XO:i:0 XT:A:R"); EXPECT_EQ(ourTest.getChr(),"chr21"); EXPECT_EQ(ourTest.getLength(),40); EXPECT_EQ(ourTest.getStart(),9719905); EXPECT_EQ(ourTest.getEnd(),9719944); EXPECT_EQ(ourTest.getStrand(),StrandDir::FORWARD); uTags minusStrand; minusStrand=factory::makeTagfromSamString("HWI-ST333_0111_FC:6:2202:20769:154221#TAGTCG/3 83 chr21 9719905 15 40M = 9719985 120 AGCAATTATCTTCACATAAAAACTACACAGAAACTTTCTG aaacceeegggggiiiiiiiiiihiihihiiiiiiiiiih X0:i:2 X1:i:57 MD:Z:2G2A27T6 XG:i:0 AM:i:0 NM:i:3 SM:i:0 XM:i:3 XO:i:0 XT:A:R"); EXPECT_EQ(minusStrand.getStrand(),StrandDir::REVERSE); }
33.930233
314
0.705278
NGS-lib
7d3013745deb7db393378c97e18ae3e8e2f42bc3
2,808
cpp
C++
tests/RaZ/Render/Shader.cpp
Sausty/RaZ
211cc1c0c4a7374520a3141fc069b7717e2e5e0f
[ "MIT" ]
339
2017-09-24T17:26:15.000Z
2022-03-20T13:25:39.000Z
tests/RaZ/Render/Shader.cpp
Sausty/RaZ
211cc1c0c4a7374520a3141fc069b7717e2e5e0f
[ "MIT" ]
24
2017-09-22T10:30:12.000Z
2022-01-05T21:32:20.000Z
tests/RaZ/Render/Shader.cpp
Sausty/RaZ
211cc1c0c4a7374520a3141fc069b7717e2e5e0f
[ "MIT" ]
24
2018-01-21T17:38:18.000Z
2022-02-02T11:16:22.000Z
#include "Catch.hpp" #include "RaZ/Render/Renderer.hpp" #include "RaZ/Render/Shader.hpp" TEST_CASE("Shader validity") { Raz::Renderer::recoverErrors(); // Flushing errors { Raz::VertexShader vertShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); vertShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(vertShader.isValid()); } { Raz::GeometryShader geomShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(geomShader.isValid()); geomShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(geomShader.isValid()); } { Raz::FragmentShader fragShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); fragShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(fragShader.isValid()); } } TEST_CASE("Vertex shader from source") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string vertSource = R"( #version 330 core void main() { gl_Position = vec4(1.0); } )"; const Raz::VertexShader vertShader = Raz::VertexShader::loadFromSource(vertSource); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); vertShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isCompiled()); } TEST_CASE("Fragment shader from source") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string fragSource = R"( #version 330 core layout(location = 0) out vec4 fragColor; void main() { fragColor = vec4(1.0); } )"; const Raz::FragmentShader fragShader = Raz::FragmentShader::loadFromSource(fragSource); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); fragShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isCompiled()); } TEST_CASE("Vertex shader imported") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string vertShaderPath = RAZ_TESTS_ROOT + "../shaders/common.vert"s; const Raz::VertexShader vertShader(vertShaderPath); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); CHECK(vertShader.getPath() == vertShaderPath); vertShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isCompiled()); } TEST_CASE("Fragment shader imported") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string fragShaderPath = RAZ_TESTS_ROOT + "../shaders/lambert.frag"s; const Raz::FragmentShader fragShader(fragShaderPath); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); CHECK(fragShader.getPath() == fragShaderPath); fragShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isCompiled()); }
25.297297
89
0.696581
Sausty
7d308e882bb9fc4f933e53fc01cf3594cbfdbd04
909
cpp
C++
tests/src/TestTimings.cpp
iotcoop/pfff
c8d7bbb271320c6a5088b3d5ca810a172555884d
[ "BSD-3-Clause" ]
7
2015-05-18T04:37:43.000Z
2021-05-07T23:19:40.000Z
tests/src/TestTimings.cpp
iotcoop/pfff
c8d7bbb271320c6a5088b3d5ca810a172555884d
[ "BSD-3-Clause" ]
3
2015-07-20T09:28:23.000Z
2015-07-20T09:31:51.000Z
tests/src/TestTimings.cpp
iotcoop/pfff
c8d7bbb271320c6a5088b3d5ca810a172555884d
[ "BSD-3-Clause" ]
1
2019-02-20T10:58:49.000Z
2019-02-20T10:58:49.000Z
// Timings for Poly1305Aes and Md5 on 100mb of data (doesn't really "test" anything, just outputs results) #include "config.h" #include <string.h> #include "PfffPostHashing.h" void timings(long len, const char* title) { Md5Hasher md5; Poly1305AesHasher paes(1); ostringstream o1, o2; UnitTest::Timer t1, t2; char* memory = new char[len]; memset(memory, 0, len); t1.Start(); md5.output_hash(o1, memory, len); int time1 = t1.GetTimeInMs(); t2.Start(); paes.output_hash(o2, memory, len); int time2 = t2.GetTimeInMs(); delete[] memory; cout << "MD5(" << title << "): " << "\t" << time1 << endl; cout << "Poly1305AES(" << title << "):" << "\t" << time2 << endl; } TEST(TestTimings) { const long MB = 1024*1024; timings(1*MB, "1MB"); timings(10*MB, "10MB"); timings(100*MB, "100MB"); }
25.971429
107
0.570957
iotcoop
7d3273f11efd2af5e0ee426d3c1790d19dd893b3
6,546
cpp
C++
brain/sw/components/brain-httpd/firmware_handler.cpp
tomseago/sparklemotion
572369ff67977be3626a1162d208a33dddd33e63
[ "MIT" ]
24
2019-03-21T23:17:24.000Z
2022-03-10T07:59:27.000Z
brain/sw/components/brain-httpd/firmware_handler.cpp
tomseago/sparklemotion
572369ff67977be3626a1162d208a33dddd33e63
[ "MIT" ]
138
2019-03-21T23:29:48.000Z
2022-03-22T05:01:47.000Z
brain/sw/components/brain-httpd/firmware_handler.cpp
tomseago/sparklemotion
572369ff67977be3626a1162d208a33dddd33e63
[ "MIT" ]
5
2019-06-09T00:50:38.000Z
2022-02-02T04:22:44.000Z
// // Created by Tom Seago on 2019-08-07. // #include "firmware_handler.h" #include "http_server.h" #include <string.h> #include <sys/param.h> #include <esp_ota_ops.h> /* Max length a file path can have on storage */ //#define FILE_PATH_MAX (ESP_VFS_PATH_MAX + CONFIG_SPIFFS_OBJ_NAME_LEN) #define SCRATCH_BUFSIZE 8192 #define TAG TAG_HTTPD static esp_err_t glue_putHandler(httpd_req_t *req) { if (!req) return ESP_ERR_INVALID_ARG; return ((FirmwareHandler*)(req->user_ctx))->_putHandler(req); } esp_err_t FirmwareHandler::registerHandlers(HttpServer &server) { // Also do the equivalent initialization stuff - maybe want to come up with // a scheme for doing this better elsewhere //strcpy(this->basePath, "/spiffs/www"); httpd_uri_t firmwareHandler = { .uri = "/firmware", .method = HTTP_POST, .handler = glue_putHandler, .user_ctx = this, }; esp_err_t err; err = httpd_register_uri_handler(server.m_hServer, &firmwareHandler); if (ESP_OK != err) { ESP_LOGE(TAG, "Failed to register PUT uri handler %d", err); return err; } return ESP_OK; } // #define IS_FILE_EXT(filename, ext) \ // // (strcasecmp(&filename[strlen(filename) - sizeof(ext) + 1], ext) == 0) /* Set HTTP response content type according to file extension */ //static esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename) //{ // if (IS_FILE_EXT(filename, ".pdf")) { // return httpd_resp_set_type(req, "application/pdf"); // } else if (IS_FILE_EXT(filename, ".html")) { // return httpd_resp_set_type(req, "text/html"); // } else if (IS_FILE_EXT(filename, ".jpeg")) { // return httpd_resp_set_type(req, "image/jpeg"); // } else if (IS_FILE_EXT(filename, ".ico")) { // return httpd_resp_set_type(req, "image/x-icon"); // } // /* This is a limited set only */ // /* For any other type always set as plain text */ // return httpd_resp_set_type(req, "text/plain"); //} // ///* Copies the full path into destination buffer and returns // * pointer to path (skipping the preceding base path) */ //static const char* get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize) //{ // const size_t base_pathlen = strlen(base_path); // size_t pathlen = strlen(uri); // // const char *quest = strchr(uri, '?'); // if (quest) { // pathlen = MIN(pathlen, quest - uri); // } // const char *hash = strchr(uri, '#'); // if (hash) { // pathlen = MIN(pathlen, hash - uri); // } // // if (base_pathlen + pathlen + 1 > destsize) { // /* Full path string won't fit into destination buffer */ // return NULL; // } // // /* Construct full path (base + path) */ // strcpy(dest, base_path); // strlcpy(dest + base_pathlen, uri, pathlen + 1); // // /* Return pointer to path, skipping the base */ // return dest + base_pathlen; //} static void logFree(void *ctx) { ESP_LOGI(TAG, "Freeing a ctx"); free(ctx); } esp_err_t FirmwareHandler::_putHandler(httpd_req_t *req) { ESP_LOGE(TAG, "==== OTA via HTTP PUT Started ===="); // Could check filesize, but don't really care // req->content_len const esp_partition_t* updatePartition = esp_ota_get_next_update_partition(nullptr); if (!updatePartition) { ESP_LOGE(TAG, "Unable to get a next ota update partition"); return ESP_FAIL; } esp_ota_handle_t otaHandle; if (ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_begin(updatePartition, OTA_SIZE_UNKNOWN, &otaHandle)) != ESP_OK) { return ESP_FAIL; } ESP_LOGE(TAG, "ota_begin() call succeeded."); ESP_LOGI(TAG, " type = %d", updatePartition->type); ESP_LOGI(TAG, " subtype = %d", updatePartition->subtype); ESP_LOGI(TAG, " address = 0x%x", updatePartition->address); ESP_LOGI(TAG, " size = %d", updatePartition->size); ESP_LOGI(TAG, " label = %s", updatePartition->label); if (!req->sess_ctx) { ESP_LOGI(TAG, "Creating a new session context"); req->sess_ctx = malloc(SCRATCH_BUFSIZE); if (!req->sess_ctx) { ESP_LOGE(TAG, "Failed to create session chunk buffer"); return ESP_FAIL; } req->free_ctx = logFree; } int received; int remaining = req->content_len; char* buf = (char*)req->sess_ctx; while (remaining > 0) { ESP_LOGI(TAG, "Remaining OTA size : %d", remaining); /* Receive the file part by part into a buffer */ if ((received = httpd_req_recv(req, buf, MIN(remaining, SCRATCH_BUFSIZE))) <= 0) { if (received == HTTPD_SOCK_ERR_TIMEOUT) { /* Retry if timeout occurred */ continue; } /* In case of unrecoverable error, * close and delete the unfinished file*/ esp_ota_end(otaHandle); ESP_LOGE(TAG, "Firmware reception failed!"); /* Respond with 500 Internal Server Error */ httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to receive firmware"); return ESP_FAIL; } /* Write buffer content to file on storage */ if (esp_ota_write(otaHandle, buf, received) != ESP_OK) { esp_ota_end(otaHandle); ESP_LOGE(TAG, "Firmware write failed!"); /* Respond with 500 Internal Server Error */ httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to write file to storage"); return ESP_FAIL; } /* Keep track of remaining size of * the file left to be uploaded */ remaining -= received; } auto endResult = esp_ota_end(otaHandle); if (endResult != ESP_OK) { ESP_LOGE(TAG, "OTA Failed with %d", endResult); /* Respond with an empty chunk to signal HTTP response completion */ httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; } ESP_LOGE(TAG, "==== Valid OTA received ===="); auto setResult = esp_ota_set_boot_partition(updatePartition); if (setResult != ESP_OK) { ESP_LOGE(TAG, "Setting the OTA boot partition failed: %d", endResult); /* Respond with an empty chunk to signal HTTP response completion */ httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; } ESP_LOGE(TAG, "Boot partition set, Triggering restart"); brain_restart(500); httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; }
33.228426
112
0.624809
tomseago
7d378c26fe0c1298e99d86382bebb7d058ff596f
5,774
cpp
C++
newbase/NFmiSnapShotInterface.cpp
fmidev/smartmet-library-newbase
12d93660c06e3c66a039ea75530bd9ca5daf7ab8
[ "MIT" ]
null
null
null
newbase/NFmiSnapShotInterface.cpp
fmidev/smartmet-library-newbase
12d93660c06e3c66a039ea75530bd9ca5daf7ab8
[ "MIT" ]
7
2017-01-17T10:46:33.000Z
2019-11-21T07:50:17.000Z
newbase/NFmiSnapShotInterface.cpp
fmidev/smartmet-library-newbase
12d93660c06e3c66a039ea75530bd9ca5daf7ab8
[ "MIT" ]
2
2017-01-17T07:33:28.000Z
2018-04-26T07:10:23.000Z
// ====================================================================== /*! * \file NFmiSnapShotInterface.cpp * \brief Implementation of class NFmiSnapShortInterface */ // ====================================================================== #include "NFmiSnapShotInterface.h" #include <macgyver/Exception.h> #include <ctime> #include <fstream> using namespace std; // ---------------------------------------------------------------------- /*! * Destructor */ // ---------------------------------------------------------------------- NFmiSnapShotInterface::~NFmiSnapShotInterface() { try { delete itsData; delete itsInfo; } catch (...) { Fmi::Exception exception(BCP, "Destructor failed", nullptr); exception.printError(); } } // ---------------------------------------------------------------------- /*! * Constructor * * \param theDataFileName Undocumented * \param theWorkingDirectory Undocumented * \param theSourceDirectory Undocumented * \param theUpdateInterval Undocumented */ // ---------------------------------------------------------------------- NFmiSnapShotInterface::NFmiSnapShotInterface(NFmiString theDataFileName, NFmiString theWorkingDirectory, NFmiString theSourceDirectory, time_t theUpdateInterval) : fIsValid(), itsUpdateInterval(theUpdateInterval), itsInfo(nullptr), itsData(nullptr), itsDataFileName(), itsSourceDirectory(theSourceDirectory), itsWorkingDirectory(theWorkingDirectory), itsStartingTime(time(nullptr)) { try { theDataFileName.UpperCase(); if (theDataFileName == NFmiString("ECMWF")) { itsDataFileName = "ECMWF_Suomi_192_3_uusin.sqd"; } else if (theDataFileName == NFmiString("HIRLAM")) { itsDataFileName = "HIRLAM_Suomi_48_1_uusin.sqd"; } else if (theDataFileName == NFmiString("KEPA")) { itsDataFileName = "kepa_suomi_168_1_uusin.sqd"; } else if (theDataFileName == NFmiString("KEPALYHYT")) { itsDataFileName = "Kepa_LightBoy_Uusin.sqd"; } else if (theDataFileName == NFmiString("KEPAPITKÄ")) { itsDataFileName = "Kepa_FatBoy_Uusin.sqd"; } else if (theDataFileName == NFmiString("SYNOP")) { itsDataFileName = "Havainto_uusin.fqd"; } else if (theDataFileName == NFmiString("TUTKA")) { itsDataFileName = "RadRain1h_ennuste4h10km.sqd"; } else if (theDataFileName == NFmiString("TUTKATIHEÄ")) { itsDataFileName = "Sadekertyma-1_uusin.sqd"; } else if (theDataFileName == NFmiString("TOPOGRAFIA")) { itsDataFileName = R"(Mask\topography_europe_400x399_polster_text.fqd)"; } else if (theDataFileName == NFmiString("TIEPIIRIT")) { itsDataFileName = R"(Mask\tiealueet2.sqd)"; } else { itsDataFileName = theDataFileName; } } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } // ---------------------------------------------------------------------- /*! * \param theInfo Undocumented * \return Undocumented */ // ---------------------------------------------------------------------- bool NFmiSnapShotInterface::Update(NFmiQueryInfo** theInfo) { try { bool retBool = false; if (IsValid()) return retBool; else if (itsInfo) { retBool = true; if (*theInfo) delete *theInfo; } else if (ReadData()) { retBool = true; } if (itsInfo) *theInfo = new NFmiQueryInfo(*itsInfo); return retBool; } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- bool NFmiSnapShotInterface::IsValid() { try { if (!itsInfo || time(nullptr) - itsStartingTime > itsUpdateInterval) return false; return true; } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } // ---------------------------------------------------------------------- /*! * \return Undocumented */ // ---------------------------------------------------------------------- bool NFmiSnapShotInterface::ReadData() { try { // Kopioidaan tiedosto paikalliseksi NFmiString command = NFmiString("clone.exe "); command += itsSourceDirectory; command += NFmiString(" "); command += itsDataFileName; command += NFmiString(" "); command += itsWorkingDirectory; // Mika 08.11.2001 Kayttamaton paluuarvo antaa varoituksia. // int aRet = system(command); // if( aRet != 0 ) // return false; system(command); delete itsData; delete itsInfo; itsData = nullptr; itsInfo = nullptr; NFmiString fileName = NFmiString(itsWorkingDirectory) += itsDataFileName; ifstream localFile; localFile.open(fileName, ios::in | ios::binary); if (localFile) { itsData = new NFmiQueryData(); localFile >> *itsData; localFile.close(); } else { ifstream remoteFile; fileName = NFmiString(itsSourceDirectory) += itsDataFileName; remoteFile.open(fileName, ios::in | ios::binary); if (remoteFile) { itsData = new NFmiQueryData(); remoteFile >> *itsData; remoteFile.close(); } else return false; } itsInfo = new NFmiQueryInfo(itsData); return true; } catch (...) { throw Fmi::Exception::Trace(BCP, "Operation failed!"); } } // ======================================================================
24.995671
77
0.518358
fmidev
7d392cb87a83460a79a6304169facef98f988304
2,451
cpp
C++
test/test.cpp
AZMDDY/astar
49ea623e042181e29a3de17bf79ec872d104fe61
[ "MIT" ]
2
2020-10-20T00:03:49.000Z
2020-10-24T09:27:13.000Z
test/test.cpp
AZMDDY/astar
49ea623e042181e29a3de17bf79ec872d104fe61
[ "MIT" ]
null
null
null
test/test.cpp
AZMDDY/astar
49ea623e042181e29a3de17bf79ec872d104fe61
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include "point.hpp" #include "map.hpp" #include "astar.hpp" #include "play.hpp" using namespace astar; Point MapRandPoint(uint32_t h, uint32_t w) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, h * w); auto res = dis(gen); int pH = res / w; int pW = res - pH * w; return {pW, pH}; } void GenBarrier(Map& map) { uint32_t count = (map.Height() * map.Width()) / 8; for (uint32_t i = 0; i < count;) { auto point = MapRandPoint(map.Height(), map.Width()); if (map.At(point) == 0) { map.Assign(point, 1); i++; } else { continue; } } } void GenStartAndEnd(Map& map, Point& start, Point& end) { if (map.Empty()) { return; } for (uint32_t i = 0; i < 2;) { auto point = MapRandPoint(map.Height(), map.Width()); if (map.At(point) == 0) { if (i == 0) { map.Assign(point, 2); start = point; } else { map.Assign(point, 3); end = point; } i++; } else { continue; } } } int main(int argc, char** argv) { uint32_t mapHeight = 0; uint32_t mapWidth = 0; std::cout << "map width: "; std::cin >> mapWidth; std::cout << "map height: "; std::cin >> mapHeight; Map maze(mapWidth, mapHeight); GenBarrier(maze); Point start; Point end; GenStartAndEnd(maze, start, end); AStar aStar(D8); aStar.LoadMap(maze); auto path = aStar.FindPath(start, end); // display the maze uint32_t count = 0; PrintMaze(maze); if (path.empty()) { std::cout << "path not found" << std::endl; return 0; } while (count < path.size()) { std::this_thread::sleep_for(1s); ClearScreen(maze.Height() + 1); maze.Assign(path[count], 4); PrintMaze(maze); ClearScreen(1); std::cout << "(" << path[count].x << ", " << path[count].y << ")" << std::endl; count++; } ClearScreen(maze.Height() + 1); PrintMaze(maze); uint32_t i = 0; for (; i < (path.size() - 1); i++) { std::cout << "(" << path[i].x << ", " << path[i].y << ") -> "; } std::cout << "(" << path[i].x << ", " << path[i].y << ")" << std::endl; return 0; }
23.122642
87
0.485924
AZMDDY
7d3c01ed6da3271047049ba6a690530cb4932984
8,237
cpp
C++
src/zoneserver/service/cheat/CheatService.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
src/zoneserver/service/cheat/CheatService.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
src/zoneserver/service/cheat/CheatService.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
#include "ZoneServerPCH.h" #include "CheatService.h" #include "../arena/ArenaService.h" #include "../../model/gameobject/EntityEvent.h" #include "../../model/gameobject/Entity.h" #include "../../model/gameobject/AbstractAnchor.h" #include "../../model/gameobject/ability/Cheatable.h" #include "../../model/gameobject/ability/Networkable.h" #include "../../controller/EntityController.h" #include "../../controller/callback/BotCommandCallback.h" #include "../../controller/callback/BuildingStateCallback.h" #include "../../helper/InventoryHelper.h" #include "../../service/anchor/AnchorService.h" #include "../../service/arena/ArenaService.h" #include "../../world/World.h" #include "../../ZoneService.h" #include "../../s2s/ZoneArenaServerProxy.h" #include <sne/core/utility/Unicode.h> #include <boost/lexical_cast.hpp> namespace gideon { namespace zoneserver { /** * @class BotMoveEvent */ class BotMoveEvent : public go::EntityEvent, public sne::core::ThreadSafeMemoryPoolMixin<BotMoveEvent> { public: BotMoveEvent(const Position& position) : position_(position) {} private: virtual void call(go::Entity& entity) { gc::BotCommandCallback* callback = entity.getController().queryBotCommandCallback(); if (callback != nullptr) { callback->commandMoved(position_); } } private: const Position position_; }; /** * @class BotSkillCastEvent */ class BotSkillCastEvent : public go::EntityEvent, public sne::core::ThreadSafeMemoryPoolMixin<BotSkillCastEvent> { public: BotSkillCastEvent() {} private: virtual void call(go::Entity& entity) { gc::BotCommandCallback* callback = entity.getController().queryBotCommandCallback(); if (callback != nullptr) { callback->commandSkillCasted(); } } }; void CheatService::execute(go::Cheatable& cheatable, ObjectId ownerId, const wstring_t& command, const wstring_t& params) { if (! cheatable.canCheatable()) { return; } try { if (command == L"/additem") { const size_t find_pos = params.find_first_of(L" "); const string_t param1 = sne::core::toUtf8(params.substr(0, find_pos)); const string_t param2 = sne::core::toUtf8(params.substr(find_pos + 1)); const DataCode itemCode = boost::lexical_cast<DataCode>(param1); const uint8_t itemCount = uint8_t(boost::lexical_cast<uint32_t>(param2)); const uint8_t revisionItemCount = itemCount > getStackItemCount(itemCode) ? getStackItemCount(itemCode) : itemCount; const CodeType ct = getCodeType(itemCode); if (isItemType(ct)) { cheatable.cheatAddItem(itemCode, revisionItemCount); } } else if (command == L"/move") { const size_t find_pos = params.find_first_of(L" "); const wstring_t param1 = params.substr(0, find_pos); const wstring_t param2 = params.substr(find_pos + 1); const Position position(boost::lexical_cast<float32_t>(param1), boost::lexical_cast<float32_t>(param2), 0.0f); BotMoveEvent::Ref event(new BotMoveEvent(position)); WORLD->broadcast(event); // 브로드 캐스팅 } else if (command == L"/castskill") { BotSkillCastEvent::Ref event(new BotSkillCastEvent()); WORLD->broadcast(event); } else if (command == L"/fullpoints") { cheatable.cheatFullCharacterPoints(); } else if (command == L"/rewardexp") { const ExpPoint rewardExp = toExpPoint(boost::lexical_cast<int>(params)); cheatable.cheatRewardExp(rewardExp < ceMin ? ceMin: rewardExp); } else if (command == L"/showmethemoney") { const GameMoney money = boost::lexical_cast<GameMoney>(params); cheatable.cheatUpGameMoney(money < 0 ? 0 : money); } else if (command == L"/addskill") { const SkillCode skillCode = boost::lexical_cast<SkillCode>(params); cheatable.cheatAddSkill(skillCode); } else if (command == L"/recall") { const size_t find_pos = params.find_first_of(L" "); const Nickname nickname = params.substr(0, find_pos); cheatable.cheatRecall(nickname); } else if (command == L"/toplayer") { const size_t find_pos = params.find_first_of(L" "); const Nickname nickname = params.substr(0, find_pos); cheatable.cheatTeleportToPlayer(nickname); } else if (command == L"/toposition") { wstring_t tempParams = params; size_t find_pos = params.find_first_of(L" "); const wstring_t param1 = tempParams.substr(0, find_pos); tempParams = tempParams.substr(find_pos + 1); find_pos = tempParams.find_first_of(L" "); const wstring_t param2 = tempParams.substr(0, find_pos); tempParams = tempParams.substr(find_pos + 1); const wstring_t param3 = tempParams.substr(0, find_pos); const float32_t positionX = boost::lexical_cast<float32_t>(param1); const float32_t positionY = boost::lexical_cast<float32_t>(param2); const float32_t positionZ = boost::lexical_cast<float32_t>(param3); cheatable.cheatTeleportToPosition(Position(positionX, positionY, positionZ)); } else if (command == L"/mercenarypoint") { const MercenaryPoint mercenaryPoint = boost::lexical_cast<MercenaryPoint>(params); cheatable.cheatMercenaryPoint(mercenaryPoint < 0 ? 0 : mercenaryPoint); } else if (command == L"/logout") { const size_t find_pos = params.find_first_of(L" "); const Nickname nickname = params.substr(0, find_pos); go::Entity* player = WORLD->getPlayer(nickname); if (player) { player->queryNetworkable()->logout(); } } else if (command == L"/arenapoint") { const ArenaPoint arenaPoint = boost::lexical_cast<ArenaPoint>(params); cheatable.cheatArenaPoint(arenaPoint < 0 ? 0 : arenaPoint); } else if (command == L"/releasedeserter") { if (ZONE_SERVICE->isArenaServer()) { ARENA_SERVICE->releaseDeserter(ownerId); } else { ZONE_SERVICE->getArenaServerProxy().z2a_releaseDeserter(ownerId); } } else if (command == L"/who") { cheatable.cheatWhoIsInZone(); } else if (command == L"/destorybuilding") { const ObjectId buildingId = boost::lexical_cast<ObjectId>(params); go::AbstractAnchor* abstractAnchor = ANCHOR_SERVICE->getAnchor(GameObjectInfo(otBuilding, buildingId)); if (abstractAnchor) { gc::BuildingStateCallback* callback = abstractAnchor->getController().queryBuildingStateCallback(); if (callback) { callback->buildDestroyed(); static_cast<go::Entity*>(abstractAnchor)->despawn(); } } } else if (command == L"/destoryanchor") { const ObjectId buildingId = boost::lexical_cast<ObjectId>(params); go::AbstractAnchor* abstractAnchor = ANCHOR_SERVICE->getAnchor(GameObjectInfo(otAnchor, buildingId)); if (abstractAnchor) { static_cast<go::Entity*>(abstractAnchor)->despawn(); } } else if (command == L"/resetcooltime") { cheatable.cheatResetCooldown(); } else if (command == L"/acceptquest") { const QuestCode questCode = boost::lexical_cast<QuestCode>(params); cheatable.cheatAcceptQuest(questCode); } else if (command == L"/forgeCoin") { const ForgeCoin forgeCoin = boost::lexical_cast<ForgeCoin>(params); cheatable.cheatForgeCoin(forgeCoin < 0 ? 0 : forgeCoin); } } catch (boost::bad_lexical_cast&) { SNE_LOG_ERROR("bad cheat key") } } }} // namespace gideon { namespace zoneserver {
40.576355
115
0.613573
mark-online
7d3e45754d10d7f5a3906f9998026b41ba7b5b92
395
cpp
C++
FIGUREFUL/main.cpp
raafatabualazm/Competitive-Programming-Solutions
3c8c953e9597e64a77e804ba4d3881c8f0354c7a
[ "MIT" ]
null
null
null
FIGUREFUL/main.cpp
raafatabualazm/Competitive-Programming-Solutions
3c8c953e9597e64a77e804ba4d3881c8f0354c7a
[ "MIT" ]
null
null
null
FIGUREFUL/main.cpp
raafatabualazm/Competitive-Programming-Solutions
3c8c953e9597e64a77e804ba4d3881c8f0354c7a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { map<pair<int, int>, string> code; string name; int m,n,k1,k2; scanf("%d", &m); while (m--) { cin >> k1 >> k2 >> name; code[make_pair(k1, k2)] = name; } scanf("%d", &n); while(n--) { scanf("%d%d", &k1, &k2); cout << code[make_pair(k1,k2)] << endl; } return 0; }
17.173913
47
0.463291
raafatabualazm
7d42aec8e09eca5b92cc375c7235b51ff9e93e21
4,171
hpp
C++
include/foxy/impl/session/async_read.impl.hpp
djarek/foxy
c5a008760505f670e599216e003f08963c32d201
[ "BSL-1.0" ]
null
null
null
include/foxy/impl/session/async_read.impl.hpp
djarek/foxy
c5a008760505f670e599216e003f08963c32d201
[ "BSL-1.0" ]
null
null
null
include/foxy/impl/session/async_read.impl.hpp
djarek/foxy
c5a008760505f670e599216e003f08963c32d201
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot // com) // // 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) // // Official repository: https://github.com/LeonineKing1199/foxy // #ifndef FOXY_IMPL_SESSION_ASYNC_READ_IMPL_HPP_ #define FOXY_IMPL_SESSION_ASYNC_READ_IMPL_HPP_ #include <foxy/session.hpp> namespace foxy { namespace detail { template <class Stream, class Parser, class ReadHandler> struct read_op : boost::asio::coroutine { private: struct state { ::foxy::basic_session<Stream>& session; Parser& parser; boost::asio::executor_work_guard<decltype(session.get_executor())> work; explicit state(ReadHandler const& handler, ::foxy::basic_session<Stream>& session_, Parser& parser_) : session(session_) , parser(parser_) , work(session.get_executor()) { } }; boost::beast::handler_ptr<state, ReadHandler> p_; public: read_op() = delete; read_op(read_op const&) = default; read_op(read_op&&) = default; template <class DeducedHandler> read_op(::foxy::basic_session<Stream>& session, Parser& parser, DeducedHandler&& handler) : p_(std::forward<DeducedHandler>(handler), session, parser) { } using executor_type = boost::asio::associated_executor_t< ReadHandler, decltype((std::declval<::foxy::basic_session<Stream>&>().get_executor()))>; using allocator_type = boost::asio::associated_allocator_t<ReadHandler>; auto get_executor() const noexcept -> executor_type { return boost::asio::get_associated_executor(p_.handler(), p_->session.get_executor()); } auto get_allocator() const noexcept -> allocator_type { return boost::asio::get_associated_allocator(p_.handler()); } auto operator()(boost::system::error_code ec, std::size_t const bytes_transferred, bool const is_continuation = true) -> void; }; template <class Stream, class Parser, class ReadHandler> auto read_op<Stream, Parser, ReadHandler>:: operator()(boost::system::error_code ec, std::size_t const bytes_transferred, bool const is_continuation) -> void { using namespace std::placeholders; using boost::beast::bind_handler; namespace http = boost::beast::http; auto& s = *p_; BOOST_ASIO_CORO_REENTER(*this) { BOOST_ASIO_CORO_YIELD http::async_read(s.session.stream, s.session.buffer, s.parser, std::move(*this)); if (ec) { goto upcall; } { auto work = std::move(s.work); return p_.invoke(boost::system::error_code(), bytes_transferred); } upcall: if (!is_continuation) { BOOST_ASIO_CORO_YIELD boost::asio::post(bind_handler(std::move(*this), ec, 0)); } auto work = std::move(s.work); p_.invoke(ec, 0); } } } // namespace detail template <class Stream, class X> template <class Parser, class ReadHandler> auto basic_session<Stream, X>::async_read( Parser& parser, ReadHandler&& handler) & -> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void(boost::system::error_code, std::size_t)) { boost::asio::async_completion<ReadHandler, void(boost::system::error_code, std::size_t)> init(handler); detail::timed_op_wrapper<Stream, detail::read_op, BOOST_ASIO_HANDLER_TYPE( ReadHandler, void(boost::system::error_code, std::size_t)), void(boost::system::error_code, std::size_t)>( *this, std::move(init.completion_handler)) .template init<Stream, Parser>(parser); return init.result.get(); } } // namespace foxy #endif // FOXY_IMPL_SESSION_ASYNC_READ_IMPL_HPP_
28.37415
80
0.614481
djarek
7d43465d3369eb5606cc416932eb52bd194549d1
2,428
cpp
C++
src/container/Handle.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
45
2018-08-24T12:57:38.000Z
2021-11-12T11:21:49.000Z
src/container/Handle.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
null
null
null
src/container/Handle.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
4
2019-09-16T02:48:42.000Z
2020-07-10T03:50:31.000Z
#include "Handle.h" #include <atomic> #include "../system/Memory.h" using namespace L; static constexpr uint32_t address_bits = 48; static constexpr uint64_t address_mask = (1ull << address_bits) - 1; static constexpr uint64_t version_bits = 16; static constexpr uint64_t version_mask = (1ull << version_bits) - 1; static uint64_t* handle_objects = nullptr; static std::atomic<uint64_t> next_index = {0}; static std::atomic<uint64_t> freelist = {address_mask}; GenericHandle::GenericHandle(void* ptr) { L_ASSERT((uint64_t(ptr) & address_mask) == uint64_t(ptr)); for(uint64_t freeslot_index; freeslot_index = freelist, freelist != address_mask;) { const uint64_t freeslot = handle_objects[freeslot_index]; const uint64_t version = freeslot >> address_bits; const uint64_t new_freeslot_index = freeslot & address_mask; _ver_index = (version << address_bits) | freeslot_index; if(!freelist.compare_exchange_strong(freeslot_index, new_freeslot_index)) { continue; } handle_objects[freeslot_index] = (version << address_bits) | (uint64_t)ptr; return; } // Allocate memory for handle slots if(handle_objects == nullptr) { handle_objects = (uint64_t*)Memory::virtual_alloc(1ull << 20); } // Allocate new handle slot _ver_index = next_index++; handle_objects[_ver_index] = uint64_t(ptr); } void* GenericHandle::pointer() const { if(_ver_index != UINT64_MAX) { const uint64_t version = _ver_index >> address_bits; const uint64_t index = _ver_index & address_mask; const uint64_t object = handle_objects[index]; // Check object version matches if((object >> address_bits) == version) { return (void*)(object & address_mask); } } return nullptr; } uint64_t GenericHandle::index() const { return _ver_index & address_mask; } void GenericHandle::release() { if(_ver_index != UINT64_MAX) { const uint64_t version = _ver_index >> address_bits; const uint64_t new_freeslot_index = _ver_index & address_mask; const uint64_t new_freeslot = handle_objects[new_freeslot_index]; if((new_freeslot >> address_bits) == version) { uint64_t old_freeslot; do { old_freeslot = freelist; handle_objects[new_freeslot_index] = ((version + 1) << address_bits) | old_freeslot; } while(!freelist.compare_exchange_strong(old_freeslot, new_freeslot_index)); } _ver_index = UINT64_MAX; } }
31.128205
92
0.714168
Lyatus
7d4720b4431a56e6c41a15c12ad8269e2db1b0da
5,805
cpp
C++
assignment2/A2.cpp
Uncle-Road/CS205_cpp
95d1e73676e0db65da077d1e6dc5148a5fa9a9ab
[ "MIT" ]
null
null
null
assignment2/A2.cpp
Uncle-Road/CS205_cpp
95d1e73676e0db65da077d1e6dc5148a5fa9a9ab
[ "MIT" ]
null
null
null
assignment2/A2.cpp
Uncle-Road/CS205_cpp
95d1e73676e0db65da077d1e6dc5148a5fa9a9ab
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <cstring> #include <cmath> #include <cstdlib> //support for exit() #include <algorithm> #include <vector> using namespace std; struct city { string name ; string country; double longitude; double latitude; }; const double R = 6371; const double PI = 3.1415926535; const double val = PI/180; #define MAX_NAME_LENGTH 35 #define MAX_ARRAY_LENTH 1000 #define FILE_NAME "world_cities.csv" vector<const city *> choose_City{}; bool end_judge(string str); string trim(string str); bool is_number(const std::string &s); vector<city> readFile(const string &filename); bool InputCity(const city **p, const vector<city> &cityList); double findDistance(const city &city1, const city &city2); void process(vector<city> cityList); int main(){ vector<city> cityList = readFile(FILE_NAME); if(cityList.size()==0){ return 0; } process(cityList); cout<<"Progarm is end!"<<endl; return 0; } void process(vector<city> cityList){ while (true) { const city *c1 = nullptr, *c2 = nullptr; while (c1 == nullptr) { cout<<"\n------------------------------------"<<endl; cout<<"Input \"bye\" to end the programmer! You need at least input three char"<<endl; cout << "please input the first city name: "; if (!InputCity(&c1, cityList)) { return ; } } while (c2 == nullptr) { cout << "please input the second city name: "; if (!InputCity(&c2, cityList)) { return ; } } double distance = findDistance(*c1, *c2); cout << "The distance between " << c1->name << " and " << c2->name << " is " << distance << " km." << endl; } return; } bool end_judge(string str) { if (str.size() == 3 && ('b' == str[0] || 'B' == str[0]) && ('y' == str[1] || 'Y' == str[1]) && ('e' == str[2] || 'E' == str[2]) ) { return true; } return false; } string trim(string str) { if (str.empty()) return str; str.erase(0, str.find_first_not_of(" ")); str.erase(str.find_last_not_of(" ") + 1); return str; } bool is_number(const string &str) { bool a,b; a= !str.empty(); b= find_if(str.begin(), str.end(),[](unsigned char c) { return !isdigit(c); }) == str.end(); return a&&b; } vector<city> readFile(const string &filename){ vector<city> cityList; ifstream inFile; inFile.open(filename); if(!inFile.good()){ cout << "we can\'t open this file: " <<filename <<endl; exit(EXIT_FAILURE); return cityList; } int line_serial =1; string data; while(getline(inFile,data)){ if(cityList.size() >= MAX_ARRAY_LENTH){ cout <<"This file too larger! It more than " << MAX_ARRAY_LENTH <<" lines, operate skipping instruction." <<endl; } string separate = ","; string information[5]; int num =0; size_t index=0; //divide while((index = data.find(separate)) != string::npos){ information[num] = data.substr(0,index); data.erase(0,index + 1); num++; } information[num] = data; if(information[0].size() > MAX_NAME_LENGTH || information[2].size()>MAX_NAME_LENGTH ){ cout <<"No." <<line_serial<<" name length is larger than "<<MAX_NAME_LENGTH << " skip this line."<<endl; } //store transform(information[0].begin(),information[0].end(),information[0].begin(),::toupper); city city1; city1.name = information[0]; city1.country = information[2]; city1.latitude = stod(information[3]); city1.longitude = stod(information[4]); cityList.push_back(city1); line_serial++; } return cityList; } bool InputCity(const city **pt, const vector<city> &cityList) { string str; getline(cin, str); str = trim(str); if(end_judge(str)){ return false; } transform(str.begin(), str.end(), str.begin(), ::toupper); if (is_number(str) && !cityList.empty()) { int num = stoi(str); if (num < 0 || num >= choose_City.size()) { cout << "please enter a correct input" << endl; return true; } *pt = choose_City[num]; choose_City.clear(); return true; } if (str.size() < 3) { cout << "Too short, the City name at least 3 char." << endl; return true; } choose_City.clear(); for (auto city = cityList.begin(); city != cityList.end(); city++) { if (city->name.rfind(str, 0) == 0) { if (choose_City.size() == 1) { cout << "Those city is match, input integer to choose city" << endl; cout << "0. " << choose_City[0]->name << ", " << choose_City[0]->country << endl; cout << "1. " << city->name << ", " << city->country << endl; } else if (choose_City.size() > 1) { cout << choose_City.size() << ". " << city->name << ", " << city->country << endl; } choose_City.push_back(&*city); } } if (choose_City.size() >= 2) { return true; }else if (choose_City.size() == 0){ cout<<"NO CITY EXIST!"<<endl; return true; } *pt = choose_City[0]; return true; } double findDistance(const city &city1, const city &city2){ double ans =0; double phi1 = 90 - city1.latitude; double theta1 = city1.longitude; double phi2 = 90 - city2.latitude; double theta2 = city2.longitude; double c = sin(phi1*val)*sin(phi2*val)*cos((theta1-theta2)*val)+cos(phi1*val)*cos(phi2*val); ans = R * acos(c); return ans; }
30.07772
125
0.549699
Uncle-Road
7d53e8ed09ee0737c09b0d0b08b4f8b18c49fcf2
3,441
cpp
C++
test/src/test_enumeration.cpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
192
2016-09-29T17:10:07.000Z
2022-03-22T15:22:48.000Z
test/src/test_enumeration.cpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
35
2016-10-03T16:57:12.000Z
2021-09-28T13:11:15.000Z
test/src/test_enumeration.cpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
47
2016-09-29T08:21:32.000Z
2022-03-19T10:05:43.000Z
/* * Copyright (c) 2015-2016 Spotify AB * * 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 <string> #include <boost/test/unit_test.hpp> #include <spotify/json/codec/string.hpp> #include <spotify/json/codec/enumeration.hpp> #include <spotify/json/decode.hpp> #include <spotify/json/encode.hpp> #include <spotify/json/encode_exception.hpp> BOOST_AUTO_TEST_SUITE(spotify) BOOST_AUTO_TEST_SUITE(json) BOOST_AUTO_TEST_SUITE(codec) namespace { template <typename Codec> typename Codec::object_type test_decode(const Codec &codec, const std::string &json) { decode_context c(json.c_str(), json.c_str() + json.size()); auto obj = codec.decode(c); BOOST_CHECK_EQUAL(c.position, c.end); return obj; } template <typename Codec> void test_decode_fail(const Codec &codec, const std::string &json) { decode_context c(json.c_str(), json.c_str() + json.size()); BOOST_CHECK_THROW(codec.decode(c), decode_exception); } enum class Test { A, B }; } // namespace /* * Constructing */ BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct) { enumeration_t<Test, string_t> codec( string(), std::vector<std::pair<Test, std::string>>()); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_helper_with_codec) { enumeration<Test>(string(), { { Test::A, "A" } }); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_multiple_parameters_helper_with_codec) { enumeration<Test>(string(), { { Test::A, "A" }, { Test::B, "B" } }); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_helper) { enumeration<Test, std::string>({ { Test::A, "A" } }); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_multiple_parameters_helper) { enumeration<Test, std::string>({ { Test::A, "A" }, { Test::B, "B" } }); } /* * Decoding */ BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_decode) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" }, { Test::B, "B" } }); BOOST_CHECK(test_decode(codec, "\"A\"") == Test::A); BOOST_CHECK(test_decode(codec, "\"B\"") == Test::B); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_not_decode_invalid_value) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" } }); test_decode_fail(codec, "\"B\""); } /* * Encoding */ BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_encode) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" }, { Test::B, "B" } }); BOOST_CHECK_EQUAL(encode(codec, Test::A), "\"A\""); BOOST_CHECK_EQUAL(encode(codec, Test::B), "\"B\""); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_not_encode_missing_value) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" } }); BOOST_CHECK_THROW(encode(codec, Test::B), encode_exception); } BOOST_AUTO_TEST_SUITE_END() // codec BOOST_AUTO_TEST_SUITE_END() // json BOOST_AUTO_TEST_SUITE_END() // spotify
29.410256
106
0.718396
ivangalkin
7d56ac7349ed2b5615cc83a113f5172d15b50a05
7,431
cpp
C++
joystick/joystick_win32.cpp
matthew-macgregor/blitzplus_msvc2019
2a4b3b8b9f8e9b7ad2dc81bd80e08bb62c98bcdc
[ "Zlib" ]
69
2015-01-04T08:42:44.000Z
2022-03-13T09:56:24.000Z
joystick/joystick_win32.cpp
JamesLinus/blitzplus
a4615c064f99a70fdd131554b6f5e2241611aff9
[ "Zlib" ]
3
2016-09-24T04:13:55.000Z
2021-11-04T11:11:44.000Z
joystick/joystick_win32.cpp
JamesLinus/blitzplus
a4615c064f99a70fdd131554b6f5e2241611aff9
[ "Zlib" ]
29
2015-05-14T03:59:52.000Z
2020-07-25T02:46:25.000Z
#ifdef WIN32 #define WIN32_LEAN_AND_MEAN #define DIRECTINPUT_VERSION 0x500 #include <math.h> #include <dinput.h> #include <mmsystem.h> #include "joystick.h" static DIOBJECTDATAFORMAT c_rgodfDIJoystick[44] = { { &GUID_XAxis, 0, 0x80FFFF03, 256 },{ &GUID_YAxis, 4, 0x80FFFF03, 256 }, { &GUID_ZAxis, 8, 0x80FFFF03, 256 },{ &GUID_RxAxis, 12, 0x80FFFF03, 256 }, { &GUID_RyAxis, 16, 0x80FFFF03, 256 },{ &GUID_RzAxis, 20, 0x80FFFF03, 256 }, { &GUID_Slider, 24, 0x80FFFF03, 256 },{ &GUID_Slider, 28, 0x80FFFF03, 256 }, { &GUID_POV, 32, 0x80FFFF10, 0 },{ &GUID_POV, 36, 0x80FFFF10, 0 }, { &GUID_POV, 40, 0x80FFFF10, 0 },{ &GUID_POV, 44, 0x80FFFF10, 0 }, { NULL, 48, 0x80FFFF0C, 0 },{ NULL, 49, 0x80FFFF0C, 0 }, { NULL, 50, 0x80FFFF0C, 0 },{ NULL, 51, 0x80FFFF0C, 0 }, { NULL, 52, 0x80FFFF0C, 0 },{ NULL, 53, 0x80FFFF0C, 0 }, { NULL, 54, 0x80FFFF0C, 0 },{ NULL, 55, 0x80FFFF0C, 0 }, { NULL, 56, 0x80FFFF0C, 0 },{ NULL, 57, 0x80FFFF0C, 0 }, { NULL, 58, 0x80FFFF0C, 0 },{ NULL, 59, 0x80FFFF0C, 0 }, { NULL, 60, 0x80FFFF0C, 0 },{ NULL, 61, 0x80FFFF0C, 0 }, { NULL, 62, 0x80FFFF0C, 0 },{ NULL, 63, 0x80FFFF0C, 0 }, { NULL, 64, 0x80FFFF0C, 0 },{ NULL, 65, 0x80FFFF0C, 0 }, { NULL, 66, 0x80FFFF0C, 0 },{ NULL, 67, 0x80FFFF0C, 0 }, { NULL, 68, 0x80FFFF0C, 0 },{ NULL, 69, 0x80FFFF0C, 0 }, { NULL, 70, 0x80FFFF0C, 0 },{ NULL, 71, 0x80FFFF0C, 0 }, { NULL, 72, 0x80FFFF0C, 0 },{ NULL, 73, 0x80FFFF0C, 0 }, { NULL, 74, 0x80FFFF0C, 0 },{ NULL, 75, 0x80FFFF0C, 0 }, { NULL, 76, 0x80FFFF0C, 0 },{ NULL, 77, 0x80FFFF0C, 0 }, { NULL, 78, 0x80FFFF0C, 0 },{ NULL, 79, 0x80FFFF0C, 0 } }; const DIDATAFORMAT c_dfDIJoystick = { 24, 16, 0x1, 80, 44, c_rgodfDIJoystick }; static const int MAX_JOYS=32; typedef HRESULT(WINAPI*DICREATE)(HINSTANCE,DWORD,IDirectInput**,IUnknown*); struct Joystate{ IDirectInputDevice2 *dev; int type,mins[12],maxs[12]; float x,y,z,u,v,yaw,pitch,roll,hat; int hit[32]; char down[32]; }; static int _joys,_pollTime; static Joystate _states[MAX_JOYS]; static IDirectInput2 *_directInput; static void poll(){ if( !_joys ) return; int tm=timeGetTime(); if( tm-_pollTime<3 ) return; _pollTime=tm; for( int n=0;n<_joys;++n ){ Joystate *st=_states+n; IDirectInputDevice2 *dev=st->dev; if( dev->Poll()<0 ){ dev->Acquire(); if( dev->Poll()<0 ){ continue; } } DIJOYSTATE state; if( dev->GetDeviceState( sizeof(state),&state )<0 ) continue; st->x=(state.lX-st->mins[0])/(float)st->maxs[0]*2-1; st->y=(state.lY-st->mins[1])/(float)st->maxs[1]*2-1; st->z=(state.lZ-st->mins[2])/(float)st->maxs[2]*2-1; st->u=(state.rglSlider[0]-st->mins[6])/(float)st->maxs[6]*2-1; st->v=(state.rglSlider[1]-st->mins[7])/(float)st->maxs[7]*2-1; st->pitch=((state.lRx-st->mins[3])/(float)st->maxs[3]*2-1)*180; st->yaw=((state.lRy-st->mins[4])/(float)st->maxs[4]*2-1)*180; st->roll=((state.lRz-st->mins[5])/(float)st->maxs[5]*2-1)*180; if( (state.rgdwPOV[0]&0xffff)==0xffff ) st->hat=-1; else st->hat=(float)floor(state.rgdwPOV[0]/100.0f+.5f); for( int k=1;k<32;++k ){ bool down=!!( state.rgbButtons[(k-1)&15] & 0x80 ); if( down && !st->down[k] ) ++st->hit[k]; st->down[k]=down; } } } static BOOL CALLBACK enumJoystick( LPCDIDEVICEINSTANCE devinst,LPVOID pvRef ){ if( (devinst->dwDevType&0xff)!=DIDEVTYPE_JOYSTICK ) return DIENUM_CONTINUE; IDirectInputDevice *t_dev; if( _directInput->CreateDevice( devinst->guidInstance,&t_dev,0 )<0 ) return DIENUM_CONTINUE; IDirectInputDevice2 *dev; if( t_dev->QueryInterface( IID_IDirectInputDevice2,(void**)&dev )<0 ){ t_dev->Release();return DIENUM_CONTINUE; } t_dev->Release(); if( dev->SetCooperativeLevel( 0,DISCL_BACKGROUND|DISCL_NONEXCLUSIVE )>=0 ){ if( dev->SetDataFormat( &c_dfDIJoystick )>=0 ){ Joystate *st=_states+_joys; st->dev=dev; st->type=((devinst->dwDevType>>8)&0xff)==DIDEVTYPEJOYSTICK_GAMEPAD ? 1 : 2; for( int k=0;k<12;++k ){ //initialize joystick axis ranges (d'oh!) DIPROPRANGE range; range.diph.dwSize=sizeof(DIPROPRANGE); range.diph.dwHeaderSize=sizeof(DIPROPHEADER); range.diph.dwObj=k*4+12; range.diph.dwHow=DIPH_BYOFFSET; if( dev->GetProperty( DIPROP_RANGE,&range.diph )<0 ){ st->mins[k]=0; st->maxs[k]=65535; continue; } st->mins[k]=range.lMin; st->maxs[k]=range.lMax-range.lMin; } ++_joys; return _joys<MAX_JOYS ? DIENUM_CONTINUE : DIENUM_STOP; } } dev->Release(); return DIENUM_CONTINUE; } static int dir( float n ){ return n<(-1.0f/3.0f) ? -1 : (n>(1.0f/3.0f) ? 1 : 0); } int bbJoyType( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].type; } int bbJoyDown( int n,int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].down[n&31]; } int bbJoyHit( int n,int port ){ if( port<0 || port>=_joys ) return 0; poll(); int t=_states[port].hit[n&31]; _states[port].hit[n&31]=0; return t; } float bbJoyX( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].x; } float bbJoyY( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].y; } float bbJoyZ( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].z; } float bbJoyU( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].u; } float bbJoyV( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].v; } float bbJoyPitch( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].pitch; } float bbJoyYaw( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].yaw; } float bbJoyRoll( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return _states[port].roll; } int bbJoyHat( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return (int)_states[port].hat; } int bbJoyXDir( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return dir( _states[port].x ); } int bbJoyYDir( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return dir( _states[port].y ); } int bbJoyZDir( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return dir( _states[port].z ); } int bbJoyUDir( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return dir( _states[port].u ); } int bbJoyVDir( int port ){ if( port<0 || port>=_joys ) return 0; poll(); return dir( _states[port].v ); } void bbFlushJoy(){ if( !_joys ) return; poll(); for( int k=0;k<_joys;++k ){ Joystate *st=_states+k; memset( st->hit,0,sizeof(st->hit) ); memset( st->down,0,sizeof(st->down) ); } } class Win32Joystick : public BBModule{ HMODULE _module; public: Win32Joystick(){ reg( "Win32Joystick" ); } bool startup(){ _joys=0; _module=0; _directInput=0; memset( &_states,0,sizeof(_states) ); if( _module=LoadLibrary( "dinput.dll" ) ){ if( DICREATE create=(DICREATE)GetProcAddress( _module,"DirectInputCreateA" ) ){ IDirectInput *di; if( create( GetModuleHandle(0),DIRECTINPUT_VERSION,&di,0 )>=0 ){ if( di->QueryInterface( IID_IDirectInput2,(void**)&_directInput )>=0 ){ di->Release(); _directInput->EnumDevices( DIDEVTYPE_JOYSTICK,enumJoystick,0,DIEDFL_ATTACHEDONLY ); return true; } di->Release(); } } FreeLibrary( _module ); } return true; } void shutdown(){ if( !_joys ) return; FreeLibrary( _module ); } }win32Joystick; #endif
24.852843
93
0.635312
matthew-macgregor
7d56b7d969c5a80e6d5fe9afed169823d3ea9511
51,719
cpp
C++
ESMF/src/Infrastructure/Mesh/src/Moab/io/NCHelper.cpp
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
1
2018-07-05T16:48:58.000Z
2018-07-05T16:48:58.000Z
ESMF/src/Infrastructure/Mesh/src/Moab/io/NCHelper.cpp
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
1
2022-03-04T16:12:02.000Z
2022-03-04T16:12:02.000Z
ESMF/src/Infrastructure/Mesh/src/Moab/io/NCHelper.cpp
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
null
null
null
#include "NCHelper.hpp" #include "NCHelperEuler.hpp" #include "NCHelperFV.hpp" #include "NCHelperHOMME.hpp" #include "NCHelperMPAS.hpp" #include "NCHelperGCRM.hpp" #include <sstream> #include "MBTagConventions.hpp" #ifdef WIN32 #ifdef size_t #undef size_t #endif #endif namespace moab { NCHelper* NCHelper::get_nc_helper(ReadNC* readNC, int fileId, const FileOptions& opts, EntityHandle fileSet) { // Check if CF convention is being followed bool is_CF = false; std::map<std::string, ReadNC::AttData>& globalAtts = readNC->globalAtts; std::map<std::string, ReadNC::AttData>::iterator attIt = globalAtts.find("conventions"); if (attIt == globalAtts.end()) attIt = globalAtts.find("Conventions"); if (attIt != globalAtts.end()) { unsigned int sz = attIt->second.attLen; std::string att_data; att_data.resize(sz + 1); att_data[sz] = '\000'; int success = NCFUNC(get_att_text)(fileId, attIt->second.attVarId, attIt->second.attName.c_str(), &att_data[0]); if (0 == success && att_data.find("CF") != std::string::npos) is_CF = true; } if (is_CF) { if (NCHelperEuler::can_read_file(readNC, fileId)) return new (std::nothrow) NCHelperEuler(readNC, fileId, opts, fileSet); else if (NCHelperFV::can_read_file(readNC, fileId)) return new (std::nothrow) NCHelperFV(readNC, fileId, opts, fileSet); else if (NCHelperHOMME::can_read_file(readNC, fileId)) return new (std::nothrow) NCHelperHOMME(readNC, fileId, opts, fileSet); } else { if (NCHelperMPAS::can_read_file(readNC)) return new (std::nothrow) NCHelperMPAS(readNC, fileId, opts, fileSet); // For a HOMME connectivity file, there might be no CF convention else if (NCHelperHOMME::can_read_file(readNC, fileId)) return new (std::nothrow) NCHelperHOMME(readNC, fileId, opts, fileSet); // gcrm reader else if (NCHelperGCRM::can_read_file(readNC)) return new (std::nothrow) NCHelperGCRM(readNC, fileId, opts, fileSet); } // Unknown NetCDF grid (will fill this in later for POP, CICE and CLM) return NULL; } ErrorCode NCHelper::create_conventional_tags(const std::vector<int>& tstep_nums) { Interface*& mbImpl = _readNC->mbImpl; std::vector<std::string>& dimNames = _readNC->dimNames; std::vector<int>& dimLens = _readNC->dimLens; std::map<std::string, ReadNC::AttData>& globalAtts = _readNC->globalAtts; std::map<std::string, ReadNC::VarData>& varInfo = _readNC->varInfo; DebugOutput& dbgOut = _readNC->dbgOut; int& partMethod = _readNC->partMethod; ScdInterface* scdi = _readNC->scdi; ErrorCode rval; std::string tag_name; // <__NUM_DIMS> Tag numDimsTag = 0; tag_name = "__NUM_DIMS"; int numDims = dimNames.size(); rval = mbImpl->tag_get_handle(tag_name.c_str(), 1, MB_TYPE_INTEGER, numDimsTag, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(numDimsTag, &_fileSet, 1, &numDims);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__NUM_VARS> Tag numVarsTag = 0; tag_name = "__NUM_VARS"; int numVars = varInfo.size(); rval = mbImpl->tag_get_handle(tag_name.c_str(), 1, MB_TYPE_INTEGER, numVarsTag, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(numVarsTag, &_fileSet, 1, &numVars);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__DIM_NAMES> Tag dimNamesTag = 0; tag_name = "__DIM_NAMES"; std::string dimnames; unsigned int dimNamesSz = dimNames.size(); for (unsigned int i = 0; i != dimNamesSz; i++) { dimnames.append(dimNames[i]); dimnames.push_back('\0'); } int dimnamesSz = dimnames.size(); rval = mbImpl->tag_get_handle(tag_name.c_str(), 0, MB_TYPE_OPAQUE, dimNamesTag, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); const void* ptr = dimnames.c_str(); rval = mbImpl->tag_set_by_ptr(dimNamesTag, &_fileSet, 1, &ptr, &dimnamesSz);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__DIM_LENS> Tag dimLensTag = 0; tag_name = "__DIM_LENS"; int dimLensSz = dimLens.size(); rval = mbImpl->tag_get_handle(tag_name.c_str(), 0, MB_TYPE_INTEGER, dimLensTag, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); ptr = &(dimLens[0]); rval = mbImpl->tag_set_by_ptr(dimLensTag, &_fileSet, 1, &ptr, &dimLensSz);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__VAR_NAMES> Tag varNamesTag = 0; tag_name = "__VAR_NAMES"; std::string varnames; std::map<std::string, ReadNC::VarData>::iterator mapIter; for (mapIter = varInfo.begin(); mapIter != varInfo.end(); ++mapIter) { varnames.append(mapIter->first); varnames.push_back('\0'); } int varnamesSz = varnames.size(); rval = mbImpl->tag_get_handle(tag_name.c_str(), 0, MB_TYPE_OPAQUE, varNamesTag, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); ptr = varnames.c_str(); rval = mbImpl->tag_set_by_ptr(varNamesTag, &_fileSet, 1, &ptr, &varnamesSz);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // __<dim_name>_LOC_MINMAX (for time) for (unsigned int i = 0; i != dimNamesSz; i++) { if (dimNames[i] == "time" || dimNames[i] == "Time" || dimNames[i] == "t") { // some files might have Time dimension as 0, it will not appear in any // variables, so skip it if (nTimeSteps==0) continue; std::stringstream ss_tag_name; ss_tag_name << "__" << dimNames[i] << "_LOC_MINMAX"; tag_name = ss_tag_name.str(); Tag tagh = 0; std::vector<int> val(2, 0); val[0] = 0; val[1] = nTimeSteps - 1; rval = mbImpl->tag_get_handle(tag_name.c_str(), 2, MB_TYPE_INTEGER, tagh, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(tagh, &_fileSet, 1, &val[0]);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); } } // __<dim_name>_LOC_VALS (for time) for (unsigned int i = 0; i != dimNamesSz; i++) { if (dimNames[i] == "time" || dimNames[i] == "Time" || dimNames[i] == "t") { std::vector<int> val; if (!tstep_nums.empty()) val = tstep_nums; else { // some files might have Time dimension as 0, it will not appear in any // variables, so skip it if (tVals.empty()) continue; val.resize(tVals.size()); for (unsigned int j = 0; j != tVals.size(); j++) val[j] = j; } Tag tagh = 0; std::stringstream ss_tag_name; ss_tag_name << "__" << dimNames[i] << "_LOC_VALS"; tag_name = ss_tag_name.str(); rval = mbImpl->tag_get_handle(tag_name.c_str(), val.size(), MB_TYPE_INTEGER, tagh, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(tagh, &_fileSet, 1, &val[0]);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); } } // __<var_name>_DIMS for (mapIter = varInfo.begin(); mapIter != varInfo.end(); ++mapIter) { Tag varNamesDimsTag = 0; std::stringstream ss_tag_name; ss_tag_name << "__" << mapIter->first << "_DIMS"; tag_name = ss_tag_name.str(); unsigned int varDimSz = varInfo[mapIter->first].varDims.size(); if (varDimSz == 0) continue; std::vector<Tag> varDimTags(varDimSz); for (unsigned int i = 0; i != varDimSz; i++) { Tag tmptag = 0; std::string tmptagname = dimNames[varInfo[mapIter->first].varDims[i]]; rval = mbImpl->tag_get_handle(tmptagname.c_str(), 0, MB_TYPE_OPAQUE, tmptag, MB_TAG_ANY);MB_CHK_SET_ERR(rval, "Trouble getting tag " << tmptagname); varDimTags[i] = tmptag; } // rval = mbImpl->tag_get_handle(tag_name.c_str(), varDimSz, MB_TYPE_HANDLE, varNamesDimsTag, MB_TAG_SPARSE | MB_TAG_CREAT); // We should not use MB_TYPE_HANDLE for Tag here. Tag is a pointer, which is 4 bytes on 32 bit machines and 8 bytes on 64 bit machines. // Normally, entity handle is 8 bytes on 64 bit machines, but it can also be configured to 4 bytes. rval = mbImpl->tag_get_handle(tag_name.c_str(), varDimSz*sizeof(Tag), MB_TYPE_OPAQUE, varNamesDimsTag, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(varNamesDimsTag, &_fileSet, 1, &(varDimTags[0]));MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); } // <PARTITION_METHOD> Tag part_tag = scdi->part_method_tag(); if (!part_tag) MB_SET_ERR(MB_FAILURE, "Trouble getting PARTITION_METHOD tag"); rval = mbImpl->tag_set_data(part_tag, &_fileSet, 1, &partMethod);MB_CHK_SET_ERR(rval, "Trouble setting data to PARTITION_METHOD tag"); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__GLOBAL_ATTRIBS> tag_name = "__GLOBAL_ATTRIBS"; Tag globalAttTag = 0; rval = mbImpl->tag_get_handle(tag_name.c_str(), 0, MB_TYPE_OPAQUE, globalAttTag, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); std::string gattVal; std::vector<int> gattLen; rval = create_attrib_string(globalAtts, gattVal, gattLen);MB_CHK_SET_ERR(rval, "Trouble creating global attribute string"); const void* gattptr = gattVal.c_str(); int globalAttSz = gattVal.size(); rval = mbImpl->tag_set_by_ptr(globalAttTag, &_fileSet, 1, &gattptr, &globalAttSz);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__GLOBAL_ATTRIBS_LEN> tag_name = "__GLOBAL_ATTRIBS_LEN"; Tag globalAttLenTag = 0; if (gattLen.size() == 0) gattLen.push_back(0); rval = mbImpl->tag_get_handle(tag_name.c_str(), gattLen.size(), MB_TYPE_INTEGER, globalAttLenTag, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(globalAttLenTag, &_fileSet, 1, &gattLen[0]);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // __<var_name>_ATTRIBS and __<var_name>_ATTRIBS_LEN for (mapIter = varInfo.begin(); mapIter != varInfo.end(); ++mapIter) { std::stringstream ssTagName; ssTagName << "__" << mapIter->first << "_ATTRIBS"; tag_name = ssTagName.str(); Tag varAttTag = 0; rval = mbImpl->tag_get_handle(tag_name.c_str(), 0, MB_TYPE_OPAQUE, varAttTag, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); std::string varAttVal; std::vector<int> varAttLen; if (mapIter->second.numAtts < 1) { if (dummyVarNames.find(mapIter->first) != dummyVarNames.end()) { // This variable is a dummy coordinate variable varAttVal = "DUMMY_VAR"; } else { // This variable has no attributes varAttVal = "NO_ATTRIBS"; } } else { rval = create_attrib_string(mapIter->second.varAtts, varAttVal, varAttLen);MB_CHK_SET_ERR(rval, "Trouble creating attribute string for variable " << mapIter->first); } const void* varAttPtr = varAttVal.c_str(); int varAttSz = varAttVal.size(); if (0 == varAttSz) varAttSz = 1; rval = mbImpl->tag_set_by_ptr(varAttTag, &_fileSet, 1, &varAttPtr, &varAttSz);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); ssTagName << "_LEN"; tag_name = ssTagName.str(); Tag varAttLenTag = 0; if (0 == varAttLen.size()) varAttLen.push_back(0); rval = mbImpl->tag_get_handle(tag_name.c_str(), varAttLen.size(), MB_TYPE_INTEGER, varAttLenTag, MB_TAG_SPARSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); rval = mbImpl->tag_set_data(varAttLenTag, &_fileSet, 1, &varAttLen[0]);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); } // <__VAR_NAMES_LOCATIONS> tag_name = "__VAR_NAMES_LOCATIONS"; Tag varNamesLocsTag = 0; std::vector<int> varNamesLocs(varInfo.size()); rval = mbImpl->tag_get_handle(tag_name.c_str(), varNamesLocs.size(), MB_TYPE_INTEGER, varNamesLocsTag, MB_TAG_CREAT | MB_TAG_SPARSE);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); for (mapIter = varInfo.begin(); mapIter != varInfo.end(); ++mapIter) { varNamesLocs[std::distance(varInfo.begin(), mapIter)] = mapIter->second.entLoc; } rval = mbImpl->tag_set_data(varNamesLocsTag, &_fileSet, 1, &varNamesLocs[0]);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); // <__MESH_TYPE> Tag meshTypeTag = 0; tag_name = "__MESH_TYPE"; std::string meshTypeName = get_mesh_type_name(); rval = mbImpl->tag_get_handle(tag_name.c_str(), 0, MB_TYPE_OPAQUE, meshTypeTag, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating conventional tag " << tag_name); ptr = meshTypeName.c_str(); int leng = meshTypeName.size(); rval = mbImpl->tag_set_by_ptr(meshTypeTag, &_fileSet, 1, &ptr, &leng);MB_CHK_SET_ERR(rval, "Trouble setting data to conventional tag " << tag_name); dbgOut.tprintf(2, "Conventional tag %s created\n", tag_name.c_str()); return MB_SUCCESS; } ErrorCode NCHelper::update_time_tag_vals() { Interface*& mbImpl = _readNC->mbImpl; std::vector<std::string>& dimNames = _readNC->dimNames; ErrorCode rval; // The time tag might be a dummy one (e.g. 'Time' for MPAS) std::string time_tag_name = dimNames[tDim]; if (dummyVarNames.find(time_tag_name) != dummyVarNames.end()) return MB_SUCCESS; Tag time_tag = 0; const void* data = NULL; int time_tag_size = 0; rval = mbImpl->tag_get_handle(time_tag_name.c_str(), 0, MB_TYPE_DOUBLE, time_tag, MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble getting tag " << time_tag_name); rval = mbImpl->tag_get_by_ptr(time_tag, &_fileSet, 1, &data, &time_tag_size);MB_CHK_SET_ERR(rval, "Trouble getting data of tag " << time_tag_name); const double* time_tag_vals = static_cast<const double*>(data); // Merge tVals (read from current file) to existing time tag // Assume that time_tag_vals and tVals are both sorted std::vector<double> merged_time_vals; merged_time_vals.reserve(time_tag_size + nTimeSteps); int i = 0; int j = 0; // Merge time values from time_tag_vals and tVals while (i < time_tag_size && j < nTimeSteps) { if (time_tag_vals[i] < tVals[j]) merged_time_vals.push_back(time_tag_vals[i++]); else merged_time_vals.push_back(tVals[j++]); } // Append remaining time values of time_tag_vals (if any) while (i < time_tag_size) merged_time_vals.push_back(time_tag_vals[i++]); // Append remaining time values of tVals (if any) while (j < nTimeSteps) merged_time_vals.push_back(tVals[j++]); data = &merged_time_vals[0]; time_tag_size = merged_time_vals.size(); rval = mbImpl->tag_set_by_ptr(time_tag, &_fileSet, 1, &data, &time_tag_size);MB_CHK_SET_ERR(rval, "Trouble setting data to tag " << time_tag_name); return MB_SUCCESS; } ErrorCode NCHelper::read_variables_setup(std::vector<std::string>& var_names, std::vector<int>& tstep_nums, std::vector<ReadNC::VarData>& vdatas, std::vector<ReadNC::VarData>& vsetdatas) { std::map<std::string, ReadNC::VarData>& varInfo = _readNC->varInfo; std::vector<std::string>& dimNames = _readNC->dimNames; std::map<std::string, ReadNC::VarData>::iterator mit; // If empty read them all (except ignored variables) if (var_names.empty()) { for (mit = varInfo.begin(); mit != varInfo.end(); ++mit) { ReadNC::VarData vd = (*mit).second; // If read all variables at once, skip ignored ones if (ignoredVarNames.find(vd.varName) != ignoredVarNames.end()) continue; // Coordinate variables (include dummy ones) were read to the file set by default if (std::find(dimNames.begin(), dimNames.end(), vd.varName) != dimNames.end()) continue; if (vd.entLoc == ReadNC::ENTLOCSET) vsetdatas.push_back(vd); else vdatas.push_back(vd); } } else { // Read specified variables (might include ignored ones) for (unsigned int i = 0; i < var_names.size(); i++) { mit = varInfo.find(var_names[i]); if (mit != varInfo.end()) { ReadNC::VarData vd = (*mit).second; // Upon creation of dummy coordinate variables, tag values have already been set if (dummyVarNames.find(vd.varName) != dummyVarNames.end()) continue; if (vd.entLoc == ReadNC::ENTLOCSET) vsetdatas.push_back(vd); else vdatas.push_back(vd); } else { MB_SET_ERR(MB_FAILURE, "Couldn't find specified variable " << var_names[i]); } } } if (tstep_nums.empty() && nTimeSteps > 0) { // No timesteps input, get them all for (int i = 0; i < nTimeSteps; i++) tstep_nums.push_back(i); } if (!tstep_nums.empty()) { for (unsigned int i = 0; i < vdatas.size(); i++) { vdatas[i].varTags.resize(tstep_nums.size(), 0); vdatas[i].varDatas.resize(tstep_nums.size()); // NC reader assumes that non-set variables always have timesteps assert(std::find(vdatas[i].varDims.begin(), vdatas[i].varDims.end(), tDim) != vdatas[i].varDims.end()); vdatas[i].has_tsteps = true; } for (unsigned int i = 0; i < vsetdatas.size(); i++) { if ((std::find(vsetdatas[i].varDims.begin(), vsetdatas[i].varDims.end(), tDim) != vsetdatas[i].varDims.end()) && (vsetdatas[i].varName != dimNames[tDim])) { // Set variables with timesteps: e.g. xtime(Time) or xtime(Time, StrLen) vsetdatas[i].varTags.resize(tstep_nums.size(), 0); vsetdatas[i].varDatas.resize(tstep_nums.size()); vsetdatas[i].has_tsteps = true; } else { // Set variables without timesteps: no time dimension, or time itself vsetdatas[i].varTags.resize(1, 0); vsetdatas[i].varDatas.resize(1); vsetdatas[i].has_tsteps = false; } } } return MB_SUCCESS; } ErrorCode NCHelper::read_variables_to_set(std::vector<ReadNC::VarData>& vdatas, std::vector<int>& tstep_nums) { Interface*& mbImpl = _readNC->mbImpl; DebugOutput& dbgOut = _readNC->dbgOut; ErrorCode rval = read_variables_to_set_allocate(vdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble allocating space to read set variables"); // Finally, read into that space int success; for (unsigned int i = 0; i < vdatas.size(); i++) { // Note, for set variables without timesteps, loop one time and then break for (unsigned int t = 0; t < tstep_nums.size(); t++) { void* data = vdatas[i].varDatas[t]; // Set variables with timesteps, e.g. xtime(Time) or xtime(Time, StrLen) if (vdatas[i].has_tsteps) { // Set readStart for each timestep along time dimension vdatas[i].readStarts[0] = tstep_nums[t]; } switch (vdatas[i].varDataType) { case NC_BYTE: case NC_CHAR: success = NCFUNCAG(_vara_text)(_fileId, vdatas[i].varId, &vdatas[i].readStarts[0], &vdatas[i].readCounts[0], (char*) data); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read byte/char data for variable " << vdatas[i].varName); break; case NC_SHORT: case NC_INT: success = NCFUNCAG(_vara_int)(_fileId, vdatas[i].varId, &vdatas[i].readStarts[0], &vdatas[i].readCounts[0], (int*) data); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read short/int data for variable " << vdatas[i].varName); break; case NC_FLOAT: case NC_DOUBLE: success = NCFUNCAG(_vara_double)(_fileId, vdatas[i].varId, &vdatas[i].readStarts[0], &vdatas[i].readCounts[0], (double*) data); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read float/double data for variable " << vdatas[i].varName); break; default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for variable " << vdatas[i].varName); } dbgOut.tprintf(2, "Setting data for variable %s, time step %d\n", vdatas[i].varName.c_str(), tstep_nums[t]); rval = mbImpl->tag_set_by_ptr(vdatas[i].varTags[t], &_fileSet, 1, &data, &vdatas[i].sz);MB_CHK_SET_ERR(rval, "Trouble setting tag data for variable " << vdatas[i].varName); // Memory pointed by pointer data can be deleted, as tag_set_by_ptr() has already copied the tag values switch (vdatas[i].varDataType) { case NC_BYTE: case NC_CHAR: delete[] (char*) data; break; case NC_SHORT: case NC_INT: delete[] (int*) data; break; case NC_FLOAT: case NC_DOUBLE: delete[] (double*) data; break; default: break; } vdatas[i].varDatas[t] = NULL; // Loop continues only for set variables with timesteps, e.g. xtime(Time) or xtime(Time, StrLen) if (!vdatas[i].has_tsteps) break; } } // Debug output, if requested if (1 == dbgOut.get_verbosity()) { dbgOut.printf(1, "Read variables: %s", vdatas.begin()->varName.c_str()); for (unsigned int i = 1; i < vdatas.size(); i++) dbgOut.printf(1, ", %s ", vdatas[i].varName.c_str()); dbgOut.tprintf(1, "\n"); } return rval; } ErrorCode NCHelper::read_coordinate(const char* var_name, int lmin, int lmax, std::vector<double>& cvals) { std::map<std::string, ReadNC::VarData>& varInfo = _readNC->varInfo; std::map<std::string, ReadNC::VarData>::iterator vmit = varInfo.find(var_name); if (varInfo.end() == vmit) MB_SET_ERR(MB_FAILURE, "Couldn't find variable " << var_name); assert(lmin >= 0 && lmax >= lmin); NCDF_SIZE tstart = lmin; NCDF_SIZE tcount = lmax - lmin + 1; NCDF_DIFF dum_stride = 1; int success; // Check size if ((std::size_t)tcount != cvals.size()) cvals.resize(tcount); // Check to make sure it's a float or double switch ((*vmit).second.varDataType) { case NC_FLOAT: case NC_DOUBLE: // Read float as double success = NCFUNCAG(_vars_double)(_fileId, (*vmit).second.varId, &tstart, &tcount, &dum_stride, &cvals[0]); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read float/double data for variable " << var_name); break; default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for variable " << var_name); } return MB_SUCCESS; } ErrorCode NCHelper::get_tag_to_set(ReadNC::VarData& var_data, int tstep_num, Tag& tagh) { Interface*& mbImpl = _readNC->mbImpl; DebugOutput& dbgOut = _readNC->dbgOut; int& tStepBase = _readNC->tStepBase; if (tStepBase > 0) tstep_num += tStepBase; std::ostringstream tag_name; if (var_data.has_tsteps) tag_name << var_data.varName << tstep_num; else tag_name << var_data.varName; ErrorCode rval = MB_SUCCESS; tagh = 0; switch (var_data.varDataType) { case NC_BYTE: case NC_CHAR: rval = mbImpl->tag_get_handle(tag_name.str().c_str(), 0, MB_TYPE_OPAQUE, tagh, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating tag " << tag_name.str()); break; case NC_SHORT: case NC_INT: rval = mbImpl->tag_get_handle(tag_name.str().c_str(), 0, MB_TYPE_INTEGER, tagh, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating tag " << tag_name.str()); break; case NC_FLOAT: case NC_DOUBLE: rval = mbImpl->tag_get_handle(tag_name.str().c_str(), 0, MB_TYPE_DOUBLE, tagh, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating tag " << tag_name.str()); break; default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for variable " << var_data.varName); } dbgOut.tprintf(2, "Tag %s created\n", tag_name.str().c_str()); return rval; } ErrorCode NCHelper::get_tag_to_nonset(ReadNC::VarData& var_data, int tstep_num, Tag& tagh, int num_lev) { Interface*& mbImpl = _readNC->mbImpl; DebugOutput& dbgOut = _readNC->dbgOut; int& tStepBase = _readNC->tStepBase; if (tStepBase > 0) tstep_num += tStepBase; std::ostringstream tag_name; tag_name << var_data.varName << tstep_num; ErrorCode rval = MB_SUCCESS; tagh = 0; switch (var_data.varDataType) { case NC_BYTE: case NC_CHAR: rval = mbImpl->tag_get_handle(tag_name.str().c_str(), num_lev, MB_TYPE_OPAQUE, tagh, MB_TAG_DENSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating tag " << tag_name.str()); break; case NC_SHORT: case NC_INT: rval = mbImpl->tag_get_handle(tag_name.str().c_str(), num_lev, MB_TYPE_INTEGER, tagh, MB_TAG_DENSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating tag " << tag_name.str()); break; case NC_FLOAT: case NC_DOUBLE: rval = mbImpl->tag_get_handle(tag_name.str().c_str(), num_lev, MB_TYPE_DOUBLE, tagh, MB_TAG_DENSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating tag " << tag_name.str()); break; default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for variable " << var_data.varName); } dbgOut.tprintf(2, "Tag %s created\n", tag_name.str().c_str()); return rval; } ErrorCode NCHelper::create_attrib_string(const std::map<std::string, ReadNC::AttData>& attMap, std::string& attVal, std::vector<int>& attLen) { int success; std::stringstream ssAtt; unsigned int sz = 0; std::map<std::string, ReadNC::AttData>::const_iterator attIt = attMap.begin(); for (; attIt != attMap.end(); ++attIt) { ssAtt << attIt->second.attName; ssAtt << '\0'; void* attData = NULL; switch (attIt->second.attDataType) { case NC_BYTE: case NC_CHAR: sz = attIt->second.attLen; attData = (char *) malloc(sz); success = NCFUNC(get_att_text)(_fileId, attIt->second.attVarId, attIt->second.attName.c_str(), (char*) attData); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read byte/char data for attribute " << attIt->second.attName); ssAtt << "char;"; break; case NC_SHORT: sz = attIt->second.attLen * sizeof(short); attData = (short *) malloc(sz); success = NCFUNC(get_att_short)(_fileId, attIt->second.attVarId, attIt->second.attName.c_str(), (short*) attData); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read short data for attribute " << attIt->second.attName); ssAtt << "short;"; break; case NC_INT: sz = attIt->second.attLen * sizeof(int); attData = (int *) malloc(sz); success = NCFUNC(get_att_int)(_fileId, attIt->second.attVarId, attIt->second.attName.c_str(), (int*) attData); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read int data for attribute " << attIt->second.attName); ssAtt << "int;"; break; case NC_FLOAT: sz = attIt->second.attLen * sizeof(float); attData = (float *) malloc(sz); success = NCFUNC(get_att_float)(_fileId, attIt->second.attVarId, attIt->second.attName.c_str(), (float*) attData); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read float data for attribute " << attIt->second.attName); ssAtt << "float;"; break; case NC_DOUBLE: sz = attIt->second.attLen * sizeof(double); attData = (double *) malloc(sz); success = NCFUNC(get_att_double)(_fileId, attIt->second.attVarId, attIt->second.attName.c_str(), (double*) attData); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read double data for attribute " << attIt->second.attName); ssAtt << "double;"; break; default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for attribute " << attIt->second.attName); } char* tmpc = (char *) attData; for (unsigned int counter = 0; counter != sz; ++counter) ssAtt << tmpc[counter]; free(attData); ssAtt << ';'; attLen.push_back(ssAtt.str().size() - 1); } attVal = ssAtt.str(); return MB_SUCCESS; } ErrorCode NCHelper::create_dummy_variables() { Interface*& mbImpl = _readNC->mbImpl; std::vector<std::string>& dimNames = _readNC->dimNames; std::vector<int>& dimLens = _readNC->dimLens; std::map<std::string, ReadNC::VarData>& varInfo = _readNC->varInfo; DebugOutput& dbgOut = _readNC->dbgOut; // Hack: look at all dimensions, and see if we have one that does not appear in the list of varInfo names // Right now, candidates are from unstructured meshes, such as ncol (HOMME) and nCells (MPAS) // For each of them, create a dummy coordinate variable with a sparse tag to store the dimension length for (unsigned int i = 0; i < dimNames.size(); i++) { // If there is a variable with this dimension name, skip if (varInfo.find(dimNames[i]) != varInfo.end()) continue; // Create a dummy coordinate variable int sizeTotalVar = varInfo.size(); std::string var_name(dimNames[i]); ReadNC::VarData& data = varInfo[var_name]; data.varName = var_name; data.varId = sizeTotalVar; data.varTags.resize(1, 0); data.varDataType = NC_INT; data.varDims.resize(1); data.varDims[0] = (int)i; data.numAtts = 0; data.entLoc = ReadNC::ENTLOCSET; dummyVarNames.insert(var_name); dbgOut.tprintf(2, "Dummy coordinate variable created for dimension %s\n", var_name.c_str()); // Create a corresponding sparse tag Tag tagh; ErrorCode rval = mbImpl->tag_get_handle(var_name.c_str(), 0, MB_TYPE_INTEGER, tagh, MB_TAG_CREAT | MB_TAG_SPARSE | MB_TAG_VARLEN);MB_CHK_SET_ERR(rval, "Trouble creating tag for dummy coordinate variable " << var_name); // Tag value is the dimension length const void* ptr = &dimLens[i]; // Tag size is 1 int size = 1; rval = mbImpl->tag_set_by_ptr(tagh, &_fileSet, 1, &ptr, &size);MB_CHK_SET_ERR(rval, "Trouble setting tag data for dummy coordinate variable " << var_name); dbgOut.tprintf(2, "Sparse tag created for dimension %s\n", var_name.c_str()); } return MB_SUCCESS; } ErrorCode NCHelper::read_variables_to_set_allocate(std::vector<ReadNC::VarData>& vdatas, std::vector<int>& tstep_nums) { std::vector<int>& dimLens = _readNC->dimLens; DebugOutput& dbgOut = _readNC->dbgOut; ErrorCode rval = MB_SUCCESS; for (unsigned int i = 0; i < vdatas.size(); i++) { // Set up readStarts and readCounts if (vdatas[i].has_tsteps) { // First: time vdatas[i].readStarts.push_back(0); // This value is timestep dependent, will be set later vdatas[i].readCounts.push_back(1); // Next: other dimensions for (unsigned int idx = 1; idx != vdatas[i].varDims.size(); idx++) { vdatas[i].readStarts.push_back(0); vdatas[i].readCounts.push_back(dimLens[vdatas[i].varDims[idx]]); } } else { if (vdatas[i].varDims.empty()) { // Scalar variable vdatas[i].readStarts.push_back(0); vdatas[i].readCounts.push_back(1); } else { for (unsigned int idx = 0; idx != vdatas[i].varDims.size(); idx++) { vdatas[i].readStarts.push_back(0); vdatas[i].readCounts.push_back(dimLens[vdatas[i].varDims[idx]]); } } } // Get variable size vdatas[i].sz = 1; for (std::size_t idx = 0; idx != vdatas[i].readCounts.size(); idx++) vdatas[i].sz *= vdatas[i].readCounts[idx]; // Note, for set variables without timesteps, loop one time and then break for (unsigned int t = 0; t < tstep_nums.size(); t++) { dbgOut.tprintf(2, "Reading variable %s, time step %d\n", vdatas[i].varName.c_str(), tstep_nums[t]); if (tstep_nums[t] >= dimLens[tDim]) { MB_SET_ERR(MB_INDEX_OUT_OF_RANGE, "Wrong value for timestep number " << tstep_nums[t]); } // Get the tag to read into if (!vdatas[i].varTags[t]) { rval = get_tag_to_set(vdatas[i], tstep_nums[t], vdatas[i].varTags[t]);MB_CHK_SET_ERR(rval, "Trouble getting tag to set variable " << vdatas[i].varName); } switch (vdatas[i].varDataType) { case NC_BYTE: case NC_CHAR: vdatas[i].varDatas[t] = new char[vdatas[i].sz]; break; case NC_SHORT: case NC_INT: vdatas[i].varDatas[t] = new int[vdatas[i].sz]; break; case NC_FLOAT: case NC_DOUBLE: vdatas[i].varDatas[t] = new double[vdatas[i].sz]; break; default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for variable " << vdatas[i].varName); } // Loop continues only for set variables with timesteps, e.g. xtime(Time) or xtime(Time, StrLen) if (!vdatas[i].has_tsteps) break; } } return rval; } ErrorCode ScdNCHelper::check_existing_mesh() { Interface*& mbImpl = _readNC->mbImpl; // Get the number of vertices int num_verts; ErrorCode rval = mbImpl->get_number_entities_by_dimension(_fileSet, 0, num_verts);MB_CHK_SET_ERR(rval, "Trouble getting number of vertices"); /* // Check against parameters // When ghosting is used, this check might fail (to be updated later) if (num_verts > 0) { int expected_verts = (lDims[3] - lDims[0] + 1) * (lDims[4] - lDims[1] + 1) * (-1 == lDims[2] ? 1 : lDims[5] - lDims[2] + 1); if (num_verts != expected_verts) { MB_SET_ERR(MB_FAILURE, "Number of vertices doesn't match"); } } */ // Check the number of elements too int num_elems; rval = mbImpl->get_number_entities_by_dimension(_fileSet, (-1 == lCDims[2] ? 2 : 3), num_elems);MB_CHK_SET_ERR(rval, "Trouble getting number of elements"); /* // Check against parameters // When ghosting is used, this check might fail (to be updated later) if (num_elems > 0) { int expected_elems = (lCDims[3] - lCDims[0] + 1) * (lCDims[4] - lCDims[1] + 1) * (-1 == lCDims[2] ? 1 : (lCDims[5] - lCDims[2] + 1)); if (num_elems != expected_elems) { MB_SET_ERR(MB_FAILURE, "Number of elements doesn't match"); } } */ return MB_SUCCESS; } ErrorCode ScdNCHelper::create_mesh(Range& faces) { Interface*& mbImpl = _readNC->mbImpl; Tag& mGlobalIdTag = _readNC->mGlobalIdTag; const Tag*& mpFileIdTag = _readNC->mpFileIdTag; DebugOutput& dbgOut = _readNC->dbgOut; ScdInterface* scdi = _readNC->scdi; ScdParData& parData = _readNC->parData; Range tmp_range; ScdBox* scd_box; ErrorCode rval = scdi->construct_box(HomCoord(lDims[0], lDims[1], lDims[2], 1), HomCoord(lDims[3], lDims[4], lDims[5], 1), NULL, 0, scd_box, locallyPeriodic, &parData, true);MB_CHK_SET_ERR(rval, "Trouble creating scd vertex sequence"); // Add verts to tmp_range first, so we can duplicate global ids in vertex ids tmp_range.insert(scd_box->start_vertex(), scd_box->start_vertex() + scd_box->num_vertices() - 1); if (mpFileIdTag) { int count; void* data; rval = mbImpl->tag_iterate(*mpFileIdTag, tmp_range.begin(), tmp_range.end(), count, data);MB_CHK_SET_ERR(rval, "Failed to iterate file ID tag on local vertices"); assert(count == scd_box->num_vertices()); int* fid_data = (int*) data; rval = mbImpl->tag_iterate(mGlobalIdTag, tmp_range.begin(), tmp_range.end(), count, data);MB_CHK_SET_ERR(rval, "Failed to iterate global ID tag on local vertices"); assert(count == scd_box->num_vertices()); int* gid_data = (int*) data; for (int i = 0; i < count; i++) fid_data[i] = gid_data[i]; } // Then add box set and elements to the range, then to the file set tmp_range.insert(scd_box->start_element(), scd_box->start_element() + scd_box->num_elements() - 1); tmp_range.insert(scd_box->box_set()); rval = mbImpl->add_entities(_fileSet, tmp_range);MB_CHK_SET_ERR(rval, "Couldn't add new vertices to current file set"); dbgOut.tprintf(1, "scdbox %d quads, %d vertices\n", scd_box->num_elements(), scd_box->num_vertices()); // Set the vertex coordinates double *xc, *yc, *zc; rval = scd_box->get_coordinate_arrays(xc, yc, zc);MB_CHK_SET_ERR(rval, "Couldn't get vertex coordinate arrays"); int i, j, k, il, jl, kl; int dil = lDims[3] - lDims[0] + 1; int djl = lDims[4] - lDims[1] + 1; assert(dil == (int)ilVals.size() && djl == (int)jlVals.size() && (-1 == lDims[2] || lDims[5] - lDims[2] + 1 == (int)levVals.size())); for (kl = lDims[2]; kl <= lDims[5]; kl++) { k = kl - lDims[2]; for (jl = lDims[1]; jl <= lDims[4]; jl++) { j = jl - lDims[1]; for (il = lDims[0]; il <= lDims[3]; il++) { i = il - lDims[0]; unsigned int pos = i + j * dil + k * dil * djl; xc[pos] = ilVals[i]; yc[pos] = jlVals[j]; zc[pos] = (-1 == lDims[2] ? 0.0 : levVals[k]); } } } #ifndef NDEBUG int num_verts = (lDims[3] - lDims[0] + 1) * (lDims[4] - lDims[1] + 1) * (-1 == lDims[2] ? 1 : lDims[5] - lDims[2] + 1); std::vector<int> gids(num_verts); Range verts(scd_box->start_vertex(), scd_box->start_vertex() + scd_box->num_vertices() - 1); rval = mbImpl->tag_get_data(mGlobalIdTag, verts, &gids[0]);MB_CHK_SET_ERR(rval, "Trouble getting local gid values of vertices"); int vmin = *(std::min_element(gids.begin(), gids.end())), vmax = *(std::max_element(gids.begin(), gids.end())); dbgOut.tprintf(1, "Vertex gids %d-%d\n", vmin, vmax); #endif // Add elements to the range passed in faces.insert(scd_box->start_element(), scd_box->start_element() + scd_box->num_elements() - 1); if (2 <= dbgOut.get_verbosity()) { assert(scd_box->boundary_complete()); EntityHandle dum_ent = scd_box->start_element(); rval = mbImpl->list_entities(&dum_ent, 1);MB_CHK_SET_ERR(rval, "Trouble listing first hex"); std::vector<EntityHandle> connect; rval = mbImpl->get_connectivity(&dum_ent, 1, connect);MB_CHK_SET_ERR(rval, "Trouble getting connectivity"); rval = mbImpl->list_entities(&connect[0], connect.size());MB_CHK_SET_ERR(rval, "Trouble listing element connectivity"); } Range edges; mbImpl->get_adjacencies(faces, 1, true, edges, Interface::UNION); // Create COORDS tag for quads rval = create_quad_coordinate_tag();MB_CHK_SET_ERR(rval, "Trouble creating COORDS tag for quads"); return MB_SUCCESS; } ErrorCode ScdNCHelper::read_variables(std::vector<std::string>& var_names, std::vector<int>& tstep_nums) { std::vector<ReadNC::VarData> vdatas; std::vector<ReadNC::VarData> vsetdatas; ErrorCode rval = read_variables_setup(var_names, tstep_nums, vdatas, vsetdatas);MB_CHK_SET_ERR(rval, "Trouble setting up to read variables"); if (!vsetdatas.empty()) { rval = read_variables_to_set(vsetdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble reading variables to set"); } if (!vdatas.empty()) { rval = read_scd_variables_to_nonset(vdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble reading variables to verts/edges/faces"); } return MB_SUCCESS; } ErrorCode ScdNCHelper::read_scd_variables_to_nonset_allocate(std::vector<ReadNC::VarData>& vdatas, std::vector<int>& tstep_nums) { Interface*& mbImpl = _readNC->mbImpl; std::vector<int>& dimLens = _readNC->dimLens; DebugOutput& dbgOut = _readNC->dbgOut; Range* range = NULL; // Get vertices Range verts; ErrorCode rval = mbImpl->get_entities_by_dimension(_fileSet, 0, verts);MB_CHK_SET_ERR(rval, "Trouble getting vertices in current file set"); assert("Should only have a single vertex subrange, since they were read in one shot" && verts.psize() == 1); Range edges; rval = mbImpl->get_entities_by_dimension(_fileSet, 1, edges);MB_CHK_SET_ERR(rval, "Trouble getting edges in current file set"); // Get faces Range faces; rval = mbImpl->get_entities_by_dimension(_fileSet, 2, faces);MB_CHK_SET_ERR(rval, "Trouble getting faces in current file set"); assert("Should only have a single face subrange, since they were read in one shot" && faces.psize() == 1); #ifdef MOAB_HAVE_MPI moab::Range faces_owned; bool& isParallel = _readNC->isParallel; if (isParallel) { ParallelComm*& myPcomm = _readNC->myPcomm; rval = myPcomm->filter_pstatus(faces, PSTATUS_NOT_OWNED, PSTATUS_NOT, -1, &faces_owned);MB_CHK_SET_ERR(rval, "Trouble getting owned faces in current file set"); } else faces_owned = faces; // Not running in parallel, but still with MPI #endif for (unsigned int i = 0; i < vdatas.size(); i++) { // Support non-set variables with 4 dimensions like (time, lev, lat, lon) assert(4 == vdatas[i].varDims.size()); // For a non-set variable, time should be the first dimension assert(tDim == vdatas[i].varDims[0]); // Set up readStarts and readCounts vdatas[i].readStarts.resize(4); vdatas[i].readCounts.resize(4); // First: time vdatas[i].readStarts[0] = 0; // This value is timestep dependent, will be set later vdatas[i].readCounts[0] = 1; // Next: lev vdatas[i].readStarts[1] = 0; vdatas[i].readCounts[1] = vdatas[i].numLev; // Finally: lat (or slat) and lon (or slon) switch (vdatas[i].entLoc) { case ReadNC::ENTLOCVERT: // Vertices vdatas[i].readStarts[2] = lDims[1]; vdatas[i].readCounts[2] = lDims[4] - lDims[1] + 1; vdatas[i].readStarts[3] = lDims[0]; vdatas[i].readCounts[3] = lDims[3] - lDims[0] + 1; range = &verts; break; case ReadNC::ENTLOCNSEDGE: case ReadNC::ENTLOCEWEDGE: case ReadNC::ENTLOCEDGE: // Not implemented yet, set a global error MB_SET_GLB_ERR(MB_NOT_IMPLEMENTED, "Reading edge data is not implemented yet"); case ReadNC::ENTLOCFACE: // Faces vdatas[i].readStarts[2] = lCDims[1]; vdatas[i].readCounts[2] = lCDims[4] - lCDims[1] + 1; vdatas[i].readStarts[3] = lCDims[0]; vdatas[i].readCounts[3] = lCDims[3] - lCDims[0] + 1; #ifdef MOAB_HAVE_MPI range = &faces_owned; #else range = &faces; #endif break; default: MB_SET_ERR(MB_FAILURE, "Unexpected entity location type for variable " << vdatas[i].varName); } for (unsigned int t = 0; t < tstep_nums.size(); t++) { dbgOut.tprintf(2, "Reading variable %s, time step %d\n", vdatas[i].varName.c_str(), tstep_nums[t]); if (tstep_nums[t] >= dimLens[tDim]) { MB_SET_ERR(MB_INDEX_OUT_OF_RANGE, "Wrong value for timestep number " << tstep_nums[t]); } // Get the tag to read into if (!vdatas[i].varTags[t]) { rval = get_tag_to_nonset(vdatas[i], tstep_nums[t], vdatas[i].varTags[t], vdatas[i].numLev);MB_CHK_SET_ERR(rval, "Trouble getting tag to non-set variable " << vdatas[i].varName); } // Get ptr to tag space void* data; int count; rval = mbImpl->tag_iterate(vdatas[i].varTags[t], range->begin(), range->end(), count, data);MB_CHK_SET_ERR(rval, "Failed to iterate tag for non-set variable " << vdatas[i].varName); assert((unsigned)count == range->size()); vdatas[i].varDatas[t] = data; } // Get variable size vdatas[i].sz = 1; for (std::size_t idx = 0; idx != vdatas[i].readCounts.size(); idx++) vdatas[i].sz *= vdatas[i].readCounts[idx]; } return rval; } ErrorCode ScdNCHelper::read_scd_variables_to_nonset(std::vector<ReadNC::VarData>& vdatas, std::vector<int>& tstep_nums) { DebugOutput& dbgOut = _readNC->dbgOut; ErrorCode rval = read_scd_variables_to_nonset_allocate(vdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble allocating space to read non-set variables"); // Finally, read into that space int success; for (unsigned int i = 0; i < vdatas.size(); i++) { std::size_t sz = vdatas[i].sz; // A typical supported variable: float T(time, lev, lat, lon) // For tag values, need transpose (lev, lat, lon) to (lat, lon, lev) size_t ni = vdatas[i].readCounts[3]; // lon or slon size_t nj = vdatas[i].readCounts[2]; // lat or slat size_t nk = vdatas[i].readCounts[1]; // lev for (unsigned int t = 0; t < tstep_nums.size(); t++) { // Tag data for this timestep void* data = vdatas[i].varDatas[t]; // Set readStart for each timestep along time dimension vdatas[i].readStarts[0] = tstep_nums[t]; switch (vdatas[i].varDataType) { case NC_BYTE: case NC_CHAR: { std::vector<char> tmpchardata(sz); success = NCFUNCAG(_vara_text)(_fileId, vdatas[i].varId, &vdatas[i].readStarts[0], &vdatas[i].readCounts[0], &tmpchardata[0]); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read byte/char data for variable " << vdatas[i].varName); if (vdatas[i].numLev > 1) // Transpose (lev, lat, lon) to (lat, lon, lev) kji_to_jik(ni, nj, nk, data, &tmpchardata[0]); else { for (std::size_t idx = 0; idx != tmpchardata.size(); idx++) ((char*) data)[idx] = tmpchardata[idx]; } break; } case NC_SHORT: case NC_INT: { std::vector<int> tmpintdata(sz); success = NCFUNCAG(_vara_int)(_fileId, vdatas[i].varId, &vdatas[i].readStarts[0], &vdatas[i].readCounts[0], &tmpintdata[0]); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read short/int data for variable " << vdatas[i].varName); if (vdatas[i].numLev > 1) // Transpose (lev, lat, lon) to (lat, lon, lev) kji_to_jik(ni, nj, nk, data, &tmpintdata[0]); else { for (std::size_t idx = 0; idx != tmpintdata.size(); idx++) ((int*) data)[idx] = tmpintdata[idx]; } break; } case NC_FLOAT: case NC_DOUBLE: { std::vector<double> tmpdoubledata(sz); success = NCFUNCAG(_vara_double)(_fileId, vdatas[i].varId, &vdatas[i].readStarts[0], &vdatas[i].readCounts[0], &tmpdoubledata[0]); if (success) MB_SET_ERR(MB_FAILURE, "Failed to read float/double data for variable " << vdatas[i].varName); if (vdatas[i].numLev > 1) // Transpose (lev, lat, lon) to (lat, lon, lev) kji_to_jik(ni, nj, nk, data, &tmpdoubledata[0]); else { for (std::size_t idx = 0; idx != tmpdoubledata.size(); idx++) ((double*) data)[idx] = tmpdoubledata[idx]; } break; } default: MB_SET_ERR(MB_FAILURE, "Unexpected data type for variable " << vdatas[i].varName); } } } // Debug output, if requested if (1 == dbgOut.get_verbosity()) { dbgOut.printf(1, "Read variables: %s", vdatas.begin()->varName.c_str()); for (unsigned int i = 1; i < vdatas.size(); i++) dbgOut.printf(1, ", %s ", vdatas[i].varName.c_str()); dbgOut.tprintf(1, "\n"); } return rval; } ErrorCode ScdNCHelper::create_quad_coordinate_tag() { Interface*& mbImpl = _readNC->mbImpl; Range ents; ErrorCode rval = mbImpl->get_entities_by_type(_fileSet, moab::MBQUAD, ents);MB_CHK_SET_ERR(rval, "Trouble getting quads"); std::size_t numOwnedEnts = 0; #ifdef MOAB_HAVE_MPI Range ents_owned; bool& isParallel = _readNC->isParallel; if (isParallel) { ParallelComm*& myPcomm = _readNC->myPcomm; rval = myPcomm->filter_pstatus(ents, PSTATUS_NOT_OWNED, PSTATUS_NOT, -1, &ents_owned);MB_CHK_SET_ERR(rval, "Trouble getting owned quads"); numOwnedEnts = ents_owned.size(); } else { numOwnedEnts = ents.size(); ents_owned = ents; } #else numOwnedEnts = ents.size(); #endif if (numOwnedEnts == 0) return MB_SUCCESS; assert(numOwnedEnts == ilCVals.size() * jlCVals.size()); std::vector<double> coords(numOwnedEnts * 3); std::size_t pos = 0; for (std::size_t j = 0; j != jlCVals.size(); ++j) { for (std::size_t i = 0; i != ilCVals.size(); ++i) { pos = j * ilCVals.size() * 3 + i * 3; coords[pos] = ilCVals[i]; coords[pos + 1] = jlCVals[j]; coords[pos + 2] = 0.0; } } std::string tag_name = "COORDS"; Tag tagh = 0; rval = mbImpl->tag_get_handle(tag_name.c_str(), 3, MB_TYPE_DOUBLE, tagh, MB_TAG_DENSE | MB_TAG_CREAT);MB_CHK_SET_ERR(rval, "Trouble creating COORDS tag"); void *data; int count; #ifdef MOAB_HAVE_MPI rval = mbImpl->tag_iterate(tagh, ents_owned.begin(), ents_owned.end(), count, data);MB_CHK_SET_ERR(rval, "Failed to iterate COORDS tag on quads"); #else rval = mbImpl->tag_iterate(tagh, ents.begin(), ents.end(), count, data);MB_CHK_SET_ERR(rval, "Failed to iterate COORDS tag on quads"); #endif assert(count == (int)numOwnedEnts); double* quad_data = (double*) data; std::copy(coords.begin(), coords.end(), quad_data); return MB_SUCCESS; } ErrorCode UcdNCHelper::read_variables(std::vector<std::string>& var_names, std::vector<int>& tstep_nums) { std::vector<ReadNC::VarData> vdatas; std::vector<ReadNC::VarData> vsetdatas; ErrorCode rval = read_variables_setup(var_names, tstep_nums, vdatas, vsetdatas);MB_CHK_SET_ERR(rval, "Trouble setting up to read variables"); if (!vsetdatas.empty()) { rval = read_variables_to_set(vsetdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble reading variables to set"); } if (!vdatas.empty()) { #ifdef MOAB_HAVE_PNETCDF // With pnetcdf support, we will use async read rval = read_ucd_variables_to_nonset_async(vdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble reading variables to verts/edges/faces"); #else // Without pnetcdf support, we will use old read rval = read_ucd_variables_to_nonset(vdatas, tstep_nums);MB_CHK_SET_ERR(rval, "Trouble reading variables to verts/edges/faces"); #endif } return MB_SUCCESS; } } // namespace moab
40.884585
187
0.646977
joeylamcy
7d5b6bc46dca279363db254f7ec569c81fbdf343
801
cpp
C++
Competitive Programming/counting_valleys.cpp
darnoceloc/Algorithms
bc455cc00d9405493c951b8ea3132e615a49c9ee
[ "MIT" ]
null
null
null
Competitive Programming/counting_valleys.cpp
darnoceloc/Algorithms
bc455cc00d9405493c951b8ea3132e615a49c9ee
[ "MIT" ]
null
null
null
Competitive Programming/counting_valleys.cpp
darnoceloc/Algorithms
bc455cc00d9405493c951b8ea3132e615a49c9ee
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <limits> #include <fstream> // Complete the countingValleys function below. int countingValleys(int n, std::string s) { int elevation = 0; int valleys = 0; for(int i = 0; i < n; i++){ if(elevation == 0 && s[i] == 'D'){ valleys += 1; } if (s[i] == 'U'){ elevation += 1; } if (s[i] == 'D'){ elevation += -1; } } return valleys; } int main(){ std::ofstream fout(getenv("OUTPUT_PATH")); int n; std::cin >> n; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::string s; std::getline(std::cin, s); int result = countingValleys(n, s); fout << result << "\n"; fout.close(); return 0; }
19.536585
71
0.503121
darnoceloc
7d603fbc768f522484dd1870294162a515fa6ce7
1,990
cpp
C++
PraktiskieDarbi/praktiskaisDarbs1.cpp
ElizaGulbe/MIprogramma_darbi
4b1e027afe939317046d82e99d65a4d22d84651e
[ "MIT" ]
null
null
null
PraktiskieDarbi/praktiskaisDarbs1.cpp
ElizaGulbe/MIprogramma_darbi
4b1e027afe939317046d82e99d65a4d22d84651e
[ "MIT" ]
null
null
null
PraktiskieDarbi/praktiskaisDarbs1.cpp
ElizaGulbe/MIprogramma_darbi
4b1e027afe939317046d82e99d65a4d22d84651e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> using namespace std; float computeAvgValue(int arr[10]){ float sum = 0; for (int i = 0; i <= 9; i++) { sum += arr[i]; } float average = sum/10; return average; } float findBiggest(float arr[10]) { float curBiggest = arr[0]; for (int i = 1; i<=9; i++) { if (curBiggest < arr[i]) { curBiggest = arr[i]; } } return curBiggest; } void displayArray(int arr[5][5]){ for(int i = 0; i<5;i++) { for(int x = 0; x<5;x++) { if (x == 4) { cout << x << endl; } else { cout << x << " "; } } } } void twoDimensionalArr() { int twoDimArr[5][5]; for(int i = 0; i<5;i++){ for(int x = 0; x<5;x++){ twoDimArr[i][x] = x; } } displayArray(twoDimArr); } int countOccurance(string userInput) { int occuranceOfA = 0; for(char i: userInput) { if (i == 'a') { occuranceOfA++; } } return occuranceOfA; } string cutNumbers(string userInput){ string retVal; for(int i = 0; i < userInput.size(); i++){ if (isdigit(userInput[i]) == 0) { retVal.push_back(userInput[i]); } else{ continue; } } return retVal; } int main(){ string userInput; getline(cin,userInput); cout << "varda " << userInput << "simbols a atkartojas " << countOccurance(userInput) << " reizes" << endl; string cutDigits; getline(cin,cutDigits); cout << "iznemot no simbolu virkes " << cutDigits << " visus ciparus sanak " << cutNumbers(cutDigits) << endl; int arr[10] = {1,2,3,4,5,6,8,8,9,10}; cout << "masiva videja vertiba ir " << computeAvgValue(arr) << endl; float arrfloat[10] = {1.1,2.2,3.3,4.4,10.1,5.4,6.7,7.8,8.9,9.8}; cout << "find biggest retVal" << findBiggest(arrfloat) << endl; twoDimensionalArr(); return 0; }
22.359551
115
0.51608
ElizaGulbe
7d60c646d8121c85bd5c9787487373c9855e66da
1,848
cpp
C++
frameworks/runtime-src/Classes/lua-binding/manual/lua_cocos2dx_plugin_manual.cpp
edwardzhou/ddz-client
ed5db2b625cc55192027ffd69e0ec5f342a40222
[ "MIT" ]
5
2018-01-22T13:00:11.000Z
2021-02-20T04:24:30.000Z
frameworks/runtime-src/Classes/lua-binding/manual/lua_cocos2dx_plugin_manual.cpp
edwardzhou/ddz-client
ed5db2b625cc55192027ffd69e0ec5f342a40222
[ "MIT" ]
null
null
null
frameworks/runtime-src/Classes/lua-binding/manual/lua_cocos2dx_plugin_manual.cpp
edwardzhou/ddz-client
ed5db2b625cc55192027ffd69e0ec5f342a40222
[ "MIT" ]
5
2018-01-10T00:40:29.000Z
2021-08-22T14:12:44.000Z
#include "lua_cocos2dx_plugin_manual.hpp" #include "PluginManager.h" #include "PluginProtocol.h" #include "ProtocolAnalytics.h" #include "PluginParam.h" #include "tolua_fix.h" #include "LuaBasicConversions.h" int tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00(lua_State* tolua_S) { int argc = 0; cocos2d::plugin::PluginProtocol* cobj = nullptr; bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 if (!tolua_isusertype(tolua_S,1,"plugin.PluginProtocol",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::plugin::PluginProtocol*)tolua_tousertype(tolua_S,1,0); #if COCOS2D_DEBUG >= 1 if (!cobj) { tolua_error(tolua_S,"invalid 'cobj' in function 'tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00'", nullptr); return 0; } #endif argc = lua_gettop(tolua_S)-1; if (argc == 0) { CCLOG("%s has wrong number of arguments: %d, was expecting at least %d \n", "callFuncWithParam",argc, 1); return 0; } std::std::vector<cocos2d::plugin::PluginParam*> params; for (int i=0; i<argc; i++) { if (lua_istable(tolua_S, i+2) > 0) { // table } } #if COCOS2D_DEBUG >= 1 tolua_lerror: tolua_error(tolua_S,"#ferror in function 'tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00'.",&tolua_err); #endif return 0; } static void extendPluginProtocol(lua_State* L) { lua_pushstring(L, "plugin.PluginProtocol"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { tolua_function(L, "callFuncWithParam", tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00); } lua_pop(L, 1); } int register_all_cocos2dx_plugin_manual(lua_State* L) { if (nullptr == L) return 0; extendPluginProtocol(L); return 0; }
24.315789
125
0.6829
edwardzhou
7d629a2a0ec8fc39bc991f5e0e713bd7433d5e1a
2,122
cpp
C++
src/person.cpp
arctech-training-worldline-cpp/HospitalManagementDemo
a553c9fa523ac1308564e424ce996a676557d91f
[ "MIT" ]
7
2021-07-04T18:18:02.000Z
2022-02-20T14:29:23.000Z
src/person.cpp
arctech-training-worldline-cpp/HospitalManagementDemo
a553c9fa523ac1308564e424ce996a676557d91f
[ "MIT" ]
null
null
null
src/person.cpp
arctech-training-worldline-cpp/HospitalManagementDemo
a553c9fa523ac1308564e424ce996a676557d91f
[ "MIT" ]
2
2021-11-08T13:30:34.000Z
2021-11-16T02:57:26.000Z
using namespace std; #include <vector> #include <string> #include <iostream> #include <sstream> #include <fstream> #include "./../include/global.hh" #include "./../include/person.hh" person::person() { id = -1; } void person::addPerson(int16_t minAge, int16_t maxAge) { //getting basic details of the person from the user side; cout << "\nEnter name: \nFirst name:\n"; getline(cin >> ws, firstName); cout << "\nLast name:\n"; getline(cin, lastName); cout << "\nEnter age: \n"; cin >> age; while (age <= 0) cout << "Was that supposed to make any kind of sense?\nEnter again!\n", cin >> age; if (category != 2) { if (age < minAge) return void(cout << "Sorry, person should be at least " << minAge << " years old to be registered as a " << cat << ".\n"); else if (age > maxAge) return void(cout << "Sorry, we can't register a person older than " << maxAge << " years as a " << cat << ".\n"); } cout << "\nGender (M = Male || F = Female): \n"; cin >> gender; while (gender != 'M' && gender != 'F') cout << "M or F?\n", cin >> gender; cout << "\nEnter mobile number (with country code): \n"; getline(cin >> ws, mobNumber); add.takeInput(); return; } void person::printDetails() { if (id == -1) return; cout << "\nDetails:\n"; cout << "ID : " << id << "\n"; cout << "Full Name : " << firstName << " " << lastName << "\n"; cout << "Gender : " << gender << "\n"; cout << "Age : " << age << "\n"; cout << "Mobile : " << mobNumber << "\n"; cout << "Address : "; add.print(); return; } void person::printDetailsFromHistory() { if (id == -1) return; cout << "\nHistory Details :\n"; cout << "Full Name : " << firstName << " " << lastName << "\n"; cout << "Gender : " << gender << "\n"; cout << "Age : " << age << "\n"; cout << "Mobile : " << mobNumber << "\n"; cout << "Address : "; add.print(); return; }
30.314286
134
0.494816
arctech-training-worldline-cpp
7d667e5944be9ad5c6921f9e298ff28bd8beec5d
3,161
cpp
C++
project3D/GameObject.cpp
nandos13/Shadercpp
404f2ab8d3b32073a54945081d74fac46bdd0178
[ "MIT" ]
null
null
null
project3D/GameObject.cpp
nandos13/Shadercpp
404f2ab8d3b32073a54945081d74fac46bdd0178
[ "MIT" ]
null
null
null
project3D/GameObject.cpp
nandos13/Shadercpp
404f2ab8d3b32073a54945081d74fac46bdd0178
[ "MIT" ]
null
null
null
#include "GameObject.h" #include "Application3D.h" #include <limits> glm::mat4 GameObject::getMatrixTransform() { // Define radian float rad = 3.14f / 180.0f; glm::mat4 transform = glm::translate(m_translation) * glm::rotate(m_rotationEuler.z * rad, glm::vec3(0, 0, 1)) * glm::rotate(m_rotationEuler.y * rad, glm::vec3(0, 1, 0)) * glm::rotate(m_rotationEuler.x * rad, glm::vec3(1, 0, 0)) * glm::scale(m_scale); return transform; } GameObject::GameObject() { m_translation = glm::vec3(0); m_rotationEuler = glm::vec3(0); m_scale = glm::vec3(1); } GameObject::~GameObject() { } void GameObject::Draw(glm::mat4 cameraMatrix, unsigned int programID) { // Verify the model exists if (m_model != nullptr) { // Get Lighting information and pass into shader GetLights(programID); // Pass info in to draw model m_model->Draw(getMatrixTransform(), cameraMatrix, programID); } } void GameObject::GetLights(unsigned int programID) { // Get the vector of scene lights std::vector<Light*> sceneLights = Application3D::GetLightSources(); Light* closeLights[8]; int size = sceneLights.size(); if (size > 8) { // Loop through all lights and find the closest 8 light sources int i = sceneLights.size() - 1; while (i > 0) { // Sort the list by distance to the gameobject if (glm::distance(sceneLights[i]->GetPosition(), this->m_translation) < glm::distance(sceneLights[i - 1]->GetPosition(), this->m_translation)) { // Swap the two elements std::iter_swap(sceneLights.begin()+i, sceneLights.begin()+i-1); // Move index up in case distance is larger than those already tested if (i != sceneLights.size() - 1) i++; } else { i--; } } } // Find how many objects need to be copied unsigned int quantity = (sceneLights.size() > 8) ? 8 : sceneLights.size(); // Copy first 8 elements to the new array for (unsigned int j = 0; j < quantity; j++) { closeLights[j] = sceneLights[j]; } // Pass in the amount of lights to be used unsigned int quantityUniform = glGetUniformLocation(programID, "lightQuantity"); glUniform1i(quantityUniform, quantity); // Pass in the light positions & information (intensity, etc) glm::vec3 closeLightPositions[8]; glm::vec2 closeLightInfo[8]; for (int i = 0; i < quantity; i++) { if (closeLights[i] != nullptr) { closeLightPositions[i] = closeLights[i]->GetPosition(); closeLightInfo[i] = glm::vec2(closeLights[i]->GetIntensity(), closeLights[i]->GetReach()); } } // Positions unsigned int lightsUniform = glGetUniformLocation(programID, "lights"); glUniform3fv(lightsUniform, 8, &closeLightPositions[0].x); // Other info unsigned int lightsInfoUniform = glGetUniformLocation(programID, "lightsInfo"); glUniform2fv(lightsInfoUniform, 8, &closeLightInfo[0].x); } void GameObject::SetModel(Model * model) { m_model = model; } Model * GameObject::GetModel() { return m_model; } void GameObject::SetTranslation(glm::vec3 translation) { m_translation = translation; } void GameObject::SetRotation(glm::vec3 euler) { m_rotationEuler = euler; } void GameObject::SetScale(glm::vec3 localScale) { m_scale = localScale; }
25.288
93
0.693135
nandos13
7d670b5a68f4d4dcb4a193ed68aa5994f9d91229
4,690
hpp
C++
order.hpp
chaosmw/youdex
78e1c20548183b7c9b30ec924ff0711c029123ef
[ "MIT" ]
1
2020-08-29T09:53:29.000Z
2020-08-29T09:53:29.000Z
order.hpp
chaosmw/youdex
78e1c20548183b7c9b30ec924ff0711c029123ef
[ "MIT" ]
null
null
null
order.hpp
chaosmw/youdex
78e1c20548183b7c9b30ec924ff0711c029123ef
[ "MIT" ]
null
null
null
#pragma once #include <eosiolib/eosio.hpp> #include <eosiolib/asset.hpp> #include "exchange_types.hpp" using namespace eosio; using namespace std; namespace dex { // caution: the order is deliberately designd for matching routine, do not change it!!! // see get_range enum order_type: uint8_t { RESERVED = 0, ASK_MARKET = 1, ASK_LIMITED = 2, BID_MARKET = 3, // so we can use them for tick matching, do NOT change the order! BID_LIMITED = 4, // biding orders are always at the top price list, when calling get_price }; uint128_t make_match_128(uint16_t pid, uint8_t type, asset price) { uint128_t temp = 0; uint128_t pid128 = (uint128_t)pid; uint128_t type128 = (uint128_t)type; // Notic that for bidding orders, we use reverse order!!! uint64_t price64 = (type != BID_LIMITED) ? price.amount : static_cast<uint64_t>(-price.amount); temp = (pid128 << 72) | (type128 << 64) | price64; return temp; } enum close_reason: uint8_t { NORMAL = 0, CANCELLED = 1, EXPIRED = 2, NOT_ENOUGH_FEE = 3, }; const uint8_t ORDER_TYPE_MASK = 0x0F; auto temp = make_tuple(0, 0, 0); typedef asset order_price; typedef asset quote_amount; // Orders are stored within different scopes? // (_self, _self) struct order { uint64_t id; uint64_t gid; // primary key account_name owner; exch::exchange_pair_id pair_id; order_type type; // Timing related fileds time placed_time; time updated_time; time closed_time; uint8_t close_reason; time expiration_time; asset initial; asset remain; order_price price; quote_amount deal; void reset() { // CAN NOT CHANGE GID id = 0; pair_id = 0; type = RESERVED; placed_time = 0; updated_time = 0; closed_time = 0; close_reason = 0; expiration_time = 0; initial = asset(0); remain = asset(0); price = asset(0); deal = asset(0); } auto primary_key() const { return gid; } uint64_t get_id() const { return id; } uint64_t get_expiration() const { return expiration_time; } uint64_t get_owner() const { return owner; } uint128_t get_slot() const { return make_key_128(owner, type); } uint128_t get_price() const { return make_match_128(pair_id, type, price); } EOSLIB_SERIALIZE( order, (id)(gid)(owner)(pair_id)(type)(placed_time)(updated_time)\ (closed_time)(close_reason)(expiration_time)(initial)(remain)(price)(deal) ) }; typedef eosio::multi_index< N(orders), order, indexed_by< N( byid ), const_mem_fun< order, uint64_t, &order::get_id> >, indexed_by< N( byexp ), const_mem_fun< order, uint64_t, &order::get_expiration> >, indexed_by< N( byprice ), const_mem_fun< order, uint128_t, &order::get_price> >, indexed_by< N( byowner ), const_mem_fun< order, uint64_t, &order::get_owner> >, indexed_by< N( byslot ), const_mem_fun< order, uint128_t, &order::get_slot> > > order_table; bool match(); bool is_ask_order(order_type type) { if (type == ASK_LIMITED || type == ASK_MARKET) { return true; } return false; } bool is_limited_order(uint8_t type) { if (type == ASK_LIMITED || type == BID_LIMITED) { return true; } return false; } // pay attention to the order void get_range(order_type type, bool match_market, order_type& low, order_type& high) { switch (type) { case ASK_LIMITED: high = BID_LIMITED; low = match_market ? BID_MARKET : high; return; case ASK_MARKET: low = high = BID_LIMITED; return; case BID_LIMITED: high = ASK_LIMITED; low = match_market? ASK_MARKET : high; return; case BID_MARKET: low = high = ASK_LIMITED; return; default: eosio_assert(false, "not supported yet"); } } bool parse_order_from_string(string &memo, order& o, bool& match_now); } /// namespace dex
34.740741
114
0.550746
chaosmw
de0b48cde928efbec3fb7c938ab78bb8048be253
2,923
inl
C++
include/bit/math/detail/vector.inl
bitwizeshift/bit-math
e29d6dfe3cefecd08c3215bc4578b5903b269d86
[ "MIT" ]
3
2020-04-05T01:14:21.000Z
2021-10-03T09:34:48.000Z
include/bit/math/detail/vector.inl
bitwizeshift/bit-math
e29d6dfe3cefecd08c3215bc4578b5903b269d86
[ "MIT" ]
1
2017-10-15T20:41:30.000Z
2017-10-15T20:41:30.000Z
include/bit/math/detail/vector.inl
bitwizeshift/bit-math
e29d6dfe3cefecd08c3215bc4578b5903b269d86
[ "MIT" ]
null
null
null
#ifndef BIT_MATH_DETAIL_VECTOR_INL #define BIT_MATH_DETAIL_VECTOR_INL #ifndef BIT_MATH_VECTOR_HPP # error "vector.inl included without first including declaration header vector.hpp" #endif //---------------------------------------------------------------------------- // Detail: Vector Casting //---------------------------------------------------------------------------- namespace bit { namespace math { namespace detail { template<typename T, typename U> struct vector_caster<vector2<T>,vector2<U>> { static constexpr vector2<T> cast( const vector2<U>& from ) noexcept { return vector2<T>( from ); } }; template<typename T, typename U> struct vector_caster<vector3<T>,vector2<U>> { static constexpr vector3<T> cast( const vector2<U>& from ) noexcept { return vector3<T>( from.x(), from.y(), T(0) ); } }; template<typename T, typename U> struct vector_caster<vector4<T>,vector2<U>> { static constexpr vector4<T> cast( const vector2<U>& from ) noexcept { return vector4<T>( from.x(), from.y(), T(0), T(0) ); } }; //---------------------------------------------------------------------------- template<typename T, typename U> struct vector_caster<vector2<T>,vector3<U>> { static constexpr vector2<T> cast( const vector3<U>& from ) noexcept { return vector2<T>( from.x(), from.y() ); } }; template<typename T, typename U> struct vector_caster<vector3<T>,vector3<U>> { static constexpr vector3<T> cast( const vector3<U>& from ) noexcept { return vector3<T>( from ); } }; template<typename T, typename U> struct vector_caster<vector4<T>,vector3<U>> { static constexpr vector4<T> cast( const vector3<U>& from ) noexcept { return vector4<T>( from.x(), from.y(), from.z(), T(0) ); } }; //---------------------------------------------------------------------------- template<typename T, typename U> struct vector_caster<vector2<T>,vector4<U>> { static constexpr vector2<T> cast( const vector4<U>& from ) noexcept { return vector2<T>( from.x(), from.y() ); } }; template<typename T, typename U> struct vector_caster<vector3<T>,vector4<U>> { static constexpr vector3<T> cast( const vector4<U>& from ) noexcept { return vector3<T>( from.x(), from.y(), from.z() ); } }; template<typename T, typename U> struct vector_caster<vector4<T>,vector4<U>> { static constexpr vector4<T> cast( const vector4<U>& from ) noexcept { return vector4<T>( from ); } }; } } } // namespace bit::math::detail //---------------------------------------------------------------------------- // Vector Casting //---------------------------------------------------------------------------- template<typename To, typename From> inline constexpr To bit::math::casts::vector_cast( const From& from ) noexcept { return bit::math::detail::vector_caster<To,From>::cast(from); } #endif /* BIT_MATH_DETAIL_VECTOR_INL */
23.959016
83
0.567225
bitwizeshift
de10e86dc85a333467721695dbb3f08c264feceb
6,008
cpp
C++
cpp/oneapi/dal/algo/pca/backend/gpu/train_kernel_cov_dpc.cpp
dmitrii-kriukov/oneDAL
e962159893ffabdcc601f999f998ce2373c3ce71
[ "Apache-2.0" ]
null
null
null
cpp/oneapi/dal/algo/pca/backend/gpu/train_kernel_cov_dpc.cpp
dmitrii-kriukov/oneDAL
e962159893ffabdcc601f999f998ce2373c3ce71
[ "Apache-2.0" ]
1
2021-05-04T13:03:30.000Z
2021-05-04T13:03:30.000Z
cpp/oneapi/dal/algo/pca/backend/gpu/train_kernel_cov_dpc.cpp
dmitrii-kriukov/oneDAL
e962159893ffabdcc601f999f998ce2373c3ce71
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "oneapi/dal/algo/pca/backend/gpu/train_kernel.hpp" #include "oneapi/dal/algo/pca/backend/common.hpp" #include "oneapi/dal/algo/pca/backend/sign_flip.hpp" #include "oneapi/dal/table/row_accessor.hpp" #include "oneapi/dal/backend/primitives/lapack.hpp" #include "oneapi/dal/backend/primitives/blas.hpp" #include "oneapi/dal/backend/primitives/reduction.hpp" #include "oneapi/dal/backend/primitives/stat.hpp" #include "oneapi/dal/backend/primitives/utils.hpp" #include "oneapi/dal/detail/profiler.hpp" namespace oneapi::dal::pca::backend { namespace pr = oneapi::dal::backend::primitives; using dal::backend::context_gpu; using model_t = model<task::dim_reduction>; using input_t = train_input<task::dim_reduction>; using result_t = train_result<task::dim_reduction>; using descriptor_t = detail::descriptor_base<task::dim_reduction>; template <typename Float> auto compute_sums(sycl::queue& q, const pr::ndview<Float, 2>& data, const dal::backend::event_vector& deps = {}) { ONEDAL_PROFILER_TASK(compute_sums, q); const std::int64_t column_count = data.get_dimension(1); auto sums = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto reduce_event = pr::reduce_by_columns(q, data, sums, pr::sum<Float>{}, pr::identity<Float>{}, deps); return std::make_tuple(sums, reduce_event); } template <typename Float> auto compute_correlation(sycl::queue& q, const pr::ndview<Float, 2>& data, const pr::ndview<Float, 1>& sums, const dal::backend::event_vector& deps = {}) { ONEDAL_PROFILER_TASK(compute_correlation, q); ONEDAL_ASSERT(data.get_dimension(1) == sums.get_dimension(0)); const std::int64_t column_count = data.get_dimension(1); auto corr = pr::ndarray<Float, 2>::empty(q, { column_count, column_count }, sycl::usm::alloc::device); auto means = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto vars = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto tmp = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto gemm_event = gemm(q, data.t(), data, corr, Float(1), Float(0), deps); auto corr_event = pr::correlation(q, data, sums, means, corr, vars, tmp, { gemm_event }); auto smart_event = dal::backend::smart_event{ corr_event }.attach(tmp); return std::make_tuple(corr, means, vars, smart_event); } template <typename Float> auto compute_eigenvectors_on_host(sycl::queue& q, pr::ndarray<Float, 2>&& corr, std::int64_t component_count, const dal::backend::event_vector& deps = {}) { ONEDAL_PROFILER_TASK(compute_eigenvectors_on_host); ONEDAL_ASSERT(corr.get_dimension(0) == corr.get_dimension(1)); const std::int64_t column_count = corr.get_dimension(0); auto eigvecs = pr::ndarray<Float, 2>::empty({ component_count, column_count }); auto eigvals = pr::ndarray<Float, 1>::empty(component_count); auto host_corr = corr.to_host(q, deps); pr::sym_eigvals_descending(host_corr, component_count, eigvecs, eigvals); return std::make_tuple(eigvecs, eigvals); } template <typename Float> static result_t train(const context_gpu& ctx, const descriptor_t& desc, const input_t& input) { auto& q = ctx.get_queue(); const auto data = input.get_data(); const std::int64_t row_count = data.get_row_count(); const std::int64_t column_count = data.get_column_count(); const std::int64_t component_count = get_component_count(desc, data); dal::detail::check_mul_overflow(row_count, column_count); dal::detail::check_mul_overflow(column_count, column_count); dal::detail::check_mul_overflow(component_count, column_count); const auto data_nd = pr::table2ndarray<Float>(q, data, sycl::usm::alloc::device); auto [sums, sums_event] = compute_sums(q, data_nd); auto [corr, means, vars, corr_event] = compute_correlation(q, data_nd, sums, { sums_event }); auto [eigvecs, eigvals] = compute_eigenvectors_on_host(q, std::move(corr), component_count, { corr_event }); if (desc.get_deterministic()) { sign_flip(eigvecs); } const auto model = model_t{}.set_eigenvectors( homogen_table::wrap(eigvecs.flatten(), component_count, column_count)); return result_t{} .set_model(model) .set_eigenvalues(homogen_table::wrap(eigvals.flatten(), 1, component_count)) .set_means(homogen_table::wrap(means.flatten(q), 1, column_count)) .set_variances(homogen_table::wrap(vars.flatten(q), 1, column_count)); } template <typename Float> struct train_kernel_gpu<Float, method::cov, task::dim_reduction> { result_t operator()(const context_gpu& ctx, const descriptor_t& desc, const input_t& input) const { return train<Float>(ctx, desc, input); } }; template struct train_kernel_gpu<float, method::cov, task::dim_reduction>; template struct train_kernel_gpu<double, method::cov, task::dim_reduction>; } // namespace oneapi::dal::pca::backend
44.176471
98
0.672437
dmitrii-kriukov
de110e5302019a7f0ee9f279285372df74156109
6,765
cpp
C++
src/extern/inventor/lib/database/src/so/nodes/SoCallback.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/extern/inventor/lib/database/src/so/nodes/SoCallback.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/extern/inventor/lib/database/src/so/nodes/SoCallback.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Classes: | SoCallback | | Author(s) : Paul S. Strauss | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/actions/SoGetMatrixAction.h> #include <Inventor/actions/SoHandleEventAction.h> #include <Inventor/actions/SoRayPickAction.h> #include <Inventor/actions/SoSearchAction.h> #include <Inventor/actions/SoWriteAction.h> #include <Inventor/elements/SoGLCacheContextElement.h> #include <Inventor/nodes/SoCallback.h> SO_NODE_SOURCE(SoCallback); //////////////////////////////////////////////////////////////////////// // // Description: // Constructor // // Use: public SoCallback::SoCallback() // //////////////////////////////////////////////////////////////////////// { SO_NODE_CONSTRUCTOR(SoCallback); isBuiltIn = TRUE; callbackFunc = NULL; callbackData = NULL; } //////////////////////////////////////////////////////////////////////// // // Description: // Copies the contents of the given node into this instance. // // Use: protected, virtual void SoCallback::copyContents(const SoFieldContainer *fromFC, SbBool copyConnections) // //////////////////////////////////////////////////////////////////////// { // Copy the usual stuff SoNode::copyContents(fromFC, copyConnections); // Copy the callback function and data const SoCallback *fromCB = (const SoCallback *) fromFC; setCallback(fromCB->callbackFunc, fromCB->callbackData); } //////////////////////////////////////////////////////////////////////// // // Description: // Destructor // // Use: private SoCallback::~SoCallback() // //////////////////////////////////////////////////////////////////////// { } //////////////////////////////////////////////////////////////////////// // // Description: // Typical action method. // // Use: extender void SoCallback::doAction(SoAction *action) // //////////////////////////////////////////////////////////////////////// { SoType actionType = action->getTypeId(); SoState *state = action->getState(); if (this->callbackFunc != NULL) (*this->callbackFunc)(this->callbackData, action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the callback action // // Use: extender void SoCallback::callback(SoCallbackAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the GL render action // // Use: extender void SoCallback::GLRender(SoGLRenderAction *action) // //////////////////////////////////////////////////////////////////////// { // Ask to be cached, to match Inventor 2.0 default: SoGLCacheContextElement::shouldAutoCache(action->getState(), TRUE); SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the get bounding box action // // Use: extender void SoCallback::getBoundingBox(SoGetBoundingBoxAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the get matrix action // // Use: extender void SoCallback::getMatrix(SoGetMatrixAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the handle event thing // // Use: extender void SoCallback::handleEvent(SoHandleEventAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Pick. // // Use: extender void SoCallback::pick(SoPickAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does search... // // Use: extender void SoCallback::search(SoSearchAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); SoNode::search(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the write action // // Use: extender void SoCallback::write(SoWriteAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); SoNode::write(action); }
25.820611
77
0.520177
OpenXIP
de15d2c7b0480eb3b56ab7b2643030ca7564e831
66,245
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/CalendarView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/CalendarView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/widget/CalendarView.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 <Elastos.CoreLibrary.Libcore.h> #include <Elastos.CoreLibrary.Text.h> #include "elastos/droid/widget/CalendarView.h" #include "elastos/droid/widget/CAbsListViewLayoutParams.h" #include "elastos/droid/content/res/CConfiguration.h" #include "elastos/droid/graphics/CPaint.h" #include "elastos/droid/graphics/CRect.h" #include "elastos/droid/text/TextUtils.h" #include "elastos/droid/text/format/DateUtils.h" #include "elastos/droid/utility/CTypedValueHelper.h" #include "elastos/droid/view/CGestureDetector.h" #include "elastos/droid/R.h" #include <elastos/core/CoreUtils.h> using Elastos::Droid::App::IService; using Elastos::Droid::Content::Res::CConfiguration; using Elastos::Droid::Database::EIID_IDataSetObserver; using Elastos::Droid::Graphics::CPaint; using Elastos::Droid::Graphics::CRect; using Elastos::Droid::Graphics::PaintStyle_FILL; using Elastos::Droid::Graphics::PaintAlign_CENTER; using Elastos::Droid::Text::TextUtils; using Elastos::Droid::Text::Format::IDateUtils; using Elastos::Droid::Text::Format::DateUtils; using Elastos::Droid::Utility::IDisplayMetrics; using Elastos::Droid::Utility::ITypedValueHelper; using Elastos::Droid::Utility::CTypedValueHelper; using Elastos::Droid::Utility::ITypedValue; using Elastos::Droid::View::CGestureDetector; using Elastos::Droid::View::ILayoutInflater; using Elastos::Droid::View::EIID_IViewOnTouchListener; using Elastos::Droid::View::Accessibility::IAccessibilityRecord; using Elastos::Droid::Widget::CAbsListViewLayoutParams; using Elastos::Droid::R; using Elastos::Core::CoreUtils; using Elastos::Core::IInteger32; using Elastos::Core::ICloneable; using Elastos::Core::CSystem; using Elastos::Core::ISystem; using Elastos::Core::ICharSequence; using Elastos::Core::StringUtils; using Elastos::Core::EIID_IRunnable; using Elastos::Text::ISimpleDateFormat; using Elastos::Text::CSimpleDateFormat; using Elastos::Utility::IDate; using Elastos::Utility::ILocaleHelper; using Elastos::Utility::CLocaleHelper; using Elastos::Utility::ICalendarHelper; using Elastos::Utility::CCalendarHelper; using Elastos::Utility::ITimeZone; using Libcore::ICU::ILocaleDataHelper; using Libcore::ICU::CLocaleDataHelper; using Libcore::ICU::ILocaleData; namespace Elastos { namespace Droid { namespace Widget { //======================================================================================== // CalendarView::AbstractCalendarViewDelegate:: //======================================================================================== CAR_INTERFACE_IMPL(CalendarView::AbstractCalendarViewDelegate, Object, ICalendarViewDelegate) CalendarView::AbstractCalendarViewDelegate::AbstractCalendarViewDelegate( /* [in] */ ICalendarView* delegator, /* [in] */ IContext* context) { mDelegator = delegator; mContext = context; // Initialization based on locale AutoPtr<ILocaleHelper> hlp; CLocaleHelper::AcquireSingleton((ILocaleHelper**)&hlp); AutoPtr<ILocale> loc; hlp->GetDefault((ILocale**)&loc); SetCurrentLocale(loc); } void CalendarView::AbstractCalendarViewDelegate::SetCurrentLocale( /* [in] */ ILocale* locale) { Boolean bEqls = FALSE; if ((locale->Equals(mCurrentLocale, &bEqls), bEqls)) { return; } mCurrentLocale = locale; } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate::OnScrollListener:: //======================================================================================== CAR_INTERFACE_IMPL(CalendarView::LegacyCalendarViewDelegate::OnScrollListener, Object, IAbsListViewOnScrollListener) CalendarView::LegacyCalendarViewDelegate::OnScrollListener::OnScrollListener( /* [in] */ LegacyCalendarViewDelegate* owner) : mOwner(owner) {} ECode CalendarView::LegacyCalendarViewDelegate::OnScrollListener::OnScrollStateChanged( /* [in] */ IAbsListView* view, /* [in] */ Int32 scrollState) { mOwner->OnScrollStateChanged(view, scrollState); return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::OnScrollListener::OnScroll( /* [in] */ IAbsListView* view, /* [in] */ Int32 firstVisibleItem, /* [in] */ Int32 visibleItemCount, /* [in] */ Int32 totalItemCount) { mOwner->OnScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); return NOERROR; } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate //======================================================================================== const Boolean CalendarView::LegacyCalendarViewDelegate::DEFAULT_SHOW_WEEK_NUMBER = TRUE; const Int64 CalendarView::LegacyCalendarViewDelegate::MILLIS_IN_DAY = 86400000LL; const Int32 CalendarView::LegacyCalendarViewDelegate::DAYS_PER_WEEK = 7; const Int64 CalendarView::LegacyCalendarViewDelegate::MILLIS_IN_WEEK = DAYS_PER_WEEK * MILLIS_IN_DAY; const Int32 CalendarView::LegacyCalendarViewDelegate::SCROLL_HYST_WEEKS = 2; const Int32 CalendarView::LegacyCalendarViewDelegate::GOTO_SCROLL_DURATION = 1000; const Int32 CalendarView::LegacyCalendarViewDelegate::ADJUSTMENT_SCROLL_DURATION = 500; const Int32 CalendarView::LegacyCalendarViewDelegate::SCROLL_CHANGE_DELAY = 40; const String CalendarView::LegacyCalendarViewDelegate::DATE_FORMAT("MM/dd/yyyy"); const String CalendarView::LegacyCalendarViewDelegate::DEFAULT_MIN_DATE("01/01/1900"); const String CalendarView::LegacyCalendarViewDelegate::DEFAULT_MAX_DATE("01/01/2100"); const Int32 CalendarView::LegacyCalendarViewDelegate::DEFAULT_SHOWN_WEEK_COUNT = 6; const Int32 CalendarView::LegacyCalendarViewDelegate::DEFAULT_DATE_TEXT_SIZE = 14; const Int32 CalendarView::LegacyCalendarViewDelegate::UNSCALED_SELECTED_DATE_VERTICAL_BAR_WIDTH = 6; const Int32 CalendarView::LegacyCalendarViewDelegate::UNSCALED_WEEK_MIN_VISIBLE_HEIGHT = 12; const Int32 CalendarView::LegacyCalendarViewDelegate::UNSCALED_LIST_SCROLL_TOP_OFFSET = 2; const Int32 CalendarView::LegacyCalendarViewDelegate::UNSCALED_BOTTOM_BUFFER = 20; const Int32 CalendarView::LegacyCalendarViewDelegate::UNSCALED_WEEK_SEPARATOR_LINE_WIDTH = 1; const Int32 CalendarView::LegacyCalendarViewDelegate::DEFAULT_WEEK_DAY_TEXT_APPEARANCE_RES_ID = -1; CalendarView::LegacyCalendarViewDelegate::LegacyCalendarViewDelegate( /* [in] */ ICalendarView* delegator, /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr, /* [in] */ Int32 defStyleRes) : AbstractCalendarViewDelegate(delegator, context) , mWeekSeperatorLineWidth(0) , mDateTextSize(0) , mSelectedDateVerticalBarWidth(0) , mSelectedWeekBackgroundColor(0) , mFocusedMonthDateColor(0) , mUnfocusedMonthDateColor(0) , mWeekSeparatorLineColor(0) , mWeekNumberColor(0) , mWeekDayTextAppearanceResId(0) , mDateTextAppearanceResId(0) , mListScrollTopOffset(2) , mWeekMinVisibleHeight(12) , mBottomBuffer(20) , mShownWeekCount(0) , mShowWeekNumber(FALSE) , mDaysPerWeek(7) , mFriction(.05f) , mVelocityScale(0.333f) , mFirstDayOfWeek(0) , mCurrentMonthDisplayed(-1) , mPreviousScrollPosition(0) , mIsScrollingUp(FALSE) , mPreviousScrollState(IAbsListViewOnScrollListener::SCROLL_STATE_IDLE) , mCurrentScrollState(IAbsListViewOnScrollListener::SCROLL_STATE_IDLE) { mScrollStateChangedRunnable = new ScrollStateRunnable(this); CSimpleDateFormat::New(DATE_FORMAT, (IDateFormat**)&mDateFormat); // initialization based on locale AutoPtr<ILocaleHelper> hlp; CLocaleHelper::AcquireSingleton((ILocaleHelper**)&hlp); AutoPtr<ILocale> loc; hlp->GetDefault((ILocale**)&loc); SetCurrentLocale(loc); AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::CalendarView); AutoPtr<ITypedArray> attributesArray; context->ObtainStyledAttributes(attrs, attrIds, defStyleAttr, defStyleRes, (ITypedArray**)&attributesArray); attributesArray->GetBoolean(R::styleable::CalendarView_showWeekNumber, DEFAULT_SHOW_WEEK_NUMBER, &mShowWeekNumber); AutoPtr<ILocaleDataHelper> locDtHlp; CLocaleDataHelper::AcquireSingleton((ILocaleDataHelper**)&locDtHlp); AutoPtr<ILocaleData> locDt; locDtHlp->Get(loc, (ILocaleData**)&locDt); AutoPtr<IInteger32> pFDW; locDt->GetFirstDayOfWeek((IInteger32**)&pFDW); Int32 val = 0; pFDW->GetValue(&val); attributesArray->GetInt32(R::styleable::CalendarView_firstDayOfWeek, val, &mFirstDayOfWeek); String minDate; attributesArray->GetString(R::styleable::CalendarView_minDate, &minDate); if (TextUtils::IsEmpty(minDate) || !ParseDate(minDate, mMinDate)) { ParseDate(DEFAULT_MIN_DATE, mMinDate); } String maxDate; attributesArray->GetString(R::styleable::CalendarView_maxDate, &maxDate); if (TextUtils::IsEmpty(maxDate) || !ParseDate(maxDate, mMaxDate)) { ParseDate(DEFAULT_MAX_DATE, mMaxDate); } Boolean bIsBf = FALSE; if ((mMaxDate->IsBefore(mMinDate, &bIsBf), bIsBf)) { // throw new IllegalArgumentException("Max date cannot be before min date."); return; } attributesArray->GetInt32(R::styleable::CalendarView_shownWeekCount, DEFAULT_SHOWN_WEEK_COUNT, &mShownWeekCount); attributesArray->GetColor( R::styleable::CalendarView_selectedWeekBackgroundColor, 0, &mSelectedWeekBackgroundColor); attributesArray->GetColor( R::styleable::CalendarView_focusedMonthDateColor, 0, &mFocusedMonthDateColor); attributesArray->GetColor( R::styleable::CalendarView_unfocusedMonthDateColor, 0, &mUnfocusedMonthDateColor); attributesArray->GetColor( R::styleable::CalendarView_weekSeparatorLineColor, 0, &mWeekSeparatorLineColor); attributesArray->GetColor(R::styleable::CalendarView_weekNumberColor, 0, &mWeekNumberColor); attributesArray->GetDrawable( R::styleable::CalendarView_selectedDateVerticalBar, (IDrawable**)&mSelectedDateVerticalBar); attributesArray->GetResourceId( R::styleable::CalendarView_dateTextAppearance, R::style::TextAppearance_Small, &mDateTextAppearanceResId); UpdateDateTextSize(); attributesArray->GetResourceId( R::styleable::CalendarView_weekDayTextAppearance, DEFAULT_WEEK_DAY_TEXT_APPEARANCE_RES_ID, &mWeekDayTextAppearanceResId); attributesArray->Recycle(); AutoPtr<IResources> res; IView::Probe(mDelegator)->GetResources((IResources**)&res); AutoPtr<IDisplayMetrics> displayMetrics; res->GetDisplayMetrics((IDisplayMetrics**)&displayMetrics); AutoPtr<ITypedValueHelper> hlpType; CTypedValueHelper::AcquireSingleton((ITypedValueHelper**)&hlpType); Float fvalue; hlpType->ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_WEEK_MIN_VISIBLE_HEIGHT, displayMetrics, &fvalue); mWeekMinVisibleHeight = (Int32)fvalue; hlpType->ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_LIST_SCROLL_TOP_OFFSET, displayMetrics, &fvalue); mListScrollTopOffset = (Int32)fvalue; hlpType->ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_BOTTOM_BUFFER, displayMetrics, &fvalue); mBottomBuffer = (Int32)fvalue; hlpType->ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_SELECTED_DATE_VERTICAL_BAR_WIDTH, displayMetrics, &fvalue); mSelectedDateVerticalBarWidth = (Int32)fvalue; hlpType->ApplyDimension(ITypedValue::COMPLEX_UNIT_DIP, UNSCALED_WEEK_SEPARATOR_LINE_WIDTH, displayMetrics, &fvalue); mWeekSeperatorLineWidth = (Int32)fvalue; AutoPtr<IInterface> sv; mContext->GetSystemService(IContext::LAYOUT_INFLATER_SERVICE, (IInterface**)&sv); AutoPtr<ILayoutInflater> layoutInflater = ILayoutInflater::Probe(sv); AutoPtr<IView> content; layoutInflater->Inflate(R::layout::calendar_view, NULL, FALSE, (IView**)&content); IViewGroup::Probe(mDelegator)->AddView(content); AutoPtr<IView> vl; IView::Probe(mDelegator)->FindViewById(R::id::list, (IView**)&vl); mListView = IListView::Probe(vl); AutoPtr<IView> vn; content->FindViewById(R::id::day_names, (IView**)&vn); mDayNamesHeader = IViewGroup::Probe(vn); AutoPtr<IView> vmn; content->FindViewById(R::id::month_name, (IView**)&vmn); mMonthName = ITextView::Probe(vmn); SetUpHeader(); SetUpListView(); SetUpAdapter(); // go to today or whichever is close to today min or max date AutoPtr<ISystem> system; CSystem::AcquireSingleton((ISystem**)&system); Int64 nowTime = 0; system->GetCurrentTimeMillis(&nowTime); mTempDate->SetTimeInMillis(nowTime); Boolean bMin = FALSE, bMax = FALSE; if ((mTempDate->IsBefore(mMinDate, &bMin), bMin)) { GoTo(mMinDate, FALSE, TRUE, TRUE); } else if ((mMaxDate->IsBefore(mTempDate, &bMax), bMax)) { GoTo(mMaxDate, FALSE, TRUE, TRUE); } else { GoTo(mTempDate, FALSE, TRUE, TRUE); } IView::Probe(mDelegator)->Invalidate(); } ECode CalendarView::LegacyCalendarViewDelegate::SetShownWeekCount( /* [in] */ Int32 count) { if (mShownWeekCount != count) { mShownWeekCount = count; IView::Probe(mDelegator)->Invalidate(); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetShownWeekCount( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mShownWeekCount; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetSelectedWeekBackgroundColor( /* [in] */ Int32 color) { if (mSelectedWeekBackgroundColor != color) { mSelectedWeekBackgroundColor = color; Int32 childCount = 0; IViewGroup::Probe(mListView)->GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; IViewGroup::Probe(mListView)->GetChildAt(i, (IView**)&child); AutoPtr<WeekView> weekView = (WeekView*) child.Get(); if (weekView->mHasSelectedDay) { weekView->Invalidate(); } } } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetSelectedWeekBackgroundColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mSelectedWeekBackgroundColor; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetFocusedMonthDateColor( /* [in] */ Int32 color) { if (mFocusedMonthDateColor != color) { mFocusedMonthDateColor = color; Int32 childCount = 0; IViewGroup::Probe(mListView)->GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; IViewGroup::Probe(mListView)->GetChildAt(i, (IView**)&child); AutoPtr<WeekView> weekView = (WeekView*) child.Get(); if (weekView->mHasFocusedDay) { weekView->Invalidate(); } } } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetFocusedMonthDateColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mFocusedMonthDateColor; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetUnfocusedMonthDateColor( /* [in] */ Int32 color) { if (mUnfocusedMonthDateColor != color) { mUnfocusedMonthDateColor = color; Int32 childCount = 0; IViewGroup::Probe(mListView)->GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; IViewGroup::Probe(mListView)->GetChildAt(i, (IView**)&child); AutoPtr<WeekView> weekView = (WeekView*) child.Get(); if (weekView->mHasUnfocusedDay) { weekView->Invalidate(); } } } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetUnfocusedMonthDateColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mUnfocusedMonthDateColor; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetWeekNumberColor( /* [in] */ Int32 color) { if (mWeekNumberColor != color) { mWeekNumberColor = color; if (mShowWeekNumber) { InvalidateAllWeekViews(); } } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetWeekNumberColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mWeekNumberColor; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetWeekSeparatorLineColor( /* [in] */ Int32 color) { if (mWeekSeparatorLineColor != color) { mWeekSeparatorLineColor = color; InvalidateAllWeekViews(); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetWeekSeparatorLineColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mWeekSeparatorLineColor; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetSelectedDateVerticalBar( /* [in] */ Int32 resourceId) { AutoPtr<IContext> cxt; IView::Probe(mDelegator)->GetContext((IContext**)&cxt); AutoPtr<IDrawable> drawable; cxt->GetDrawable(resourceId, (IDrawable**)&drawable); SetSelectedDateVerticalBar(drawable); return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetSelectedDateVerticalBar( /* [in] */ IDrawable* drawable) { if (mSelectedDateVerticalBar.Get() != drawable) { mSelectedDateVerticalBar = drawable; Int32 childCount = 0; IViewGroup::Probe(mListView)->GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> child; IViewGroup::Probe(mListView)->GetChildAt(i, (IView**)&child); AutoPtr<WeekView> weekView = (WeekView*) child.Get(); if (weekView->mHasSelectedDay) { weekView->Invalidate(); } } } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetSelectedDateVerticalBar( /* [out] */ IDrawable** result) { VALIDATE_NOT_NULL(result) *result = mSelectedDateVerticalBar; REFCOUNT_ADD(*result) return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetWeekDayTextAppearance( /* [in] */ Int32 resourceId) { if (mWeekDayTextAppearanceResId != resourceId) { mWeekDayTextAppearanceResId = resourceId; SetUpHeader(); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetWeekDayTextAppearance( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mWeekDayTextAppearanceResId; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetDateTextAppearance( /* [in] */ Int32 resourceId) { if (mDateTextAppearanceResId != resourceId) { mDateTextAppearanceResId = resourceId; UpdateDateTextSize(); InvalidateAllWeekViews(); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetDateTextAppearance( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mDateTextAppearanceResId; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetEnabled( /* [in] */ Boolean enabled) { IView::Probe(mListView)->SetEnabled(enabled); return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::IsEnabled( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) return IView::Probe(mListView)->IsEnabled(result); } ECode CalendarView::LegacyCalendarViewDelegate::SetMinDate( /* [in] */ Int64 minDate) { mTempDate->SetTimeInMillis(minDate); if (IsSameDate(mTempDate, mMinDate)) { return NOERROR; } mMinDate->SetTimeInMillis(minDate); // make sure the current date is not earlier than // the new min date since the latter is used for // calculating the indices in the adapter thus // avoiding out of bounds error AutoPtr<ICalendar> date = mAdapter->mSelectedDate; Boolean bMin = FALSE; if ((date->IsBefore(mMinDate, &bMin), bMin)) { mAdapter->SetSelectedDay(mMinDate); } // reinitialize the adapter since its range depends on min date mAdapter->Init(); if ((date->IsBefore(mMinDate, &bMin), bMin)) { Int64 millis = 0; mTempDate->GetTimeInMillis(&millis); SetDate(millis); } else { // we go to the current date to force the ListView to query its // adapter for the shown views since we have changed the adapter // range and the base from which the later calculates item indices // note that calling setDate will not work since the date is the same GoTo(date, FALSE, TRUE, FALSE); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetMinDate( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) return mMinDate->GetTimeInMillis(result); } ECode CalendarView::LegacyCalendarViewDelegate::SetMaxDate( /* [in] */ Int64 maxDate) { mTempDate->SetTimeInMillis(maxDate); if (IsSameDate(mTempDate, mMaxDate)) { return NOERROR; } mMaxDate->SetTimeInMillis(maxDate); // reinitialize the adapter since its range depends on max date mAdapter->Init(); AutoPtr<ICalendar> date = mAdapter->mSelectedDate; Boolean bAft = FALSE; if ((date->IsAfter(mMaxDate, &bAft), bAft)) { Int64 millis = 0; mMaxDate->GetTimeInMillis(&millis); SetDate(millis); } else { // we go to the current date to force the ListView to query its // adapter for the shown views since we have changed the adapter // range and the base from which the later calculates item indices // note that calling setDate will not work since the date is the same GoTo(date, FALSE, TRUE, FALSE); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetMaxDate( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) return mMaxDate->GetTimeInMillis(result); } ECode CalendarView::LegacyCalendarViewDelegate::SetShowWeekNumber( /* [in] */ Boolean showWeekNumber) { if (mShowWeekNumber == showWeekNumber) { return NOERROR; } mShowWeekNumber = showWeekNumber; mAdapter->NotifyDataSetChanged(); SetUpHeader(); return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetShowWeekNumber( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) *result = mShowWeekNumber; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetFirstDayOfWeek( /* [in] */ Int32 firstDayOfWeek) { if (mFirstDayOfWeek == firstDayOfWeek) { return NOERROR; } mFirstDayOfWeek = firstDayOfWeek; mAdapter->Init(); mAdapter->NotifyDataSetChanged(); SetUpHeader(); return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetFirstDayOfWeek( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mFirstDayOfWeek; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::SetDate( /* [in] */ Int64 date) { return SetDate(date, FALSE, FALSE); } ECode CalendarView::LegacyCalendarViewDelegate::SetDate( /* [in] */ Int64 date, /* [in] */ Boolean animate, /* [in] */ Boolean center) { mTempDate->SetTimeInMillis(date); if (IsSameDate(mTempDate, mAdapter->mSelectedDate)) { return NOERROR; } GoTo(mTempDate, animate, TRUE, center); return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::GetDate( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) return mAdapter->mSelectedDate->GetTimeInMillis(result); } ECode CalendarView::LegacyCalendarViewDelegate::SetOnDateChangeListener( /* [in] */ IOnDateChangeListener* listener) { mOnDateChangeListener = listener; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::OnConfigurationChanged( /* [in] */ IConfiguration* newConfig) { AutoPtr<CConfiguration> ccf = (CConfiguration*)newConfig; return SetCurrentLocale(ccf->mLocale); } ECode CalendarView::LegacyCalendarViewDelegate::OnInitializeAccessibilityEvent( /* [in] */ IAccessibilityEvent* event) { return IAccessibilityRecord::Probe(event)->SetClassName(CoreUtils::Convert("CCalendarView")); } ECode CalendarView::LegacyCalendarViewDelegate::OnInitializeAccessibilityNodeInfo( /* [in] */ IAccessibilityNodeInfo* info) { return info->SetClassName(CoreUtils::Convert("CCalendarView")); } ECode CalendarView::LegacyCalendarViewDelegate::SetCurrentLocale( /* [in] */ ILocale* locale) { AbstractCalendarViewDelegate::SetCurrentLocale(locale); mTempDate = GetCalendarForLocale(mTempDate, locale); mFirstDayOfMonth = GetCalendarForLocale(mFirstDayOfMonth, locale); mMinDate = GetCalendarForLocale(mMinDate, locale); mMaxDate = GetCalendarForLocale(mMaxDate, locale); return NOERROR; } void CalendarView::LegacyCalendarViewDelegate::UpdateDateTextSize() { AutoPtr<IContext> cxt; IView::Probe(mDelegator)->GetContext((IContext**)&cxt); AutoPtr<ArrayOf<Int32> > attrIds = TO_ATTRS_ARRAYOF(R::styleable::TextAppearance); AutoPtr<ITypedArray> dateTextAppearance; cxt->ObtainStyledAttributes( mDateTextAppearanceResId, attrIds, (ITypedArray**)&dateTextAppearance); dateTextAppearance->GetDimensionPixelSize( R::styleable::TextAppearance_textSize, DEFAULT_DATE_TEXT_SIZE, &mDateTextSize); dateTextAppearance->Recycle(); } void CalendarView::LegacyCalendarViewDelegate::InvalidateAllWeekViews() { Int32 childCount = 0; IViewGroup::Probe(mListView)->GetChildCount(&childCount); for (Int32 i = 0; i < childCount; i++) { AutoPtr<IView> view; IViewGroup::Probe(mListView)->GetChildAt(i, (IView**)&view); view->Invalidate(); } } AutoPtr<ICalendar> CalendarView::LegacyCalendarViewDelegate::GetCalendarForLocale( /* [in] */ ICalendar* oldCalendar, /* [in] */ ILocale* locale) { if (oldCalendar == NULL) { AutoPtr<ICalendarHelper> hlp; CCalendarHelper::AcquireSingleton((ICalendarHelper**)&hlp); AutoPtr<ICalendar> res; hlp->GetInstance(locale, (ICalendar**)&res); return res; } else { Int64 currentTimeMillis = 0; oldCalendar->GetTimeInMillis(&currentTimeMillis); AutoPtr<ICalendarHelper> hlp; CCalendarHelper::AcquireSingleton((ICalendarHelper**)&hlp); AutoPtr<ICalendar> newCalendar; hlp->GetInstance(locale, (ICalendar**)&newCalendar); newCalendar->SetTimeInMillis(currentTimeMillis); return newCalendar; } } Boolean CalendarView::LegacyCalendarViewDelegate::IsSameDate( /* [in] */ ICalendar* firstDate, /* [in] */ ICalendar* secondDate) { Int32 fDay = 0, sDay = 0, fYear = 0, sYear = 0; firstDate->Get(ICalendar::DAY_OF_YEAR, &fDay); secondDate->Get(ICalendar::DAY_OF_YEAR, &sDay); firstDate->Get(ICalendar::YEAR, &fYear); secondDate->Get(ICalendar::YEAR, &sYear); return (fDay == sDay && fYear == sYear); } void CalendarView::LegacyCalendarViewDelegate::SetUpAdapter() { if (mAdapter == NULL) { mAdapter = new WeeksAdapter(mContext, this); AutoPtr<_DataSetObserver> p = new _DataSetObserver(this); mAdapter->RegisterDataSetObserver(p); IAdapterView::Probe(mListView)->SetAdapter(mAdapter); } // refresh the view with the new parameters mAdapter->NotifyDataSetChanged(); } void CalendarView::LegacyCalendarViewDelegate::SetUpHeader() { mDayLabels = ArrayOf<String>::Alloc(mDaysPerWeek); for (Int32 i = mFirstDayOfWeek, count = mFirstDayOfWeek + mDaysPerWeek; i < count; i++) { Int32 calendarDay = (i > ICalendar::SATURDAY) ? i - ICalendar::SATURDAY : i; (*mDayLabels)[i - mFirstDayOfWeek] = DateUtils::GetDayOfWeekString(calendarDay, IDateUtils::LENGTH_SHORTEST); } AutoPtr<IView> child; mDayNamesHeader->GetChildAt(0, (IView**)&child); AutoPtr<ITextView> label = ITextView::Probe(child); if (mShowWeekNumber) { IView::Probe(label)->SetVisibility(IView::VISIBLE); } else { IView::Probe(label)->SetVisibility(IView::GONE); } Int32 count = 0; mDayNamesHeader->GetChildCount(&count); for (Int32 i = 1; i < count; i++) { AutoPtr<IView> child; mDayNamesHeader->GetChildAt(i, (IView**)&child); label = ITextView::Probe(child); if (mWeekDayTextAppearanceResId > -1) { label->SetTextAppearance(mContext, mWeekDayTextAppearanceResId); } if (i < mDaysPerWeek + 1) { label->SetText(CoreUtils::Convert((*mDayLabels)[i - 1])); child->SetVisibility(IView::VISIBLE); } else { child->SetVisibility(IView::GONE); } } IView::Probe(mDayNamesHeader)->Invalidate(); } void CalendarView::LegacyCalendarViewDelegate::SetUpListView() { // Configure the listview mListView->SetDivider(NULL); mListView->SetItemsCanFocus(TRUE); IView::Probe(mListView)->SetVerticalScrollBarEnabled(FALSE); AutoPtr<OnScrollListener> p = new OnScrollListener(this); IAbsListView* listview = IAbsListView::Probe(mListView); listview->SetOnScrollListener(p); // Make the scrolling behavior nicer listview->SetFriction(mFriction); listview->SetVelocityScale(mVelocityScale); } void CalendarView::LegacyCalendarViewDelegate::GoTo( /* [in] */ ICalendar* date, /* [in] */ Boolean animate, /* [in] */ Boolean setSelected, /* [in] */ Boolean forceScroll) { Boolean bIsBf = FALSE, bIsAf = FALSE; if ((date->IsBefore(mMinDate, &bIsBf), bIsBf) || (date->IsAfter(mMaxDate, &bIsAf), bIsAf)) { // throw new IllegalArgumentException("Time not between " + mMinDate.getTime() // + " and " + mMaxDate.getTime()); return; } // Find the first and last entirely visible weeks Int32 firstFullyVisiblePosition = 0; IAdapterView::Probe(mListView)->GetFirstVisiblePosition(&firstFullyVisiblePosition); AutoPtr<IView> firstChild; IViewGroup::Probe(mListView)->GetChildAt(0, (IView**)&firstChild); Int32 t = 0; if (firstChild != NULL && (firstChild->GetTop(&t), t) < 0) { firstFullyVisiblePosition++; } Int32 lastFullyVisiblePosition = firstFullyVisiblePosition + mShownWeekCount - 1; if (firstChild != NULL && (firstChild->GetTop(&t), t) > mBottomBuffer) { lastFullyVisiblePosition--; } if (setSelected) { mAdapter->SetSelectedDay(date); } // Get the week we're going to Int32 position = GetWeeksSinceMinDate(date); // Check if the selected day is now outside of our visible range // and if so scroll to the month that contains it if (position < firstFullyVisiblePosition || position > lastFullyVisiblePosition || forceScroll) { Int64 currentTimeMillis = 0; date->GetTimeInMillis(&currentTimeMillis); mFirstDayOfMonth->SetTimeInMillis(currentTimeMillis); mFirstDayOfMonth->Set(ICalendar::DAY_OF_MONTH, 1); SetMonthDisplayed(mFirstDayOfMonth); // the earliest time we can scroll to is the min date if ((mFirstDayOfMonth->IsBefore(mMinDate, &bIsBf), bIsBf)) { position = 0; } else { position = GetWeeksSinceMinDate(mFirstDayOfMonth); } mPreviousScrollState = IAbsListViewOnScrollListener::SCROLL_STATE_FLING; IAbsListView* listview = IAbsListView::Probe(mListView); if (animate) { listview->SmoothScrollToPositionFromTop(position, mListScrollTopOffset, GOTO_SCROLL_DURATION); } else { listview->SetSelectionFromTop(position, mListScrollTopOffset); // Perform any after scroll operations that are needed OnScrollStateChanged(listview, IAbsListViewOnScrollListener::SCROLL_STATE_IDLE); } } else if (setSelected) { // Otherwise just set the selection SetMonthDisplayed(date); } } Boolean CalendarView::LegacyCalendarViewDelegate::ParseDate( /* [in] */ const String& date, /* [in] */ ICalendar* outDate) { AutoPtr<IDate> d; ECode ec = mDateFormat->Parse(date, (IDate**)&d); if (SUCCEEDED(ec)) { outDate->SetTime(d); return TRUE; } else { // Log.w(LOG_TAG, "Date: " + date + " not in format: " + DATE_FORMAT); return FALSE; } } void CalendarView::LegacyCalendarViewDelegate::OnScrollStateChanged( /* [in] */ IAbsListView* view, /* [in] */ Int32 scrollState) { mScrollStateChangedRunnable->DoScrollStateChange(view, scrollState); } void CalendarView::LegacyCalendarViewDelegate::OnScroll( /* [in] */ IAbsListView* view, /* [in] */ Int32 firstVisibleItem, /* [in] */ Int32 visibleItemCount, /* [in] */ Int32 totalItemCount) { AutoPtr<IView> _child; IViewGroup::Probe(view)->GetChildAt(0, (IView**)&_child); if (_child == NULL) { return; } AutoPtr<WeekView> child = (WeekView*)_child.Get(); // Figure out where we are Int32 h = 0, b = 0, pos = 0; IAdapterView::Probe(view)->GetFirstVisiblePosition(&pos); child->GetHeight(&h); child->GetBottom(&b); Int64 currScroll = pos * h - b; // If we have moved since our last call update the direction if (currScroll < mPreviousScrollPosition) { mIsScrollingUp = TRUE; } else if (currScroll > mPreviousScrollPosition) { mIsScrollingUp = FALSE; } else { return; } // Use some hysteresis for checking which month to highlight. This // causes the month to transition when two full weeks of a month are // visible when scrolling up, and when the first day in a month reaches // the top of the screen when scrolling down. child->GetBottom(&b); Int32 offset = b < mWeekMinVisibleHeight ? 1 : 0; if (mIsScrollingUp) { AutoPtr<IView> c; IViewGroup::Probe(view)->GetChildAt(SCROLL_HYST_WEEKS + offset, (IView**)&c); child = (WeekView*)c.Get(); } else if (offset != 0) { AutoPtr<IView> c; IViewGroup::Probe(view)->GetChildAt(offset, (IView**)&c); child = (WeekView*)c.Get(); } if (child != NULL) { // Find out which month we're moving into Int32 month = 0; if (mIsScrollingUp) { month = child->GetMonthOfFirstWeekDay(); } else { month = child->GetMonthOfLastWeekDay(); } // And how it relates to our current highlighted month Int32 monthDiff = 0; if (mCurrentMonthDisplayed == 11 && month == 0) { monthDiff = 1; } else if (mCurrentMonthDisplayed == 0 && month == 11) { monthDiff = -1; } else { monthDiff = month - mCurrentMonthDisplayed; } // Only switch months if we're scrolling away from the currently // selected month if ((!mIsScrollingUp && monthDiff > 0) || (mIsScrollingUp && monthDiff < 0)) { AutoPtr<ICalendar> firstDay = child->GetFirstDay(); if (mIsScrollingUp) { firstDay->Add(ICalendar::DAY_OF_MONTH, -DAYS_PER_WEEK); } else { firstDay->Add(ICalendar::DAY_OF_MONTH, DAYS_PER_WEEK); } SetMonthDisplayed(firstDay); } } mPreviousScrollPosition = currScroll; mPreviousScrollState = mCurrentScrollState; } void CalendarView::LegacyCalendarViewDelegate::SetMonthDisplayed( /* [in] */ ICalendar* calendar) { calendar->Get(ICalendar::MONTH, &mCurrentMonthDisplayed); mAdapter->SetFocusMonth(mCurrentMonthDisplayed); Int32 flags = IDateUtils::FORMAT_SHOW_DATE | IDateUtils::FORMAT_NO_MONTH_DAY | IDateUtils::FORMAT_SHOW_YEAR; Int64 millis = 0; calendar->GetTimeInMillis(&millis); String newMonthName = DateUtils::FormatDateRange(mContext, millis, millis, flags); mMonthName->SetText(CoreUtils::Convert(newMonthName)); IView::Probe(mMonthName)->Invalidate(); } Int32 CalendarView::LegacyCalendarViewDelegate::GetWeeksSinceMinDate( /* [in] */ ICalendar* date) { Boolean bMin = FALSE; if ((date->IsBefore(mMinDate, &bMin), bMin)) { // throw new IllegalArgumentException("fromDate: " + mMinDate.getTime() // + " does not precede toDate: " + date.getTime()); return -1; } Int64 mils = 0, minMils = 0; date->GetTimeInMillis(&mils); mMinDate->GetTimeInMillis(&minMils); AutoPtr<ITimeZone> tz, minTz; date->GetTimeZone((ITimeZone**)&tz); mMinDate->GetTimeZone((ITimeZone**)&minTz); Int32 off = 0, minOff = 0; tz->GetOffset(mils, &off); minTz->GetOffset(minMils, &minOff); Int64 endTimeMillis = mils + off; Int64 startTimeMillis = minMils + minOff; Int32 dw = 0; mMinDate->Get(ICalendar::DAY_OF_WEEK, &dw); Int64 dayOffsetMillis = (dw - mFirstDayOfWeek) * MILLIS_IN_DAY; return (Int32) ((endTimeMillis - startTimeMillis + dayOffsetMillis) / MILLIS_IN_WEEK); } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate::ScrollStateRunnable:: //======================================================================================== CAR_INTERFACE_IMPL(CalendarView::LegacyCalendarViewDelegate::ScrollStateRunnable, Object, IRunnable) CalendarView::LegacyCalendarViewDelegate::ScrollStateRunnable::ScrollStateRunnable( /* [in] */ LegacyCalendarViewDelegate* host) : mNewState(0) , mHost(host) {} void CalendarView::LegacyCalendarViewDelegate::ScrollStateRunnable::DoScrollStateChange( /* [in] */ IAbsListView* view, /* [in] */ Int32 scrollState) { mView = view; mNewState = scrollState; IView* delegator = IView::Probe(mHost->mDelegator); Boolean res; delegator->RemoveCallbacks(this, &res); delegator->PostDelayed(this, SCROLL_CHANGE_DELAY, &res); } ECode CalendarView::LegacyCalendarViewDelegate::ScrollStateRunnable::Run() { mHost->mCurrentScrollState = mNewState; // Fix the position after a scroll or a fling ends if (mNewState == IAbsListViewOnScrollListener::SCROLL_STATE_IDLE && mHost->mPreviousScrollState != IAbsListViewOnScrollListener::SCROLL_STATE_IDLE) { AutoPtr<IView> child; IViewGroup::Probe(mView)->GetChildAt(0, (IView**)&child); if (child == NULL) { // The view is no longer visible, just return return NOERROR; } Int32 b = 0; child->GetBottom(&b); Int32 dist = b - mHost->mListScrollTopOffset; if (dist > mHost->mListScrollTopOffset) { if (mHost->mIsScrollingUp) { Int32 h = 0; child->GetHeight(&h); mView->SmoothScrollBy(dist - h, ADJUSTMENT_SCROLL_DURATION); } else { mView->SmoothScrollBy(dist, ADJUSTMENT_SCROLL_DURATION); } } } mHost->mPreviousScrollState = mNewState; return NOERROR; } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate::WeeksAdapter:: //======================================================================================== CAR_INTERFACE_IMPL(CalendarView::LegacyCalendarViewDelegate::WeeksAdapter, BaseAdapter, IViewOnTouchListener) CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::WeeksAdapter( /* [in] */ IContext* context, /* [in] */ LegacyCalendarViewDelegate* host) : mSelectedWeek(0) , mFocusedMonth(0) , mTotalWeekCount(0) , mHost(host) { AutoPtr<ICalendarHelper> hlp; CCalendarHelper::AcquireSingleton((ICalendarHelper**)&hlp); hlp->GetInstance((ICalendar**)&mSelectedDate); mHost->mContext = context; AutoPtr<CalendarGestureListener> p = new CalendarGestureListener(); CGestureDetector::New(mHost->mContext, p, (IGestureDetector**)&mGestureDetector); Init(); } void CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::Init() { mSelectedWeek = mHost->GetWeeksSinceMinDate(mSelectedDate); mTotalWeekCount = mHost->GetWeeksSinceMinDate(mHost->mMaxDate); Int32 min = 0, max = 0; mHost->mMinDate->Get(ICalendar::DAY_OF_WEEK, &min); mHost->mMaxDate->Get(ICalendar::DAY_OF_WEEK, &max); if (min != mHost->mFirstDayOfWeek || max != mHost->mFirstDayOfWeek) { mTotalWeekCount++; } NotifyDataSetChanged(); } void CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::SetSelectedDay( /* [in] */ ICalendar* selectedDay) { Int32 dfy = 0, mDfy = 0, y = 0, mY = 0; selectedDay->Get(ICalendar::DAY_OF_YEAR, &dfy); mSelectedDate->Get(ICalendar::DAY_OF_YEAR, &mDfy); selectedDay->Get(ICalendar::YEAR, &y); mSelectedDate->Get(ICalendar::YEAR, &mY); if (dfy == mDfy && y == mY) { return; } Int64 mils = 0; selectedDay->GetTimeInMillis(&mils); mSelectedDate->SetTimeInMillis(mils); mSelectedWeek = mHost->GetWeeksSinceMinDate(mSelectedDate); mSelectedDate->Get(ICalendar::MONTH, &mFocusedMonth); NotifyDataSetChanged(); } AutoPtr<ICalendar> CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::GetSelectedDay() { return mSelectedDate; } ECode CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::GetCount( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) *result = mTotalWeekCount; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::GetItem( /* [in] */ Int32 position, /* [out] */ IInterface** result) { VALIDATE_NOT_NULL(result) *result = NULL; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::GetItemId( /* [in] */ Int32 position, /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) *result = position; return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::GetView( /* [in] */ Int32 position, /* [in] */ IView* convertView, /* [in] */ IViewGroup* parent, /* [out] */ IView** result) { VALIDATE_NOT_NULL(result) AutoPtr<WeekView> weekView; if (convertView != NULL) { weekView = (WeekView*)convertView; } else { weekView = new WeekView(mHost->mContext, mHost); AutoPtr<IViewGroupLayoutParams> params; CAbsListViewLayoutParams::New(IViewGroupLayoutParams::WRAP_CONTENT, IViewGroupLayoutParams::WRAP_CONTENT, (IViewGroupLayoutParams**)&params); weekView->SetLayoutParams(params); weekView->SetClickable(TRUE); weekView->SetOnTouchListener(this); } Int32 dfw = 0; Int32 selectedWeekDay = (mSelectedWeek == position) ? (mSelectedDate->Get(ICalendar::DAY_OF_WEEK, &dfw), dfw) : -1; weekView->Init(position, selectedWeekDay, mFocusedMonth); *result = weekView; REFCOUNT_ADD(*result) return NOERROR; } void CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::SetFocusMonth( /* [in] */ Int32 month) { if (mFocusedMonth == month) { return; } mFocusedMonth = month; NotifyDataSetChanged(); } ECode CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::OnTouch( /* [in] */ IView* v, /* [in] */ IMotionEvent* event, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) Boolean bEnbl = FALSE, bTouch = FALSE; if ((IView::Probe(mHost->mListView)->IsEnabled(&bEnbl), bEnbl) && (mGestureDetector->OnTouchEvent(event, &bTouch), bTouch)) { AutoPtr<WeekView> weekView = (WeekView*)v; // if we cannot find a day for the given location we are done Float x = 0.f; event->GetX(&x); if (!weekView->GetDayFromLocation(x, mHost->mTempDate)) { *result = TRUE; return NOERROR; } // it is possible that the touched day is outside the valid range // we draw whole weeks but range end can fall not on the week end Boolean bIsBf = FALSE, bIsAf = FALSE; if ((mHost->mTempDate->IsBefore(mHost->mMinDate, &bIsBf), bIsBf) || (mHost->mTempDate->IsAfter(mHost->mMaxDate, &bIsAf), bIsAf)) { *result = TRUE; return NOERROR; } OnDateTapped(mHost->mTempDate); *result = TRUE; return NOERROR; } *result = FALSE; return NOERROR; } void CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::OnDateTapped( /* [in] */ ICalendar* day) { SetSelectedDay(day); mHost->SetMonthDisplayed(day); } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::CalendarGestureListener:: //======================================================================================== ECode CalendarView::LegacyCalendarViewDelegate::WeeksAdapter::CalendarGestureListener::OnSingleTapUp( /* [in] */ IMotionEvent* e, /* [out] */ Boolean* res) { VALIDATE_NOT_NULL(res) *res = TRUE; return NOERROR; } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate::WeekView:: //======================================================================================== CalendarView::LegacyCalendarViewDelegate::WeekView::WeekView( /* [in] */ IContext* context, /* [in] */ LegacyCalendarViewDelegate* host) : mHasFocusedDay(FALSE) , mHasUnfocusedDay(FALSE) , mMonthOfFirstWeekDay(-1) , mLastWeekDayMonth(-1) , mWeek(-1) , mWidth(0) , mHeight(0) , mHasSelectedDay(FALSE) , mSelectedDay(-1) , mNumCells(0) , mSelectedLeft(-1) , mSelectedRight(-1) , mHost(host) { View::constructor(context); CRect::New((IRect**)&mTempRect); CPaint::New((IPaint**)&mDrawPaint); CPaint::New((IPaint**)&mMonthNumDrawPaint); // Sets up any standard paints that will be used InitilaizePaints(); } void CalendarView::LegacyCalendarViewDelegate::WeekView::Init( /* [in] */ Int32 weekNumber, /* [in] */ Int32 selectedWeekDay, /* [in] */ Int32 focusedMonth) { mSelectedDay = selectedWeekDay; mHasSelectedDay = mSelectedDay != -1; mNumCells = mHost->mShowWeekNumber ? mHost->mDaysPerWeek + 1 : mHost->mDaysPerWeek; mWeek = weekNumber; Int64 mils = 0; mHost->mMinDate->GetTimeInMillis(&mils); mHost->mTempDate->SetTimeInMillis(mils); mHost->mTempDate->Add(ICalendar::WEEK_OF_YEAR, mWeek); mHost->mTempDate->SetFirstDayOfWeek(mHost->mFirstDayOfWeek); // Allocate space for caching the day numbers and focus values mDayNumbers = ArrayOf<String>::Alloc(mNumCells); mFocusDay = ArrayOf<Boolean>::Alloc(mNumCells); // If we're showing the week number calculate it based on Monday Int32 i = 0; if (mHost->mShowWeekNumber) { AutoPtr<ILocaleHelper> hlp; CLocaleHelper::AcquireSingleton((ILocaleHelper**)&hlp); AutoPtr<ILocale> loc; hlp->GetDefault((ILocale**)&loc); Int32 wy = 0; mHost->mTempDate->Get(ICalendar::WEEK_OF_YEAR, &wy); AutoPtr<ArrayOf<IInterface*> > arr = ArrayOf<IInterface*>::Alloc(1); arr->Set(0, CoreUtils::Convert(wy)); (*mDayNumbers)[0] = StringUtils::Format(loc, String("%d"), arr); i++; } // Now adjust our starting day based on the start day of the week Int32 dw = 0; mHost->mTempDate->Get(ICalendar::DAY_OF_WEEK, &dw); Int32 diff = mHost->mFirstDayOfWeek - dw; mHost->mTempDate->Add(ICalendar::DAY_OF_MONTH, diff); AutoPtr<IInterface> obj; ICloneable::Probe(mHost->mTempDate)->Clone((IInterface**)&obj); mFirstDay = ICalendar::Probe(obj); mHost->mTempDate->Get(ICalendar::MONTH, &mMonthOfFirstWeekDay); mHasUnfocusedDay = TRUE; for (; i < mNumCells; i++) { Int32 m = 0; mHost->mTempDate->Get(ICalendar::MONTH, &m); Boolean isFocusedDay = (m == focusedMonth); (*mFocusDay)[i] = isFocusedDay; mHasFocusedDay |= isFocusedDay; mHasUnfocusedDay &= !isFocusedDay; // do not draw dates outside the valid range to avoid user confusion Boolean bIsBf = FALSE, bIsAf = FALSE; if ((mHost->mTempDate->IsBefore(mHost->mMinDate, &bIsBf), bIsBf) || (mHost->mTempDate->IsAfter(mHost->mMaxDate, &bIsAf), bIsAf)) { (*mDayNumbers)[i] = ""; } else { AutoPtr<ILocaleHelper> hlp; CLocaleHelper::AcquireSingleton((ILocaleHelper**)&hlp); AutoPtr<ILocale> loc; hlp->GetDefault((ILocale**)&loc); Int32 m = 0; mHost->mTempDate->Get(ICalendar::DAY_OF_MONTH, &m); AutoPtr<ArrayOf<IInterface*> > arr = ArrayOf<IInterface*>::Alloc(1); arr->Set(0, CoreUtils::Convert(m)); (*mDayNumbers)[i] = StringUtils::Format(loc, String("%d"), arr); } mHost->mTempDate->Add(ICalendar::DAY_OF_MONTH, 1); } // We do one extra add at the end of the loop, if that pushed us to // new month undo it Int32 dm = 0; mHost->mTempDate->Get(ICalendar::DAY_OF_MONTH, &dm); if (dm == 1) { mHost->mTempDate->Add(ICalendar::DAY_OF_MONTH, -1); } mHost->mTempDate->Get(ICalendar::MONTH, &mLastWeekDayMonth); UpdateSelectionPositions(); } void CalendarView::LegacyCalendarViewDelegate::WeekView::InitilaizePaints() { mDrawPaint->SetFakeBoldText(FALSE); mDrawPaint->SetAntiAlias(TRUE); mDrawPaint->SetStyle(PaintStyle_FILL); mMonthNumDrawPaint->SetFakeBoldText(TRUE); mMonthNumDrawPaint->SetAntiAlias(TRUE); mMonthNumDrawPaint->SetStyle(PaintStyle_FILL); mMonthNumDrawPaint->SetTextAlign(PaintAlign_CENTER); mMonthNumDrawPaint->SetTextSize((Float)(mHost->mDateTextSize)); } Int32 CalendarView::LegacyCalendarViewDelegate::WeekView::GetMonthOfFirstWeekDay() { return mMonthOfFirstWeekDay; } Int32 CalendarView::LegacyCalendarViewDelegate::WeekView::GetMonthOfLastWeekDay() { return mLastWeekDayMonth; } AutoPtr<ICalendar> CalendarView::LegacyCalendarViewDelegate::WeekView::GetFirstDay() { return mFirstDay; } Boolean CalendarView::LegacyCalendarViewDelegate::WeekView::GetDayFromLocation( /* [in] */ float x, /* [in] */ ICalendar* outCalendar) { Boolean isLayoutRtl = FALSE; IsLayoutRtl(&isLayoutRtl); Int32 start = 0; Int32 end = 0; if (isLayoutRtl) { start = 0; end = mHost->mShowWeekNumber ? mWidth - mWidth / mNumCells : mWidth; } else { start = mHost->mShowWeekNumber ? mWidth / mNumCells : 0; end = mWidth; } if (x < start || x > end) { outCalendar->Clear(); return FALSE; } // Selection is (x - start) / (pixels/day) which is (x - start) * day / pixels Int32 dayPosition = (Int32) ((x - start) * mHost->mDaysPerWeek / (end - start)); if (isLayoutRtl) { dayPosition = mHost->mDaysPerWeek - 1 - dayPosition; } Int64 mils = 0; mFirstDay->GetTimeInMillis(&mils); outCalendar->SetTimeInMillis(mils); outCalendar->Add(ICalendar::DAY_OF_MONTH, dayPosition); return TRUE; } void CalendarView::LegacyCalendarViewDelegate::WeekView::OnDraw( /* [in] */ ICanvas* canvas) { DrawBackground(canvas); DrawWeekNumbersAndDates(canvas); DrawWeekSeparators(canvas); DrawSelectedDateVerticalBars(canvas); } void CalendarView::LegacyCalendarViewDelegate::WeekView::DrawBackground( /* [in] */ ICanvas* canvas) { if (!mHasSelectedDay) { return; } mDrawPaint->SetColor(mHost->mSelectedWeekBackgroundColor); AutoPtr<CRect> ctr = (CRect*)mTempRect.Get(); ctr->mTop = mHost->mWeekSeperatorLineWidth; ctr->mBottom = mHeight; Boolean isLayoutRtl = FALSE; IsLayoutRtl(&isLayoutRtl); if (isLayoutRtl) { ctr->mLeft = 0; ctr->mRight = mSelectedLeft - 2; } else { ctr->mLeft = mHost->mShowWeekNumber ? mWidth / mNumCells : 0; ctr->mRight = mSelectedLeft - 2; } canvas->DrawRect(mTempRect, mDrawPaint); if (isLayoutRtl) { ctr->mLeft = mSelectedRight + 3; ctr->mRight = mHost->mShowWeekNumber ? mWidth - mWidth / mNumCells : mWidth; } else { ctr->mLeft = mSelectedRight + 3; ctr->mRight = mWidth; } canvas->DrawRect(mTempRect, mDrawPaint); } void CalendarView::LegacyCalendarViewDelegate::WeekView::DrawWeekNumbersAndDates( /* [in] */ ICanvas* canvas) { float textHeight = 0; mDrawPaint->GetTextSize(&textHeight); Int32 y = (Int32) ((mHeight + textHeight) / 2) - mHost->mWeekSeperatorLineWidth; Int32 nDays = mNumCells; Int32 divisor = 2 * nDays; mDrawPaint->SetTextAlign(PaintAlign_CENTER); mDrawPaint->SetTextSize(mHost->mDateTextSize); Int32 i = 0; Boolean bIsLo = FALSE; if ((IsLayoutRtl(&bIsLo), bIsLo)) { for (; i < nDays - 1; i++) { mMonthNumDrawPaint->SetColor((*mFocusDay)[i] ? mHost->mFocusedMonthDateColor : mHost->mUnfocusedMonthDateColor); Int32 x = (2 * i + 1) * mWidth / divisor; canvas->DrawText((*mDayNumbers)[nDays - 1 - i], x, y, mMonthNumDrawPaint); } if (mHost->mShowWeekNumber) { mDrawPaint->SetColor(mHost->mWeekNumberColor); Int32 x = mWidth - mWidth / divisor; canvas->DrawText((*mDayNumbers)[0], x, y, mDrawPaint); } } else { if (mHost->mShowWeekNumber) { mDrawPaint->SetColor(mHost->mWeekNumberColor); Int32 x = mWidth / divisor; canvas->DrawText((*mDayNumbers)[0], x, y, mDrawPaint); i++; } for (; i < nDays; i++) { mMonthNumDrawPaint->SetColor((*mFocusDay)[i] ? mHost->mFocusedMonthDateColor : mHost->mUnfocusedMonthDateColor); Int32 x = (2 * i + 1) * mWidth / divisor; canvas->DrawText((*mDayNumbers)[i], x, y, mMonthNumDrawPaint); } } } void CalendarView::LegacyCalendarViewDelegate::WeekView::DrawWeekSeparators( /* [in] */ ICanvas* canvas) { // If it is the topmost fully visible child do not draw separator line Int32 firstFullyVisiblePosition = 0; IAdapterView::Probe(mHost->mListView)->GetFirstVisiblePosition(&firstFullyVisiblePosition); AutoPtr<IView> v; IViewGroup::Probe(mHost->mListView)->GetChildAt(0, (IView**)&v); Int32 t = 0; v->GetTop(&t); if (t < 0) { firstFullyVisiblePosition++; } if (firstFullyVisiblePosition == mWeek) { return; } mDrawPaint->SetColor(mHost->mWeekSeparatorLineColor); mDrawPaint->SetStrokeWidth(mHost->mWeekSeperatorLineWidth); float startX = 0.f; float stopX = 0.f; Boolean bIsLo = FALSE; if ((IsLayoutRtl(&bIsLo), bIsLo)) { startX = 0; stopX = mHost->mShowWeekNumber ? mWidth - mWidth / mNumCells : mWidth; } else { startX = mHost->mShowWeekNumber ? mWidth / mNumCells : 0; stopX = mWidth; } canvas->DrawLine(startX, 0, stopX, 0, mDrawPaint); } void CalendarView::LegacyCalendarViewDelegate::WeekView::DrawSelectedDateVerticalBars( /* [in] */ ICanvas* canvas) { if (!mHasSelectedDay) { return; } mHost->mSelectedDateVerticalBar->SetBounds( mSelectedLeft - mHost->mSelectedDateVerticalBarWidth / 2, mHost->mWeekSeperatorLineWidth, mSelectedLeft + mHost->mSelectedDateVerticalBarWidth / 2, mHeight); mHost->mSelectedDateVerticalBar->Draw(canvas); mHost->mSelectedDateVerticalBar->SetBounds( mSelectedRight - mHost->mSelectedDateVerticalBarWidth / 2, mHost->mWeekSeperatorLineWidth, mSelectedRight + mHost->mSelectedDateVerticalBarWidth / 2, mHeight); mHost->mSelectedDateVerticalBar->Draw(canvas); } ECode CalendarView::LegacyCalendarViewDelegate::WeekView::OnSizeChanged( /* [in] */ Int32 w, /* [in] */ Int32 h, /* [in] */ Int32 oldw, /* [in] */ Int32 oldh) { mWidth = w; UpdateSelectionPositions(); return NOERROR; } void CalendarView::LegacyCalendarViewDelegate::WeekView::UpdateSelectionPositions() { if (mHasSelectedDay) { Boolean isLayoutRtl = FALSE; IsLayoutRtl(&isLayoutRtl); Int32 selectedPosition = mSelectedDay - mHost->mFirstDayOfWeek; if (selectedPosition < 0) { selectedPosition += 7; } if (mHost->mShowWeekNumber && !isLayoutRtl) { selectedPosition++; } if (isLayoutRtl) { mSelectedLeft = (mHost->mDaysPerWeek - 1 - selectedPosition) * mWidth / mNumCells; } else { mSelectedLeft = selectedPosition * mWidth / mNumCells; } mSelectedRight = mSelectedLeft + mWidth / mNumCells; } } ECode CalendarView::LegacyCalendarViewDelegate::WeekView::OnMeasure( /* [in] */ Int32 widthMeasureSpec, /* [in] */ Int32 heightMeasureSpec) { IView* view = IView::Probe(mHost->mListView); Int32 h = 0, t = 0, b = 0; view->GetHeight(&h); view->GetPaddingTop(&t); view->GetPaddingBottom(&b); mHeight = (h - t - b) / mHost->mShownWeekCount; SetMeasuredDimension(MeasureSpec::GetSize(widthMeasureSpec), mHeight); return NOERROR; } //======================================================================================== // CalendarView::LegacyCalendarViewDelegate::_DataSetObserver //======================================================================================== CalendarView::LegacyCalendarViewDelegate::_DataSetObserver::_DataSetObserver( /* [in] */ LegacyCalendarViewDelegate* host) : mHost(host) {} ECode CalendarView::LegacyCalendarViewDelegate::_DataSetObserver::OnChanged() { if (mHost->mOnDateChangeListener != NULL) { AutoPtr<ICalendar> selectedDay = mHost->mAdapter->GetSelectedDay(); Int32 y = 0, m = 0, d = 0; selectedDay->Get(ICalendar::YEAR, &y); selectedDay->Get(ICalendar::MONTH, &m); selectedDay->Get(ICalendar::DAY_OF_MONTH, &d); mHost->mOnDateChangeListener->OnSelectedDayChange(mHost->mDelegator, y, m, d); } return NOERROR; } ECode CalendarView::LegacyCalendarViewDelegate::_DataSetObserver::OnInvalidated() { return NOERROR; } //======================================================================================== // CalendarView:: //======================================================================================== const String CalendarView::TAG("CalendarView"); CAR_INTERFACE_IMPL(CalendarView, FrameLayout, ICalendarView) CalendarView::CalendarView() {} CalendarView::~CalendarView() {} ECode CalendarView::constructor( /* [in] */ IContext* context) { return constructor(context, NULL); } ECode CalendarView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs) { return constructor(context, attrs, R::attr::calendarViewStyle); } ECode CalendarView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr) { return constructor(context, attrs, defStyleAttr, 0); } ECode CalendarView::constructor( /* [in] */ IContext* context, /* [in] */ IAttributeSet* attrs, /* [in] */ Int32 defStyleAttr, /* [in] */ Int32 defStyleRes) { FrameLayout::constructor(context, attrs, defStyleAttr, defStyleRes); mDelegate = new LegacyCalendarViewDelegate(this, context, attrs, defStyleAttr, defStyleRes); return NOERROR; } ECode CalendarView::SetShownWeekCount( /* [in] */ Int32 count) { return mDelegate->SetShownWeekCount(count); } ECode CalendarView::GetShownWeekCount( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetShownWeekCount(result); } ECode CalendarView::SetSelectedWeekBackgroundColor( /* [in] */ Int32 color) { return mDelegate->SetSelectedWeekBackgroundColor(color); } ECode CalendarView::GetSelectedWeekBackgroundColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetSelectedWeekBackgroundColor(result); } ECode CalendarView::SetFocusedMonthDateColor( /* [in] */ Int32 color) { return mDelegate->SetFocusedMonthDateColor(color); } ECode CalendarView::GetFocusedMonthDateColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetFocusedMonthDateColor(result); } ECode CalendarView::SetUnfocusedMonthDateColor( /* [in] */ Int32 color) { return mDelegate->SetUnfocusedMonthDateColor(color); } ECode CalendarView::GetUnfocusedMonthDateColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetUnfocusedMonthDateColor(result); } ECode CalendarView::SetWeekNumberColor( /* [in] */ Int32 color) { return mDelegate->SetWeekNumberColor(color); } ECode CalendarView::GetWeekNumberColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetWeekNumberColor(result); } ECode CalendarView::SetWeekSeparatorLineColor( /* [in] */ Int32 color) { return mDelegate->SetWeekSeparatorLineColor(color); } ECode CalendarView::GetWeekSeparatorLineColor( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetWeekSeparatorLineColor(result); } ECode CalendarView::SetSelectedDateVerticalBar( /* [in] */ Int32 resourceId) { return mDelegate->SetSelectedDateVerticalBar(resourceId); } ECode CalendarView::SetSelectedDateVerticalBar( /* [in] */ IDrawable* drawable) { return mDelegate->SetSelectedDateVerticalBar(drawable); } ECode CalendarView::GetSelectedDateVerticalBar( /* [out] */ IDrawable** result) { VALIDATE_NOT_NULL(result) return mDelegate->GetSelectedDateVerticalBar(result); } ECode CalendarView::SetWeekDayTextAppearance( /* [in] */ Int32 resourceId) { return mDelegate->SetWeekDayTextAppearance(resourceId); } ECode CalendarView::GetWeekDayTextAppearance( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetWeekDayTextAppearance(result); } ECode CalendarView::SetDateTextAppearance( /* [in] */ Int32 resourceId) { return mDelegate->SetDateTextAppearance(resourceId); } ECode CalendarView::GetDateTextAppearance( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetDateTextAppearance(result); } ECode CalendarView::SetEnabled( /* [in] */ Boolean enabled) { return mDelegate->SetEnabled(enabled); } ECode CalendarView::IsEnabled( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) return mDelegate->IsEnabled(result); } ECode CalendarView::GetMinDate( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetMinDate(result); } ECode CalendarView::SetMinDate( /* [in] */ Int64 minDate) { return mDelegate->SetMinDate(minDate); } ECode CalendarView::GetMaxDate( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetMaxDate(result); } ECode CalendarView::SetMaxDate( /* [in] */ Int64 maxDate) { return mDelegate->SetMaxDate(maxDate); } ECode CalendarView::SetShowWeekNumber( /* [in] */ Boolean showWeekNumber) { return mDelegate->SetShowWeekNumber(showWeekNumber); } ECode CalendarView::GetShowWeekNumber( /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetShowWeekNumber(result); } ECode CalendarView::GetFirstDayOfWeek( /* [out] */ Int32* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetFirstDayOfWeek(result); } ECode CalendarView::SetFirstDayOfWeek( /* [in] */ Int32 firstDayOfWeek) { return mDelegate->SetFirstDayOfWeek(firstDayOfWeek); } ECode CalendarView::SetOnDateChangeListener( /* [in] */ IOnDateChangeListener* listener) { return mDelegate->SetOnDateChangeListener(listener); } ECode CalendarView::GetDate( /* [out] */ Int64* result) { VALIDATE_NOT_NULL(result) return mDelegate->GetDate(result); } ECode CalendarView::SetDate( /* [in] */ Int64 date) { return mDelegate->SetDate(date); } ECode CalendarView::SetDate( /* [in] */ Int64 date, /* [in] */ Boolean animate, /* [in] */ Boolean center) { return mDelegate->SetDate(date, animate, center); } ECode CalendarView::OnConfigurationChanged( /* [in] */ IConfiguration* newConfig) { FrameLayout::OnConfigurationChanged(newConfig); mDelegate->OnConfigurationChanged(newConfig); return NOERROR; } ECode CalendarView::OnInitializeAccessibilityEvent( /* [in] */ IAccessibilityEvent* event) { FrameLayout::OnInitializeAccessibilityEvent(event); return mDelegate->OnInitializeAccessibilityEvent(event); } ECode CalendarView::OnInitializeAccessibilityNodeInfo( /* [in] */ IAccessibilityNodeInfo* info) { FrameLayout::OnInitializeAccessibilityNodeInfo(info); return mDelegate->OnInitializeAccessibilityNodeInfo(info); } } //namespace Widget } //namespace Droid } //namespace Elastos
33.105947
119
0.66091
jingcao80
de1856ea478f66b6f47989f7c6f155c6fd50efce
156
cpp
C++
codeforces/656A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/656A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/656A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { long long a,res=1; cin>>a; for(int i=1; i<=a; i++)res*=2; cout<< res<<endl;; return 0; }
13
31
0.576923
Shisir
de1bb525850a824194013273eabe3229005d69fd
2,784
cc
C++
unit_test/serializer.cc
yannstad/reinforcement_learning
29e5a4f786ed81ed2c9bc64ae6b14bdbf18b99e4
[ "MIT" ]
63
2018-10-22T17:11:02.000Z
2021-12-08T17:26:41.000Z
unit_test/serializer.cc
yannstad/reinforcement_learning
29e5a4f786ed81ed2c9bc64ae6b14bdbf18b99e4
[ "MIT" ]
160
2018-10-09T02:34:57.000Z
2022-03-31T15:43:48.000Z
unit_test/serializer.cc
yannstad/reinforcement_learning
29e5a4f786ed81ed2c9bc64ae6b14bdbf18b99e4
[ "MIT" ]
36
2018-10-08T21:44:05.000Z
2022-03-22T16:20:03.000Z
#define BOOST_TEST_DYN_LINK #ifdef STAND_ALONE # define BOOST_TEST_MODULE Main #endif #include <boost/test/unit_test.hpp> #include "ranking_event.h" #include "utility/data_buffer.h" #include "logger/flatbuffer_allocator.h" using namespace reinforcement_learning; using IBuffer = utility::data_buffer; template<typename T> struct FBSerial { }; template<> struct FBSerial<ranking_event> { using Type = RankingEvent; using OffsetVector = std::vector<flatbuffers::Offset<Type>>; using BatchBuilder = messages::RankingEventBatchBuilder; static void serialize(ranking_event& evt, OffsetVector& offsets, flatbuffers::FlatBufferBuilder& builder) { const auto event_id_offset = builder.CreateString(evt.get_event_id()); const auto action_ids_vector_offset = builder.CreateVector(evt.get_action_ids()); const auto probabilities_vector_offset = builder.CreateVector(evt.get_probabilities()); const auto context_offset = builder.CreateVector(evt.get_context()); const auto model_id_offset = builder.CreateString(evt.get_model_id()); const auto offset = messages::CreateRankingEvent(builder, event_id_offset, evt.get_defered_action(), action_ids_vector_offset, context_offset, probabilities_vector_offset, model_id_offset); offsets.push_back(offset); } }; template <typename Event> struct FBCollectionSerializer { using Serial = FBSerial<Event>; FBCollectionSerializer(IBuffer& buffer) : _builder{ buffer.capacity(),&_allocator }, _allocator(buffer), _buffer(buffer) {} void add(Event& evt) { Serial::serialize(evt, _event_offsets, _builder); } uint64_t size() const { return _builder.GetSize(); } void finalize() { auto event_offsets = _builder.CreateVector(_event_offsets); typename Serial::BatchBuilder batch_builder(_builder); batch_builder.add_Events(event_offsets); auto orc = batch_builder.Finish(); _builder.Finish(orc); _buffer.set_begin(_builder.GetBufferPointer(), _builder.GetSize()); } typename Serial::OffsetVector _event_offsets; flatbuffers::FlatBufferBuilder _builder; flatbuffer_allocator _allocator; IBuffer& _buffer; }; struct ISender { void send(IBuffer&& buffer) {} }; template<typename Event, template<typename>class Serializer> void DrainQueue() { IBuffer buffer; const uint64_t high_water_mark = 1024 * 100; Serializer<Event> serializer(buffer); ISender sender; Event rank; while (serializer.size() < high_water_mark) { serializer.add(rank); } serializer.finalize(); sender.send(std::move(buffer)); } BOOST_AUTO_TEST_CASE(new_data_buffer_is_empty) { DrainQueue<ranking_event, FBCollectionSerializer>(); // DrainQueue<outcome_event, FBCollectionSerializer>(); // won't compile because specialization does not exist }
29.935484
193
0.761135
yannstad
de1c1a9cd315d35bd625c7f15bde751057a7371d
2,918
cpp
C++
kinesis-video-pic/src/mkvgen/tst/AudioCpdParserTest.cpp
nsharma098/amazon-kinesis-video-streams-producer-sdk-cpp
e3b63724494b16e00079027ccc232e8914731d66
[ "Apache-2.0" ]
1
2021-04-29T08:08:10.000Z
2021-04-29T08:08:10.000Z
kinesis-video-pic/src/mkvgen/tst/AudioCpdParserTest.cpp
jonmnick/aws-kinesis-cpp-sdk
f7d4a0fa67081780808f5b1e4cc8b97697953a72
[ "Apache-2.0" ]
null
null
null
kinesis-video-pic/src/mkvgen/tst/AudioCpdParserTest.cpp
jonmnick/aws-kinesis-cpp-sdk
f7d4a0fa67081780808f5b1e4cc8b97697953a72
[ "Apache-2.0" ]
null
null
null
#include "MkvgenTestFixture.h" class AudioCpdParserTest : public MkvgenTestBase { }; TEST_F(AudioCpdParserTest, audioCpdParser_InvalidInput) { BYTE cpd[] = {0x00, 0x00}; UINT32 cpdSize = 2; DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(NULL, cpdSize, &samplingFrequency, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, 0, &samplingFrequency, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, MIN_AAC_CPD_SIZE - 1, &samplingFrequency, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, NULL)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, NULL)); } TEST_F(AudioCpdParserTest, audioCpdParser_AacCpd) { BYTE cpd[] = {0x12, 0x10}; UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, &channelConfig)); EXPECT_EQ((DOUBLE) 44100, samplingFrequency); EXPECT_EQ(2, channelConfig); } TEST_F(AudioCpdParserTest, audioCpdParser_InvalidCpd) { BYTE cpd[] = {0x12, 0x10}; UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD, getSamplingFreqAndChannelFromAacCpd(NULL, 2, &samplingFrequency, &channelConfig)); EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD, getSamplingFreqAndChannelFromAacCpd(NULL, 0, &samplingFrequency, &channelConfig)); EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD, getSamplingFreqAndChannelFromAacCpd(cpd, 0, &samplingFrequency, &channelConfig)); EXPECT_EQ(STATUS_NULL_ARG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, NULL)); EXPECT_EQ(STATUS_NULL_ARG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, &channelConfig)); EXPECT_EQ(STATUS_NULL_ARG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, NULL)); } TEST_F(AudioCpdParserTest, audioCpdParser_invalidSamplingFrequencyIndex) { BYTE cpd[] = {0x07, 0x90}; // sampling frequency index is 15 UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD_SAMPLING_FREQUENCY_INDEX, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, &channelConfig)); } TEST_F(AudioCpdParserTest, audioCpdParser_invalidChannelConfig) { BYTE cpd[] = {0x07, 0xc8}; // channel config is 9 UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD_CHANNEL_CONFIG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, &channelConfig)); }
42.911765
154
0.789239
nsharma098
de1e527e8357da26a93b7b50f7bfc04c6d250be5
18,329
cpp
C++
game/server/tfo/npc_monster.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
13
2016-04-05T23:23:16.000Z
2022-03-20T11:06:04.000Z
game/server/tfo/npc_monster.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
null
null
null
game/server/tfo/npc_monster.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
4
2016-04-05T23:23:19.000Z
2021-05-16T05:09:46.000Z
//========= Copyright Bernt Andreas Eide, All rights reserved. ============// // // Purpose: Custom Monster NPC Entity - Allows parsing of unique stuff. Parses npc scripts in resource/data/npc // //=============================================================================// #include "cbase.h" #include "ai_basenpc.h" #include "ai_default.h" #include "ai_schedule.h" #include "ai_hull.h" #include "ai_motor.h" #include "game.h" #include "npc_headcrab.h" #include "npcevent.h" #include "entitylist.h" #include "ai_task.h" #include "activitylist.h" #include "engine/IEngineSound.h" #include "npc_BaseZombie.h" #include "npc_monster.h" #include "filesystem.h" #include <KeyValues.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define BREATH_VOL_MAX 0.6 #define ZOMBIE_ENEMY_BREATHE_DIST 300 // How close we must be to our enemy before we start breathing hard. static const char *pMoanSounds[] = { "Moan1", }; LINK_ENTITY_TO_CLASS( npc_monster, CNPC_Monster ); BEGIN_DATADESC( CNPC_Monster ) DEFINE_FIELD( m_flNextPainSoundTime, FIELD_TIME ), DEFINE_FIELD(m_bCanOpenDoors, FIELD_BOOLEAN), DEFINE_FIELD(m_iMaxHealth, FIELD_INTEGER), DEFINE_FIELD(m_iSkin, FIELD_INTEGER), DEFINE_FIELD(m_iDamage[0], FIELD_INTEGER), DEFINE_FIELD(m_iDamage[1], FIELD_INTEGER), DEFINE_FIELD(m_flAttackRange, FIELD_FLOAT), DEFINE_FIELD(cModel, FIELD_STRING), DEFINE_FIELD(cEntName, FIELD_STRING), DEFINE_FIELD(cSoundScript, FIELD_STRING), DEFINE_FIELD( m_bNearEnemy, FIELD_BOOLEAN ), DEFINE_KEYFIELD( cScript, FIELD_STRING, "Script" ), END_DATADESC() // Force Script: void CNPC_Monster::SetScript( const char *szScript ) { cScript = MAKE_STRING(szScript); } //----------------------------------------------------------------------------- // Purpose: Return a random model in the Models key. //----------------------------------------------------------------------------- const char *CNPC_Monster::GetRandomModel(KeyValues *pkvValues) { const char *szModel = NULL; int iCount = 0, iFind = 0; for (KeyValues *sub = pkvValues->GetFirstSubKey(); sub; sub = sub->GetNextKey()) iCount++; iFind = random->RandomInt(1, iCount); iCount = 0; for (KeyValues *sub = pkvValues->GetFirstSubKey(); sub; sub = sub->GetNextKey()) { iCount++; if (iCount == iFind) { szModel = ReadAndAllocStringValue(pkvValues, sub->GetName()); break; } } return szModel; } //----------------------------------------------------------------------------- // Purpose: Return data about the npc, if found. //----------------------------------------------------------------------------- KeyValues *CNPC_Monster::pkvNPCData( const char *szScript ) { KeyValues *pkvData = new KeyValues( "NPCDATA" ); if ( pkvData->LoadFromFile( filesystem, UTIL_VarArgs( "resource/data/npcs/%s.txt", szScript ), "MOD" ) ) { return pkvData; } pkvData->deleteThis(); return NULL; } //----------------------------------------------------------------------------- // Purpose: Parse data found from npcData keyValue... //----------------------------------------------------------------------------- void CNPC_Monster::ParseNPCScript( const char *szScript ) { // Get our data and make sure it is not NULL... KeyValues *pkvMyNPCData = pkvNPCData(szScript); if (!pkvMyNPCData) { Warning("NPC_MONSTER linked to %s.txt was removed, no such script exist!\n", szScript); UTIL_Remove(this); return; } // Parse our data: KeyValues *pkvInfoField = pkvMyNPCData->FindKey("Info"); KeyValues *pkvModelField = pkvMyNPCData->FindKey("Model"); KeyValues *pkvRandomModelsField = pkvMyNPCData->FindKey("Models"); bool bRandomModel = false; if (pkvInfoField) { cEntName = MAKE_STRING(ReadAndAllocStringValue(pkvInfoField, "Name")); cSoundScript = MAKE_STRING(ReadAndAllocStringValue(pkvInfoField, "SoundScript")); m_iHealth = pkvInfoField->GetInt("Health", 100); m_iDamage[0] = pkvInfoField->GetInt("DamageOneHand", 10); m_iDamage[1] = pkvInfoField->GetInt("DamageBothHands", 10); m_flAttackRange = pkvInfoField->GetFloat("AttackRange", 70.0f); m_iMaxHealth = m_iHealth; m_bCanOpenDoors = ((pkvInfoField->GetInt("CanOpenDoors") >= 1) ? true : false); } if (pkvModelField) { bRandomModel = (!pkvModelField->FindKey("Path")); if (!bRandomModel) cModel = MAKE_STRING(ReadAndAllocStringValue(pkvModelField, "Path")); m_fIsTorso = ((pkvModelField->GetInt("IsTorso") >= 1) ? true : false); if (!strcmp(pkvModelField->GetString("Skin"), "random")) m_iSkin = random->RandomInt(0, pkvModelField->GetInt("MaxSkins")); else m_iSkin = pkvModelField->GetInt("Skin"); SetBloodColor(pkvModelField->GetInt("BloodType")); } if (pkvRandomModelsField && bRandomModel) cModel = MAKE_STRING(GetRandomModel(pkvRandomModelsField)); Precache(); pkvMyNPCData->deleteThis(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::Precache( void ) { PrecacheModel( cModel.ToCStr() ); PrecacheScriptSound( UTIL_VarArgs( "NPC_%s.Die", cSoundScript.ToCStr() ) ); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Idle", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Pain", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Alert", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.FootstepRight", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.FootstepLeft", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Attack", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.FastBreath", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Moan1", cSoundScript.ToCStr())); // Default Zombie Precaching PrecacheScriptSound("Zombie.FootstepRight"); PrecacheScriptSound("Zombie.FootstepLeft"); PrecacheScriptSound("Zombie.ScuffRight"); PrecacheScriptSound("Zombie.ScuffLeft"); PrecacheScriptSound("Zombie.Pain"); PrecacheScriptSound("Zombie.Die"); PrecacheScriptSound("Zombie.Alert"); PrecacheScriptSound("Zombie.Idle"); PrecacheScriptSound("Zombie.Attack"); PrecacheScriptSound("NPC_BaseZombie.Moan1"); PrecacheScriptSound("NPC_BaseZombie.Moan2"); PrecacheScriptSound("NPC_BaseZombie.Moan3"); PrecacheScriptSound("NPC_BaseZombie.Moan4"); PrecacheScriptSound( "Zombie.AttackHit" ); PrecacheScriptSound( "Zombie.AttackMiss" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::Spawn( void ) { ParseNPCScript( cScript.ToCStr() ); m_flLastBloodTrail = gpGlobals->curtime; m_flNextPainSoundTime = 0; m_fIsHeadless = true; AddSpawnFlags( SF_NPC_LONG_RANGE ); m_flFieldOfView = 0.2; CapabilitiesClear(); CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_INNATE_MELEE_ATTACK1 ); BaseClass::Spawn(); } //----------------------------------------------------------------------------- // Purpose: Returns a moan sound for this class of zombie. //----------------------------------------------------------------------------- const char *CNPC_Monster::GetMoanSound( int nSound ) { return UTIL_VarArgs("NPC_%s.%s", cSoundScript.ToCStr(), pMoanSounds[nSound % ARRAYSIZE(pMoanSounds)]); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::StopLoopingSounds( void ) { BaseClass::StopLoopingSounds(); } //----------------------------------------------------------------------------- // Purpose: // Input : info - //----------------------------------------------------------------------------- void CNPC_Monster::Event_Killed( const CTakeDamageInfo &info ) { BaseClass::Event_Killed( info ); } void CNPC_Monster::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator ) { BaseClass::TraceAttack( info, vecDir, ptr, pAccumulator ); } //----------------------------------------------------------------------------- // Purpose: // Input : &inputInfo - // Output : int //----------------------------------------------------------------------------- int CNPC_Monster::OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo ) { return BaseClass::OnTakeDamage_Alive( inputInfo ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CNPC_Monster::MaxYawSpeed( void ) { return BaseClass::MaxYawSpeed(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- Class_T CNPC_Monster::Classify( void ) { return CLASS_ZOMBIE; } //----------------------------------------------------------------------------- // Purpose: // // NOTE: This function is still heavy with common code (found at the bottom). // we should consider moving some into the base class! (sjb) //----------------------------------------------------------------------------- void CNPC_Monster::SetZombieModel( void ) { Hull_t lastHull = GetHullType(); SetModel( cModel.ToCStr() ); if (m_fIsTorso) SetHullType(HULL_TINY); else SetHullType(HULL_HUMAN); SetHullSizeNormal( true ); SetDefaultEyeOffset(); SetActivity( ACT_IDLE ); m_nSkin = m_iSkin; if ( lastHull != GetHullType() ) { if ( VPhysicsGetObject() ) { SetupVPhysicsHull(); } } CollisionProp()->SetSurroundingBoundsType( USE_OBB_COLLISION_BOUNDS ); } //----------------------------------------------------------------------------- // Purpose: Turns off our breath so we can play another vocal sound. // TODO: pass in duration //----------------------------------------------------------------------------- void CNPC_Monster::BreatheOffShort( void ) { } //----------------------------------------------------------------------------- // Purpose: Catches the monster-specific events that occur when tagged animation // frames are played. // Input : pEvent - //----------------------------------------------------------------------------- void CNPC_Monster::HandleAnimEvent( animevent_t *pEvent ) { QAngle pAng; Vector vecDir; if ( pEvent->event == AE_ZOMBIE_ATTACK_RIGHT ) { Vector right, forward; AngleVectors( GetLocalAngles(), &forward, &right, NULL ); right = right * 100; forward = forward * 200; pAng = QAngle(-15, -20, -10); vecDir = (right + forward); ClawAttack(GetClawAttackRange(), m_iDamage[0], pAng, vecDir, ZOMBIE_BLOOD_RIGHT_HAND); return; } if ( pEvent->event == AE_ZOMBIE_ATTACK_LEFT ) { Vector right, forward; AngleVectors( GetLocalAngles(), &forward, &right, NULL ); right = right * -100; forward = forward * 200; vecDir = (right + forward); pAng = QAngle(-15, 20, -10); ClawAttack(GetClawAttackRange(), m_iDamage[0], pAng, vecDir, ZOMBIE_BLOOD_LEFT_HAND); return; } if ( pEvent->event == AE_ZOMBIE_ATTACK_BOTH ) { Vector forward; QAngle qaPunch( 45, random->RandomInt(-5,5), random->RandomInt(-5,5) ); AngleVectors( GetLocalAngles(), &forward ); forward = forward * 200; ClawAttack( GetClawAttackRange(), m_iDamage[1], qaPunch, forward, ZOMBIE_BLOOD_BOTH_HANDS ); return; } BaseClass::HandleAnimEvent( pEvent ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::PrescheduleThink( void ) { bool bNearEnemy = false; if ( GetEnemy() != NULL ) { float flDist = (GetEnemy()->GetAbsOrigin() - GetAbsOrigin()).Length(); if ( flDist < ZOMBIE_ENEMY_BREATHE_DIST ) { bNearEnemy = true; } } if ( bNearEnemy ) { if ( !m_bNearEnemy ) { m_bNearEnemy = true; } } else if ( m_bNearEnemy ) { m_bNearEnemy = false; } BaseClass::PrescheduleThink(); // We're chopped off! And we're moving! Add some blood trail... if (m_fIsTorso && IsMoving() && (m_flLastBloodTrail < gpGlobals->curtime)) { m_flLastBloodTrail = gpGlobals->curtime + 1.0f; // We don't want to spam blood all over the place. trace_t tr; UTIL_TraceLine((GetAbsOrigin() + Vector(0, 0, 50)), (GetAbsOrigin() + Vector(0, 0, -300)), MASK_ALL, this, COLLISION_GROUP_NONE, &tr); UTIL_DecalTrace(&tr, "Blood"); } } //----------------------------------------------------------------------------- // Purpose: Allows for modification of the interrupt mask for the current schedule. // In the most cases the base implementation should be called first. //----------------------------------------------------------------------------- void CNPC_Monster::BuildScheduleTestBits( void ) { BaseClass::BuildScheduleTestBits(); if ( IsCurSchedule( SCHED_CHASE_ENEMY ) ) { SetCustomInterruptCondition( COND_LIGHT_DAMAGE ); SetCustomInterruptCondition( COND_HEAVY_DAMAGE ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CNPC_Monster::SelectFailSchedule( int nFailedSchedule, int nFailedTask, AI_TaskFailureCode_t eTaskFailCode ) { int nSchedule = BaseClass::SelectFailSchedule( nFailedSchedule, nFailedTask, eTaskFailCode ); return nSchedule; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CNPC_Monster::SelectSchedule( void ) { int nSchedule = BaseClass::SelectSchedule(); if ( nSchedule == SCHED_SMALL_FLINCH ) { m_flNextFlinchTime = gpGlobals->curtime + random->RandomFloat( 1, 3 ); } return nSchedule; } //----------------------------------------------------------------------------- // Purpose: // Input : scheduleType - // Output : int //----------------------------------------------------------------------------- int CNPC_Monster::TranslateSchedule( int scheduleType ) { if ( scheduleType == SCHED_COMBAT_FACE && IsUnreachable( GetEnemy() ) ) return SCHED_TAKE_COVER_FROM_ENEMY; return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CNPC_Monster::ShouldPlayIdleSound( void ) { return CAI_BaseNPC::ShouldPlayIdleSound(); } //----------------------------------------------------------------------------- // Purpose: Play a random attack hit sound //----------------------------------------------------------------------------- void CNPC_Monster::AttackHitSound( void ) { EmitSound( "Zombie.AttackHit" ); } //----------------------------------------------------------------------------- // Purpose: Play a random attack miss sound //----------------------------------------------------------------------------- void CNPC_Monster::AttackMissSound( void ) { EmitSound( "Zombie.AttackMiss" ); } //----------------------------------------------------------------------------- // Purpose: Play a random attack sound. //----------------------------------------------------------------------------- void CNPC_Monster::AttackSound( void ) { EmitSound(UTIL_VarArgs("NPC_%s.Attack", cSoundScript.ToCStr())); } //----------------------------------------------------------------------------- // Purpose: Play a random idle sound. //----------------------------------------------------------------------------- void CNPC_Monster::IdleSound( void ) { // HACK: base zombie code calls IdleSound even when not idle! if ( m_NPCState != NPC_STATE_COMBAT ) { BreatheOffShort(); EmitSound(UTIL_VarArgs("NPC_%s.Idle", cSoundScript.ToCStr())); } } //----------------------------------------------------------------------------- // Purpose: Play a random pain sound. //----------------------------------------------------------------------------- void CNPC_Monster::PainSound( const CTakeDamageInfo &info ) { // Don't make pain sounds too often. if ( m_flNextPainSoundTime <= gpGlobals->curtime ) { //BreatheOffShort(); EmitSound(UTIL_VarArgs("NPC_%s.Pain", cSoundScript.ToCStr())); m_flNextPainSoundTime = gpGlobals->curtime + random->RandomFloat( 4.0, 7.0 ); } } void CNPC_Monster::DeathSound(const CTakeDamageInfo &info ) { if ( !( info.GetDamageType() & ( DMG_BLAST | DMG_ALWAYSGIB) ) ) { EmitSound(UTIL_VarArgs("NPC_%s.Die", cSoundScript.ToCStr())); } } //----------------------------------------------------------------------------- // Purpose: Play a random alert sound. //----------------------------------------------------------------------------- void CNPC_Monster::AlertSound( void ) { BreatheOffShort(); EmitSound(UTIL_VarArgs("NPC_%s.Alert", cSoundScript.ToCStr())); } //----------------------------------------------------------------------------- // Purpose: Sound of a footstep //----------------------------------------------------------------------------- void CNPC_Monster::FootstepSound( bool fRightFoot ) { if( fRightFoot ) { EmitSound(UTIL_VarArgs("NPC_%s.FootstepRight", cSoundScript.ToCStr())); } else { EmitSound(UTIL_VarArgs("NPC_%s.FootstepLeft", cSoundScript.ToCStr())); } if( ShouldPlayFootstepMoan() ) { m_flNextMoanSound = gpGlobals->curtime; } } //----------------------------------------------------------------------------- // Purpose: If we don't have any headcrabs to throw, we must close to attack our enemy. //----------------------------------------------------------------------------- bool CNPC_Monster::MustCloseToAttack(void) { return true; } //----------------------------------------------------------------------------- // Purpose: Overloaded so that explosions don't split the poison zombie in twain. //----------------------------------------------------------------------------- bool CNPC_Monster::ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold ) { return false; } int ACT_ZOMBIE_MONSTER_THREAT; AI_BEGIN_CUSTOM_NPC( npc_monster, CNPC_Monster ) DECLARE_ACTIVITY( ACT_ZOMBIE_MONSTER_THREAT ) AI_END_CUSTOM_NPC()
31.171769
136
0.540564
BerntA
de23c456db92799c7cdedb8b84d59f75e6bbe413
843
cpp
C++
matrix/matrix_power.cpp
ShinyaKato/competitive-programming-utils
53ae76cdc427dd816a7a11147d80a172fb16bcc3
[ "Apache-2.0" ]
1
2017-12-16T14:08:49.000Z
2017-12-16T14:08:49.000Z
matrix/matrix_power.cpp
ShinyaKato/competitive-programming-utils
53ae76cdc427dd816a7a11147d80a172fb16bcc3
[ "Apache-2.0" ]
2
2018-07-03T17:19:18.000Z
2018-07-03T17:23:10.000Z
matrix/matrix_power.cpp
ShinyaKato/competitive-programming-utils
53ae76cdc427dd816a7a11147d80a172fb16bcc3
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) #define MOD 1000000007LL using namespace std; typedef long long ll; typedef vector<ll> vec; typedef vector<vec> mat; mat mul(mat &A, mat &B) { mat C(A.size(), vector<ll>(B[0].size())); REP(i, 0, A.size()) REP(j, 0, B[0].size()) REP(k, 0, B.size()) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD; return C; } mat pow(mat A, ll n) { mat B(A.size(), vec(A.size())); REP(i, 0, A.size()) B[i][i] = 1; while(n > 0) { if(n & 1) B = mul(B, A); A = mul(A, A); n >>= 1; } return B; } int main(void) { // example of calculating n-the element of fibonacci mod 10^9 + 7 mat A(2, vec(2)); A[0][0] = 1; A[0][1] = 1; A[1][0] = 1; A[1][1] = 0; REP(i, 0, 20) cout << "fib(" << i << ") = " << pow(A, i)[1][0] << endl; }
24.085714
82
0.487544
ShinyaKato
de277bc9d7ad1f58f4c3022b424e8ff2938a7779
2,589
cpp
C++
NeoOnnx/src/Operators/TransposeOperator.cpp
sergesk/neoml
cca05584ef3d892cb00d23a105bac6674b3d50ef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoOnnx/src/Operators/TransposeOperator.cpp
sergesk/neoml
cca05584ef3d892cb00d23a105bac6674b3d50ef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
NeoOnnx/src/Operators/TransposeOperator.cpp
sergesk/neoml
cca05584ef3d892cb00d23a105bac6674b3d50ef
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* Copyright © 2017-2020 ABBYY Production 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 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 "../common.h" #pragma hdrstop #include "TransposeOperator.h" #include "NeoOnnxCheck.h" #include "onnx.pb.h" namespace NeoOnnx { CTransposeOperator::CTransposeOperator( const onnx::NodeProto& transpose, int opsetVersion ) : CLayerOperator( transpose, opsetVersion ) { // The differences between versions are in supported data types and legacy optimization attributes CheckNeoOnnxSupport( OpsetVersion >= 1 && OpsetVersion <= MaxOpsetVersion, "opset version", *this ); CheckOnnxProtocol( InputCount() == 1, "operator must have 1 input", *this ); CheckOnnxProtocol( OutputCount() == 1, "operator must have 1 output", *this ); } void CTransposeOperator::AddLayers( const CTensorArray& inputs, CDnn& /* dnn */, CTensorArray& outputs ) const { CheckOnnxProtocol( inputs[0] != nullptr, "input can't be optional", *this ); const CTensorShape& inputShape = inputs[0]->Shape(); const int dimCount = inputShape.Size(); CFastArray<int, 8> perm; GetAttribute( "perm", perm ); if( perm.IsEmpty() ) { // Default value is reverse order perm.SetBufferSize( dimCount ); for( int i = 0; i < dimCount; ++i ) { perm.Add( dimCount - 1 - i ); } } // Working only with layout (converters will be added by next layers when needed) const CTensorLayout& inputLayout = inputs[0]->Layout(); CTensorLayout outputLayout; outputLayout.SetBufferSize( dimCount ); CTensorShape outputShape; outputShape.SetBufferSize( dimCount ); for( int i = 0; i < dimCount; ++i ) { outputLayout.Add( inputLayout[perm[i]] ); outputShape.Add( inputShape[perm[i]] ); } if( inputs[0]->IsCalculated() ) { outputs.Add( new CDataTensor( outputShape, outputLayout, *dynamic_cast<const CDataTensor*>( inputs[0].Ptr() )->Data() ) ); } else { outputs.Add( new CUserTensor( outputShape, outputLayout, dynamic_cast<const CUserTensor*>( inputs[0].Ptr() )->LayerOutput() ) ); } } } // namespace NeoOnnx
34.52
112
0.696022
sergesk