hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cb31f4d1d3c9e6ce1a3f5c52005e5aaa927486fe
9,779
cc
C++
src/tint/writer/hlsl/generator_impl_sanitizer_test.cc
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
9
2021-11-05T11:08:14.000Z
2022-03-18T05:14:34.000Z
src/tint/writer/hlsl/generator_impl_sanitizer_test.cc
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
2
2021-12-01T05:08:59.000Z
2022-02-18T08:14:30.000Z
src/tint/writer/hlsl/generator_impl_sanitizer_test.cc
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
1
2022-02-11T17:39:44.000Z
2022-02-11T17:39:44.000Z
// Copyright 2021 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/tint/ast/call_statement.h" #include "src/tint/ast/stage_attribute.h" #include "src/tint/ast/variable_decl_statement.h" #include "src/tint/writer/hlsl/test_helper.h" namespace tint::writer::hlsl { namespace { using HlslSanitizerTest = TestHelper; TEST_F(HlslSanitizerTest, Call_ArrayLength) { auto* s = Structure("my_struct", {Member(0, "a", ty.array<f32>(4))}); Global("b", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kRead, ast::AttributeList{ create<ast::BindingAttribute>(1), create<ast::GroupAttribute>(2), }); Func("a_func", ast::VariableList{}, ty.void_(), ast::StatementList{ Decl(Var("len", ty.u32(), ast::StorageClass::kNone, Call("arrayLength", AddressOf(MemberAccessor("b", "a"))))), }, ast::AttributeList{ Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(ByteAddressBuffer b : register(t1, space2); void a_func() { uint tint_symbol_1 = 0u; b.GetDimensions(tint_symbol_1); const uint tint_symbol_2 = ((tint_symbol_1 - 0u) / 4u); uint len = tint_symbol_2; return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, Call_ArrayLength_OtherMembersInStruct) { auto* s = Structure("my_struct", { Member(0, "z", ty.f32()), Member(4, "a", ty.array<f32>(4)), }); Global("b", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kRead, ast::AttributeList{ create<ast::BindingAttribute>(1), create<ast::GroupAttribute>(2), }); Func("a_func", ast::VariableList{}, ty.void_(), ast::StatementList{ Decl(Var("len", ty.u32(), ast::StorageClass::kNone, Call("arrayLength", AddressOf(MemberAccessor("b", "a"))))), }, ast::AttributeList{ Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(ByteAddressBuffer b : register(t1, space2); void a_func() { uint tint_symbol_1 = 0u; b.GetDimensions(tint_symbol_1); const uint tint_symbol_2 = ((tint_symbol_1 - 4u) / 4u); uint len = tint_symbol_2; return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, Call_ArrayLength_ViaLets) { auto* s = Structure("my_struct", {Member(0, "a", ty.array<f32>(4))}); Global("b", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kRead, ast::AttributeList{ create<ast::BindingAttribute>(1), create<ast::GroupAttribute>(2), }); auto* p = Const("p", nullptr, AddressOf("b")); auto* p2 = Const("p2", nullptr, AddressOf(MemberAccessor(Deref(p), "a"))); Func("a_func", ast::VariableList{}, ty.void_(), ast::StatementList{ Decl(p), Decl(p2), Decl(Var("len", ty.u32(), ast::StorageClass::kNone, Call("arrayLength", p2))), }, ast::AttributeList{ Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(ByteAddressBuffer b : register(t1, space2); void a_func() { uint tint_symbol_1 = 0u; b.GetDimensions(tint_symbol_1); const uint tint_symbol_2 = ((tint_symbol_1 - 0u) / 4u); uint len = tint_symbol_2; return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, Call_ArrayLength_ArrayLengthFromUniform) { auto* s = Structure("my_struct", {Member(0, "a", ty.array<f32>(4))}); Global("b", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kRead, ast::AttributeList{ create<ast::BindingAttribute>(1), create<ast::GroupAttribute>(2), }); Global("c", ty.Of(s), ast::StorageClass::kStorage, ast::Access::kRead, ast::AttributeList{ create<ast::BindingAttribute>(2), create<ast::GroupAttribute>(2), }); Func("a_func", ast::VariableList{}, ty.void_(), ast::StatementList{ Decl(Var( "len", ty.u32(), ast::StorageClass::kNone, Add(Call("arrayLength", AddressOf(MemberAccessor("b", "a"))), Call("arrayLength", AddressOf(MemberAccessor("c", "a")))))), }, ast::AttributeList{ Stage(ast::PipelineStage::kFragment), }); Options options; options.array_length_from_uniform.ubo_binding = {3, 4}; options.array_length_from_uniform.bindpoint_to_size_index.emplace( sem::BindingPoint{2, 2}, 7u); GeneratorImpl& gen = SanitizeAndBuild(options); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(cbuffer cbuffer_tint_symbol_1 : register(b4, space3) { uint4 tint_symbol_1[2]; }; ByteAddressBuffer b : register(t1, space2); ByteAddressBuffer c : register(t2, space2); void a_func() { uint tint_symbol_4 = 0u; b.GetDimensions(tint_symbol_4); const uint tint_symbol_5 = ((tint_symbol_4 - 0u) / 4u); uint len = (tint_symbol_5 + ((tint_symbol_1[1].w - 0u) / 4u)); return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, PromoteArrayInitializerToConstVar) { auto* array_init = array<i32, 4>(1, 2, 3, 4); auto* array_index = IndexAccessor(array_init, 3); auto* pos = Var("pos", ty.i32(), ast::StorageClass::kNone, array_index); Func("main", ast::VariableList{}, ty.void_(), { Decl(pos), }, { Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(void main() { const int tint_symbol[4] = {1, 2, 3, 4}; int pos = tint_symbol[3]; return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, PromoteStructInitializerToConstVar) { auto* str = Structure("S", { Member("a", ty.i32()), Member("b", ty.vec3<f32>()), Member("c", ty.i32()), }); auto* struct_init = Construct(ty.Of(str), 1, vec3<f32>(2.f, 3.f, 4.f), 4); auto* struct_access = MemberAccessor(struct_init, "b"); auto* pos = Var("pos", ty.vec3<f32>(), ast::StorageClass::kNone, struct_access); Func("main", ast::VariableList{}, ty.void_(), { Decl(pos), }, { Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(struct S { int a; float3 b; int c; }; void main() { const S tint_symbol = {1, float3(2.0f, 3.0f, 4.0f), 4}; float3 pos = tint_symbol.b; return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, InlinePtrLetsBasic) { // var v : i32; // let p : ptr<function, i32> = &v; // let x : i32 = *p; auto* v = Var("v", ty.i32()); auto* p = Const("p", ty.pointer<i32>(ast::StorageClass::kFunction), AddressOf(v)); auto* x = Var("x", ty.i32(), ast::StorageClass::kNone, Deref(p)); Func("main", ast::VariableList{}, ty.void_(), { Decl(v), Decl(p), Decl(x), }, { Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(void main() { int v = 0; int x = v; return; } )"; EXPECT_EQ(expect, got); } TEST_F(HlslSanitizerTest, InlinePtrLetsComplexChain) { // var a : array<mat4x4<f32>, 4>; // let ap : ptr<function, array<mat4x4<f32>, 4>> = &a; // let mp : ptr<function, mat4x4<f32>> = &(*ap)[3]; // let vp : ptr<function, vec4<f32>> = &(*mp)[2]; // let v : vec4<f32> = *vp; auto* a = Var("a", ty.array(ty.mat4x4<f32>(), 4)); auto* ap = Const( "ap", ty.pointer(ty.array(ty.mat4x4<f32>(), 4), ast::StorageClass::kFunction), AddressOf(a)); auto* mp = Const("mp", ty.pointer(ty.mat4x4<f32>(), ast::StorageClass::kFunction), AddressOf(IndexAccessor(Deref(ap), 3))); auto* vp = Const("vp", ty.pointer(ty.vec4<f32>(), ast::StorageClass::kFunction), AddressOf(IndexAccessor(Deref(mp), 2))); auto* v = Var("v", ty.vec4<f32>(), ast::StorageClass::kNone, Deref(vp)); Func("main", ast::VariableList{}, ty.void_(), { Decl(a), Decl(ap), Decl(mp), Decl(vp), Decl(v), }, { Stage(ast::PipelineStage::kFragment), }); GeneratorImpl& gen = SanitizeAndBuild(); ASSERT_TRUE(gen.Generate()) << gen.error(); auto got = gen.result(); auto* expect = R"(void main() { float4x4 a[4] = (float4x4[4])0; float4 v = a[3][2]; return; } )"; EXPECT_EQ(expect, got); } } // namespace } // namespace tint::writer::hlsl
29.104167
79
0.591267
hexops
cb33e206a632fb56eb0d84f2b843f0e0cb97ca34
1,208
cpp
C++
riscv/llvm/3.5/cfe-3.5.0.src/test/CXX/drs/dr412.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
null
null
null
riscv/llvm/3.5/cfe-3.5.0.src/test/CXX/drs/dr412.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
null
null
null
riscv/llvm/3.5/cfe-3.5.0.src/test/CXX/drs/dr412.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
1
2021-03-24T06:40:32.000Z
2021-03-24T06:40:32.000Z
// RUN: %clang_cc1 -std=c++98 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT="throw()" -DBAD_ALLOC="throw(std::bad_alloc)" // RUN: %clang_cc1 -std=c++11 %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT=noexcept -DBAD_ALLOC= // RUN: %clang_cc1 -std=c++1y %s -verify -fexceptions -fcxx-exceptions -pedantic-errors -DNOEXCEPT=noexcept -DBAD_ALLOC= // dr412: yes // lwg404: yes // lwg2340: yes // FIXME: __SIZE_TYPE__ expands to 'long long' on some targets. __extension__ typedef __SIZE_TYPE__ size_t; namespace std { struct bad_alloc {}; } inline void* operator new(size_t) BAD_ALLOC; // expected-error {{cannot be declared 'inline'}} inline void* operator new[](size_t) BAD_ALLOC; // expected-error {{cannot be declared 'inline'}} inline void operator delete(void*) NOEXCEPT; // expected-error {{cannot be declared 'inline'}} inline void operator delete[](void*) NOEXCEPT; // expected-error {{cannot be declared 'inline'}} #if __cplusplus >= 201402L inline void operator delete(void*, size_t) NOEXCEPT; // expected-error {{cannot be declared 'inline'}} inline void operator delete[](void*, size_t) NOEXCEPT; // expected-error {{cannot be declared 'inline'}} #endif
57.52381
144
0.737583
tangyibin
cb343dea6aa1b1219c04bb3e2e34f96cf46be367
6,094
cpp
C++
SerialPrograms/Source/CommonFramework/Widgets/SerialSelector.cpp
nmousouros/Arduino-Source
f8dce62af0b619016b4c18dc0371c59568da3e9a
[ "MIT" ]
null
null
null
SerialPrograms/Source/CommonFramework/Widgets/SerialSelector.cpp
nmousouros/Arduino-Source
f8dce62af0b619016b4c18dc0371c59568da3e9a
[ "MIT" ]
null
null
null
SerialPrograms/Source/CommonFramework/Widgets/SerialSelector.cpp
nmousouros/Arduino-Source
f8dce62af0b619016b4c18dc0371c59568da3e9a
[ "MIT" ]
null
null
null
/* Serial Connection Selector * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include <QJsonObject> #include <QHBoxLayout> #include "Common/Qt/QtJsonTools.h" #include "Common/Qt/NoWheelComboBox.h" #include "SerialSelector.h" #include <iostream> using std::cout; using std::endl; namespace PokemonAutomation{ SerialSelector::SerialSelector( QString label, std::string logger_tag, PABotBaseLevel minimum_pabotbase ) : m_label(std::move(label)) , m_minimum_pabotbase(minimum_pabotbase) , m_logger_tag(std::move(logger_tag)) {} SerialSelector::SerialSelector( QString label, std::string logger_tag, PABotBaseLevel minimum_pabotbase, const QJsonValue& json ) : SerialSelector(std::move(label), std::move(logger_tag), minimum_pabotbase) { load_json(json); } void SerialSelector::load_json(const QJsonValue& json){ QString name = json.toString(); if (name.size() > 0){ m_port = QSerialPortInfo(name); } } QJsonValue SerialSelector::to_json() const{ return QJsonValue(m_port.isNull() ? "" : m_port.portName()); } const QSerialPortInfo* SerialSelector::port() const{ if (m_port.isNull()){ return nullptr; } return &m_port; } SerialSelectorUI* SerialSelector::make_ui(QWidget& parent, Logger& logger){ return new SerialSelectorUI(parent, *this, logger); } SerialSelectorUI::SerialSelectorUI( QWidget& parent, SerialSelector& value, Logger& logger ) : QWidget(&parent) , m_value(value) , m_logger(logger, value.m_logger_tag) , m_connection(value.m_port, value.m_minimum_pabotbase, m_logger) { QHBoxLayout* serial_row = new QHBoxLayout(this); serial_row->setContentsMargins(0, 0, 0, 0); serial_row->addWidget(new QLabel("<b>Serial Port:</b>", this), 1); serial_row->addSpacing(5); m_serial_box = new NoWheelComboBox(this); serial_row->addWidget(m_serial_box, 5); refresh(); serial_row->addSpacing(5); QWidget* status = new QWidget(this); serial_row->addWidget(status, 3); QVBoxLayout* sbox = new QVBoxLayout(status); sbox->setContentsMargins(0, 0, 0, 0); sbox->setSpacing(0); m_serial_program = new QLabel(this); sbox->addWidget(m_serial_program); m_serial_uptime = new QLabel(this); sbox->addWidget(m_serial_uptime); serial_row->addSpacing(5); m_serial_program->setText("<font color=\"red\">Not Connected</font>"); m_serial_uptime->hide(); m_reset_button = new QPushButton("Reset Serial", this); serial_row->addWidget(m_reset_button, 1); connect( m_serial_box, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated), this, [=](int index){ QSerialPortInfo& current_port = m_value.m_port; if (index <= 0 || index > m_ports.size()){ current_port = QSerialPortInfo(); }else{ const QSerialPortInfo& port = m_ports[index - 1]; if (!current_port.isNull() && current_port.systemLocation() == port.systemLocation()){ return; } current_port = port; } reset(); } ); connect( &m_connection, &BotBaseHandle::on_not_connected, this, [=](QString error){ if (error.size() <= 0){ m_serial_program->setText("<font color=\"red\">Not Connected</font>"); }else{ m_serial_program->setText(error); } m_serial_uptime->hide(); } ); connect( &m_connection, &BotBaseHandle::on_connecting, this, [=](){ m_serial_program->setText("<font color=\"green\">Connecting...</font>"); m_serial_uptime->hide(); } ); connect( &m_connection, &BotBaseHandle::on_ready, this, [=](QString description){ m_serial_program->setText(description); on_ready(true); } ); connect( &m_connection, &BotBaseHandle::on_stopped, this, [=](QString error){ if (error.size() <= 0){ m_serial_program->setText("<font color=\"orange\">Stopping...</font>"); }else{ m_serial_program->setText(error); } } ); connect( &m_connection, &BotBaseHandle::uptime_status, this, [=](QString status){ m_serial_uptime->setText(status); m_serial_uptime->show(); } ); connect( m_reset_button, &QPushButton::clicked, this, [=](bool){ reset(); } ); } SerialSelectorUI::~SerialSelectorUI(){} void SerialSelectorUI::refresh(){ m_serial_box->clear(); m_serial_box->addItem("(none)"); m_ports = QSerialPortInfo::availablePorts(); QSerialPortInfo& current_port = m_value.m_port; int index = 0; for (int c = 0; c < m_ports.size(); c++){ const QSerialPortInfo& port = m_ports[c]; m_serial_box->addItem(port.portName() + " - " + port.description()); if (!current_port.isNull() && current_port.systemLocation() == port.systemLocation()){ index = c + 1; } } if (index != 0){ m_serial_box->setCurrentIndex(index); }else{ current_port = QSerialPortInfo(); m_serial_box->setCurrentIndex(0); } } bool SerialSelectorUI::is_ready() const{ return m_connection.state() == BotBaseHandle::State::READY; } BotBaseHandle& SerialSelectorUI::botbase(){ return m_connection; } void SerialSelectorUI::set_options_enabled(bool enabled){ m_serial_box->setEnabled(enabled); m_reset_button->setEnabled(enabled); } void SerialSelectorUI::stop(){ m_connection.stop(); } void SerialSelectorUI::reset(){ stop(); on_ready(false); refresh(); m_connection.reset(m_value.m_port); } }
28.082949
103
0.596981
nmousouros
cb35719183bc076a014d5c090379c3a3756b21be
4,304
cc
C++
tensorflow/stream_executor/cuda/cudart_stub.cc
khodges42/tensorflow
cb011e1dd8d79757fea01be39e19cb1155681e7e
[ "Apache-2.0" ]
3
2019-02-04T10:10:19.000Z
2019-12-29T08:09:37.000Z
tensorflow/stream_executor/cuda/cudart_stub.cc
khodges42/tensorflow
cb011e1dd8d79757fea01be39e19cb1155681e7e
[ "Apache-2.0" ]
null
null
null
tensorflow/stream_executor/cuda/cudart_stub.cc
khodges42/tensorflow
cb011e1dd8d79757fea01be39e19cb1155681e7e
[ "Apache-2.0" ]
6
2018-11-29T20:52:00.000Z
2021-02-19T22:43:32.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This file wraps cuda runtime calls with dso loader so that we don't need to // have explicit linking to libcuda. #include "cuda/include/cuda_runtime_api.h" #include "tensorflow/stream_executor/lib/env.h" #include "tensorflow/stream_executor/platform/dso_loader.h" namespace { void *GetDsoHandle() { static auto handle = [] { void *result = nullptr; using DsoLoader = stream_executor::internal::DsoLoader; DsoLoader::GetLibcudartDsoHandle(&result).IgnoreError(); return result; }(); return handle; } template <typename T> T LoadSymbol(const char *symbol_name) { void *symbol = nullptr; auto env = stream_executor::port::Env::Default(); env->GetSymbolFromLibrary(GetDsoHandle(), symbol_name, &symbol).IgnoreError(); return reinterpret_cast<T>(symbol); } cudaError_t GetSymbolNotFoundError() { return cudaErrorSharedObjectSymbolNotFound; } const char *GetSymbolNotFoundStrError() { return "cudaErrorSharedObjectSymbolNotFound"; } } // namespace // Code below is auto-generated. extern "C" { cudaError_t CUDART_CB cudaFree(void *devPtr) { using FuncPtr = cudaError_t (*)(void *devPtr); static auto func_ptr = LoadSymbol<FuncPtr>("cudaFree"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(devPtr); } cudaError_t CUDART_CB cudaGetDevice(int *device) { using FuncPtr = cudaError_t (*)(int *device); static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDevice"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(device); } cudaError_t CUDART_CB cudaGetDeviceProperties(cudaDeviceProp *prop, int device) { using FuncPtr = cudaError_t (*)(cudaDeviceProp * prop, int device); static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDeviceProperties"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(prop, device); } const char *CUDART_CB cudaGetErrorString(cudaError_t error) { using FuncPtr = const char *(*)(cudaError_t error); static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetErrorString"); if (!func_ptr) return GetSymbolNotFoundStrError(); return func_ptr(error); } cudaError_t CUDART_CB cudaSetDevice(int device) { using FuncPtr = cudaError_t (*)(int device); static auto func_ptr = LoadSymbol<FuncPtr>("cudaSetDevice"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(device); } cudaError_t CUDART_CB cudaStreamAddCallback(cudaStream_t stream, cudaStreamCallback_t callback, void *userData, unsigned int flags) { using FuncPtr = cudaError_t (*)(cudaStream_t stream, cudaStreamCallback_t callback, void *userData, unsigned int flags); static auto func_ptr = LoadSymbol<FuncPtr>("cudaStreamAddCallback"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(stream, callback, userData, flags); } cudaError_t CUDART_CB cudaGetDeviceCount(int *count) { using FuncPtr = cudaError_t (*)(int *count); static auto func_ptr = LoadSymbol<FuncPtr>("cudaGetDeviceCount"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(count); } cudaError_t CUDART_CB cudaPointerGetAttributes( struct cudaPointerAttributes *attributes, const void *ptr) { using FuncPtr = cudaError_t (*)(struct cudaPointerAttributes * attributes, const void *ptr); static auto func_ptr = LoadSymbol<FuncPtr>("cudaPointerGetAttributes"); if (!func_ptr) return GetSymbolNotFoundError(); return func_ptr(attributes, ptr); } } // extern "C"
37.426087
80
0.70632
khodges42
cb3792620caa21018f8ece94216e509532d9161b
3,283
cpp
C++
src/cpp-ethereum/libethereum/TransactionReceipt.cpp
nccproject/ncc
068ccc82a73d28136546095261ad8ccef7e541a3
[ "MIT" ]
42
2021-01-04T01:59:21.000Z
2021-05-14T14:35:04.000Z
src/cpp-ethereum/libethereum/TransactionReceipt.cpp
estxcoin/estcore
4398b1d944373fe25668469966fa2660da454279
[ "MIT" ]
2
2021-01-04T02:08:47.000Z
2021-01-04T02:36:08.000Z
src/cpp-ethereum/libethereum/TransactionReceipt.cpp
estxcoin/estcore
4398b1d944373fe25668469966fa2660da454279
[ "MIT" ]
15
2021-01-04T02:00:21.000Z
2021-01-06T02:06:43.000Z
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file TransactionReceipt.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "TransactionReceipt.h" #include <libethcore/Exceptions.h> #include <boost/variant/get.hpp> using namespace std; using namespace dev; using namespace dev::eth; TransactionReceipt::TransactionReceipt(bytesConstRef _rlp) { RLP r(_rlp); if (!r.isList() || r.itemCount() != 4) BOOST_THROW_EXCEPTION(InvalidTransactionReceiptFormat()); if (!r[0].isData()) BOOST_THROW_EXCEPTION(InvalidTransactionReceiptFormat()); if (r[0].size() == 32) m_statusCodeOrStateRoot = (h256)r[0]; else if (r[0].isInt()) m_statusCodeOrStateRoot = (uint8_t)r[0]; else BOOST_THROW_EXCEPTION(InvalidTransactionReceiptFormat()); m_gasUsed = (u256)r[1]; m_bloom = (LogBloom)r[2]; for (auto const& i : r[3]) m_log.emplace_back(i); } TransactionReceipt::TransactionReceipt(h256 const& _root, u256 const& _gasUsed, LogEntries const& _log): m_statusCodeOrStateRoot(_root), m_gasUsed(_gasUsed), m_bloom(eth::bloom(_log)), m_log(_log) {} TransactionReceipt::TransactionReceipt(uint8_t _status, u256 const& _gasUsed, LogEntries const& _log): m_statusCodeOrStateRoot(_status), m_gasUsed(_gasUsed), m_bloom(eth::bloom(_log)), m_log(_log) {} void TransactionReceipt::streamRLP(RLPStream& _s) const { _s.appendList(4); if (hasStatusCode()) _s << statusCode(); else _s << stateRoot(); _s << m_gasUsed << m_bloom; _s.appendList(m_log.size()); for (LogEntry const& l: m_log) l.streamRLP(_s); } bool TransactionReceipt::hasStatusCode() const { return m_statusCodeOrStateRoot.which() == 0; } uint8_t TransactionReceipt::statusCode() const { if (hasStatusCode()) return boost::get<uint8_t>(m_statusCodeOrStateRoot); else BOOST_THROW_EXCEPTION(TransactionReceiptVersionError()); } h256 const& TransactionReceipt::stateRoot() const { if (hasStatusCode()) BOOST_THROW_EXCEPTION(TransactionReceiptVersionError()); else return boost::get<h256>(m_statusCodeOrStateRoot); } std::ostream& dev::eth::operator<<(std::ostream& _out, TransactionReceipt const& _r) { if (_r.hasStatusCode()) _out << "Status: " << _r.statusCode() << std::endl; else _out << "Root: " << _r.stateRoot() << std::endl; _out << "Gas used: " << _r.cumulativeGasUsed() << std::endl; _out << "Logs: " << _r.log().size() << " entries:" << std::endl; for (LogEntry const& i: _r.log()) { _out << "Address " << i.address << ". Topics:" << std::endl; for (auto const& j: i.topics) _out << " " << j << std::endl; _out << " Data: " << toHex(i.data) << std::endl; } _out << "Bloom: " << _r.bloom() << std::endl; return _out; }
27.358333
104
0.709717
nccproject
cb3876ee76b164483281367d1bb0beb667e46323
11,494
cpp
C++
planner_cspace/src/grid_astar_model_3dof.cpp
at-wat/neonavigation
4fabc3d100f5e211db09fb3f8e68650fa46a0d50
[ "BSD-3-Clause" ]
195
2017-02-16T08:19:29.000Z
2022-03-03T06:00:28.000Z
planner_cspace/src/grid_astar_model_3dof.cpp
at-wat/neonavigation
4fabc3d100f5e211db09fb3f8e68650fa46a0d50
[ "BSD-3-Clause" ]
584
2016-11-10T04:48:04.000Z
2021-12-19T23:53:12.000Z
planner_cspace/src/grid_astar_model_3dof.cpp
at-wat/neonavigation
4fabc3d100f5e211db09fb3f8e68650fa46a0d50
[ "BSD-3-Clause" ]
74
2016-10-15T13:54:29.000Z
2022-02-02T00:26:22.000Z
/* * Copyright (c) 2019-2020, the neonavigation authors * 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 OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <cmath> #include <limits> #include <utility> #include <vector> #include <ros/ros.h> #include <costmap_cspace_msgs/MapMetaData3D.h> #include <planner_cspace/cyclic_vec.h> #include <planner_cspace/planner_3d/grid_astar_model.h> #include <planner_cspace/planner_3d/motion_cache.h> #include <planner_cspace/planner_3d/motion_primitive_builder.h> #include <planner_cspace/planner_3d/path_interpolator.h> #include <planner_cspace/planner_3d/rotation_cache.h> namespace planner_cspace { namespace planner_3d { GridAstarModel3D::GridAstarModel3D( const costmap_cspace_msgs::MapMetaData3D& map_info, const Vecf& euclid_cost_coef, const int local_range, const BlockMemGridmapBase<float, 3, 2>& cost_estim_cache, const BlockMemGridmapBase<char, 3, 2>& cm, const BlockMemGridmapBase<char, 3, 2>& cm_hyst, const BlockMemGridmapBase<char, 3, 2>& cm_rough, const CostCoeff& cc, const int range) : hysteresis_(false) , map_info_(map_info) , euclid_cost_coef_(euclid_cost_coef) , resolution_( 1.0f / map_info.linear_resolution, 1.0f / map_info.linear_resolution, 1.0f / map_info.angular_resolution) , local_range_(local_range) , cost_estim_cache_(cost_estim_cache) , cm_(cm) , cm_hyst_(cm_hyst) , cm_rough_(cm_rough) , cc_(cc) , range_(range) { rot_cache_.reset(map_info_.linear_resolution, map_info_.angular_resolution, range_); costmap_cspace_msgs::MapMetaData3D map_info_linear(map_info_); map_info_linear.angle = 1; motion_cache_linear_.reset( map_info_linear.linear_resolution, map_info_linear.angular_resolution, range_, cm_rough_.getAddressor()); motion_cache_.reset( map_info_.linear_resolution, map_info_.angular_resolution, range_, cm_.getAddressor()); // Make boundary check threshold min_boundary_ = motion_cache_.getMaxRange(); max_boundary_ = Vec(static_cast<int>(map_info_.width), static_cast<int>(map_info_.height), static_cast<int>(map_info_.angle)) - min_boundary_; ROS_INFO("x:%d, y:%d grids around the boundary is ignored on path search", min_boundary_[0], min_boundary_[1]); createEuclidCostCache(); motion_primitives_ = MotionPrimitiveBuilder::build(map_info_, cc_, range_); search_list_rough_.clear(); Vec d; for (d[0] = -range_; d[0] <= range_; d[0]++) { for (d[1] = -range_; d[1] <= range_; d[1]++) { if (d.sqlen() > range_ * range_) continue; d[2] = 0; search_list_rough_.push_back(d); } } path_interpolator_.reset(map_info_.angular_resolution, range_); } void GridAstarModel3D::enableHysteresis(const bool enable) { hysteresis_ = enable; } void GridAstarModel3D::createEuclidCostCache() { for (int rootsum = 0; rootsum < static_cast<int>(euclid_cost_lin_cache_.size()); ++rootsum) { euclid_cost_lin_cache_[rootsum] = std::sqrt(rootsum) * euclid_cost_coef_[0]; } } float GridAstarModel3D::euclidCost(const Vec& v) const { float cost = euclidCostRough(v); int angle = v[2]; while (angle > static_cast<int>(map_info_.angle) / 2) angle -= static_cast<int>(map_info_.angle); while (angle < -static_cast<int>(map_info_.angle) / 2) angle += static_cast<int>(map_info_.angle); cost += std::abs(euclid_cost_coef_[2] * angle); return cost; } float GridAstarModel3D::euclidCostRough(const Vec& v) const { int rootsum = 0; for (int i = 0; i < 2; ++i) rootsum += v[i] * v[i]; if (rootsum < static_cast<int>(euclid_cost_lin_cache_.size())) { return euclid_cost_lin_cache_[rootsum]; } return std::sqrt(rootsum) * euclid_cost_coef_[0]; } float GridAstarModel3D::cost( const Vec& cur, const Vec& next, const std::vector<VecWithCost>& start, const Vec& goal) const { Vec d_raw = next - cur; d_raw.cycle(map_info_.angle); const Vec d = d_raw; float cost = euclidCost(d); if (d[0] == 0 && d[1] == 0) { // In-place turn int sum = 0; const int dir = d[2] < 0 ? -1 : 1; Vec pos = cur; for (int i = 0; i < std::abs(d[2]); i++) { pos[2] += dir; if (pos[2] < 0) pos[2] += map_info_.angle; else if (pos[2] >= static_cast<int>(map_info_.angle)) pos[2] -= map_info_.angle; const auto c = cm_[pos]; if (c > 99) return -1; sum += c; } cost += sum * map_info_.angular_resolution * euclid_cost_coef_[2] / euclid_cost_coef_[0] + sum * map_info_.angular_resolution * cc_.weight_costmap_turn_ / 100.0; // simplified from sum * map_info_.angular_resolution * abs(d[2]) * cc_.weight_costmap_turn_ / (100.0 * abs(d[2])) return cc_.in_place_turn_ + cost; } const Vec d2(d[0] + range_, d[1] + range_, next[2]); const Vecf motion = rot_cache_.getMotion(cur[2], d2); const float dist = motion.len(); if (motion[0] < 0) { // Going backward cost *= 1.0 + cc_.weight_backward_; } if (d[2] == 0) { const float aspect = motion[0] / motion[1]; cost += euclid_cost_coef_[2] * std::abs(1.0 / aspect) * map_info_.angular_resolution / (M_PI * 2.0); // Go-straight int sum = 0, sum_hyst = 0; Vec d_index(d[0], d[1], next[2]); d_index.cycleUnsigned(map_info_.angle); const auto cache_page = motion_cache_.find(cur[2], d_index); if (cache_page == motion_cache_.end(cur[2])) return -1; const int num = cache_page->second.getMotion().size(); for (const auto& pos_diff : cache_page->second.getMotion()) { const Vec pos( cur[0] + pos_diff[0], cur[1] + pos_diff[1], pos_diff[2]); const auto c = cm_[pos]; if (c > 99) return -1; sum += c; if (hysteresis_) sum_hyst += cm_hyst_[pos]; } const float distf = cache_page->second.getDistance(); cost += sum * map_info_.linear_resolution * distf * cc_.weight_costmap_ / (100.0 * num); cost += sum_hyst * map_info_.linear_resolution * distf * cc_.weight_hysteresis_ / (100.0 * num); } else { const std::pair<float, float>& radiuses = rot_cache_.getRadiuses(cur[2], d2); const float r1 = radiuses.first; const float r2 = radiuses.second; const float curv_radius = (r1 + r2) / 2; // Ignore boundary if (cur[0] < min_boundary_[0] || cur[1] < min_boundary_[1] || cur[0] >= max_boundary_[0] || cur[1] >= max_boundary_[1]) return -1; if (std::abs(cc_.max_vel_ / r1) > cc_.max_ang_vel_) { const float vel = std::abs(curv_radius) * cc_.max_ang_vel_; // Curve deceleration penalty cost += dist * std::abs(vel / cc_.max_vel_) * cc_.weight_decel_; } { int sum = 0, sum_hyst = 0; Vec d_index(d[0], d[1], next[2]); d_index.cycleUnsigned(map_info_.angle); const auto cache_page = motion_cache_.find(cur[2], d_index); if (cache_page == motion_cache_.end(cur[2])) return -1; const int num = cache_page->second.getMotion().size(); for (const auto& pos_diff : cache_page->second.getMotion()) { const Vec pos( cur[0] + pos_diff[0], cur[1] + pos_diff[1], pos_diff[2]); const auto c = cm_[pos]; if (c > 99) return -1; sum += c; if (hysteresis_) sum_hyst += cm_hyst_[pos]; } const float distf = cache_page->second.getDistance(); cost += sum * map_info_.linear_resolution * distf * cc_.weight_costmap_ / (100.0 * num); cost += sum * map_info_.angular_resolution * std::abs(d[2]) * cc_.weight_costmap_turn_ / (100.0 * num); cost += sum_hyst * map_info_.linear_resolution * distf * cc_.weight_hysteresis_ / (100.0 * num); } } return cost; } float GridAstarModel3D::costEstim( const Vec& cur, const Vec& goal) const { Vec s2(cur[0], cur[1], 0); float cost = cost_estim_cache_[s2]; if (cost == std::numeric_limits<float>::max()) return std::numeric_limits<float>::max(); int diff = cur[2] - goal[2]; while (diff > static_cast<int>(map_info_.angle) / 2) diff -= static_cast<int>(map_info_.angle); while (diff < -static_cast<int>(map_info_.angle) / 2) diff += static_cast<int>(map_info_.angle); cost += euclid_cost_coef_[2] * std::abs(diff); return cost; } const std::vector<GridAstarModel3D::Vec>& GridAstarModel3D::searchGrids( const Vec& p, const std::vector<VecWithCost>& ss, const Vec& es) const { const float local_range_sq = local_range_ * local_range_; for (const VecWithCost& s : ss) { const Vec ds = s.v_ - p; if (ds.sqlen() < local_range_sq) { return motion_primitives_[p[2]]; } } return search_list_rough_; } float GridAstarModel2D::cost( const Vec& cur, const Vec& next, const std::vector<VecWithCost>& start, const Vec& goal) const { Vec d = next - cur; d[2] = 0; float cost = base_->euclidCostRough(d); int sum = 0; const auto cache_page = base_->motion_cache_linear_.find(0, d); if (cache_page == base_->motion_cache_linear_.end(0)) return -1; const int num = cache_page->second.getMotion().size(); for (const auto& pos_diff : cache_page->second.getMotion()) { const Vec pos(cur[0] + pos_diff[0], cur[1] + pos_diff[1], 0); const auto c = base_->cm_rough_[pos]; if (c > 99) return -1; sum += c; } const float distf = cache_page->second.getDistance(); cost += sum * base_->map_info_.linear_resolution * distf * base_->cc_.weight_costmap_ / (100.0 * num); return cost; } float GridAstarModel2D::costEstim( const Vec& cur, const Vec& goal) const { const Vec d = goal - cur; const float cost = base_->euclidCostRough(d); return cost; } const std::vector<GridAstarModel3D::Vec>& GridAstarModel2D::searchGrids( const Vec& cur, const std::vector<VecWithCost>& start, const Vec& goal) const { return base_->search_list_rough_; } } // namespace planner_3d } // namespace planner_cspace
32.377465
118
0.666
at-wat
cb3adced9e2f053dc575e6c761d0535ab59180fa
4,220
hpp
C++
graph/graph.hpp
ytuza/proyecto
3ebd08518c80180063262810ed9515cb94a2b735
[ "MIT" ]
null
null
null
graph/graph.hpp
ytuza/proyecto
3ebd08518c80180063262810ed9515cb94a2b735
[ "MIT" ]
null
null
null
graph/graph.hpp
ytuza/proyecto
3ebd08518c80180063262810ed9515cb94a2b735
[ "MIT" ]
null
null
null
#pragma once #include "edge.hpp" #include "node.hpp" #include <algorithm> #include <deque> #include <utility> template <typename N, typename E> class Graph { public: using SelfType = Graph<N, E>; using NodeValueType = N; using EdgeValueType = E; using NodeType = Node<SelfType>; using EdgeType = Edge<SelfType>; struct PathFindData { double accDist; bool done; EdgeType *prev; PathFindData(double dist, EdgeType *prev) { this->accDist = dist; this->prev = prev; } }; protected: std::deque<NodeType *> nodeList; public: void insertNode(NodeValueType val) { nodeList.push_back(new NodeType(val)); } void insertEdge(EdgeValueType val, NodeType *nodeA, NodeType *nodeB, bool dir = 0) { EdgeType *tmp = new EdgeType(val, nodeA, nodeB, dir); nodeA->edgeList.push_back(tmp); if (nodeA != nodeB) // If the edge is a loop we don't have to push it again nodeB->edgeList.push_back(tmp); } void removeNode(NodeType *remv) { auto fnd = nodeList.begin(); while (*fnd != remv) fnd++; delete *fnd; nodeList.erase(fnd); } typename std::deque<NodeType *>::iterator removeNode(typename std::deque<NodeType *>::iterator iterator) { delete *iterator; return nodeList.erase(iterator); } // Remove all the edges between two nodes: void removeEdgesBtwn(NodeType *nodeA, NodeType *nodeB) { std::deque<EdgeType *> toremove; for (EdgeType *i : nodeA->edgeList) { auto &first = i->conNodes.first; auto &second = i->conNodes.second; if ((first == nodeA and second == nodeB) or (first == nodeB and second == nodeA)) toremove.push_back(i); } for (EdgeType *i : toremove) delete i; } void removeEdge(EdgeType *remv) { delete remv; } const std::deque<NodeType *> &getNodeList() { return nodeList; } void clear() { while (!nodeList.empty()) { delete nodeList.back(); nodeList.pop_back(); } } std::pair<double, std::deque<EdgeType *>> minPathDijkstra(NodeType *start, NodeType *end) { std::deque<NodeType *> queue; start->pathData = new PathFindData(0.0, nullptr); queue.push_back(start); while (!queue.empty()) { NodeType *crtNode = queue.front(); for (const auto &iedge : crtNode->edgeList) { NodeType *otherNode = iedge->otherNode(crtNode); double dist = crtNode->pathData->accDist + iedge->value; if (otherNode->pathData == nullptr) { otherNode->pathData = new PathFindData(dist, iedge); auto pos = std::upper_bound( queue.begin(), queue.end(), otherNode, [](auto a, auto b) { return a->pathData->accDist < b->pathData->accDist; }); queue.insert(pos, otherNode); } else { if (dist < otherNode->pathData->accDist) { NodeType *tmp = new NodeType(); tmp->pathData = new PathFindData(dist, nullptr); auto pos = std::upper_bound( queue.begin(), queue.end(), tmp, [](auto a, auto b) { return a->pathData->accDist < b->pathData->accDist; }); auto actPos = std::find(queue.begin(), queue.end(), otherNode); // TODO: replace queue.begin() with pos std::rotate(pos, actPos, actPos + 1); // TODO: use reverse iterator otherNode->pathData->accDist = dist; otherNode->pathData->prev = iedge; delete tmp->pathData; delete tmp; } } } queue.pop_front(); } std::deque<EdgeType *> edgePath; double pathLenght = 0.0; if (end->pathData) { pathLenght = end->pathData->accDist; NodeType *actNode = end; while (actNode != start) { edgePath.push_back(actNode->pathData->prev); actNode = actNode->pathData->prev->otherNode(actNode); } for (const auto &i : nodeList) { if (i->pathData) { delete i->pathData; i->pathData = nullptr; } } } return {pathLenght, edgePath}; } ~Graph() { this->clear(); } };
28.513514
86
0.579147
ytuza
cb3c47a7c4b5b99a1700bdf4d0fff2baa2bb6ac3
6,106
cpp
C++
2006/samples/database/clonreac_dg/clonreac.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
1
2021-06-25T02:58:47.000Z
2021-06-25T02:58:47.000Z
2004/samples/database/clonreac_dg/clonreac.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
null
null
null
2004/samples/database/clonreac_dg/clonreac.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
3
2020-05-23T02:47:44.000Z
2020-10-27T01:26:53.000Z
// (C) Copyright 1996,1998 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // clonreac.cpp // // Wblock Modification Sample Code // // This code demonstrates how to add additional objects during // beginDeepCloneXlation(). #include "rxregsvc.h" #include "aced.h" #include "dbidmap.h" #include "dbsymtb.h" #include "adscodes.h" // Function prototypes // void modifyWblock(); void clearReactor(); static Adesk::Boolean getYorN(const char* pStr); extern "C" AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode, void*); // Forward class declarations // class AsdkEdReactor; // Globals // AsdkEdReactor *gpEdr = NULL; // pointer to editor reactor class AsdkEdReactor : public AcEditorReactor // // Custom AcEditorReactor class for Wblock Clone event // notification { public: virtual void beginDeepCloneXlation(AcDbIdMapping& idMap, Acad::ErrorStatus* es); }; // THE FOLLOWING CODE APPEARS IN THE SDK DOCUMENT. // Since AcDbDatabase::wblock() only supports AcDbEntities // in its Array of Ids, this code demonstrates how to add // additional objects during beginDeepCloneXlation(). If // it is a WBLOCK command, it asks the user if all Text // Styles should be Wblocked. Otherwise, only those text // styles which are referenced by entities being Wblocked // will be included (Wblock's default behavior). // AsdkEdReactor is derived from AcEditorReactor // void AsdkEdReactor::beginDeepCloneXlation(AcDbIdMapping& idMap, Acad::ErrorStatus* es) { if (idMap.deepCloneContext() == AcDb::kDcWblock && getYorN("Wblock all Text Styles")) { AcDbDatabase *pOrigDb, *pDestDb; if (idMap.origDb(pOrigDb) != Acad::eOk) return; *es = idMap.destDb(pDestDb); if (*es != Acad::eOk) return; AcDbTextStyleTable *pTsTable; *es = pOrigDb->getSymbolTable(pTsTable, AcDb::kForRead); if (*es != Acad::eOk) return; AcDbTextStyleTableIterator *pTsIter; *es = pTsTable->newIterator(pTsIter); if (*es != Acad::eOk) { pTsTable->close(); return; } AcDbTextStyleTableRecord *pTsRecord; AcDbObject *pClonedObj; for (; !pTsIter->done(); pTsIter->step()) { *es = pTsIter->getRecord(pTsRecord, AcDb::kForRead); if (*es != Acad::eOk) { delete pTsIter; pTsTable->close(); return; } // We don't need to check for already cloned // Records. If the Text Style is already // cloned, wblockClone will return Acad::eOk // and pCloneObj will be NULL. // pClonedObj = NULL; *es = pTsRecord->wblockClone(pDestDb, pClonedObj, idMap, Adesk::kFalse); if (*es != Acad::eOk) { pTsRecord->close(); delete pTsIter; pTsTable->close(); return; } *es = pTsRecord->close(); if (*es != Acad::eOk) { delete pTsIter; pTsTable->close(); return; } if (pClonedObj != NULL) { *es = pClonedObj->close(); if (*es != Acad::eOk) { delete pTsIter; pTsTable->close(); return; } } } delete pTsIter; *es = pTsTable->close(); } } // END CODE APPEARING IN SDK DOCUMENT. // Adds the reactor to the editor to monitor changes. // void modifyWblock() { acedEditor->addReactor(gpEdr); acutPrintf("Added new command to Wblock.\n"); } // Removes the editor reactor // void clearReactor() { acedEditor->removeReactor(gpEdr); } // Queries the user for Yes/No answer // static Adesk::Boolean getYorN(const char* pStr) { char yorn_str[132]; // specific prompt. // acutPrintf("\n%s", pStr); acedInitGet(0, "No Yes"); yorn_str[0] = 'Y'; yorn_str[1] = '\0'; switch (acedGetString(Adesk::kFalse, " -- No/<Yes>: ", yorn_str)) { case RTKWORD: acedGetInput(yorn_str); /* Deliberate fallthrough */ default: break; } return (!((yorn_str[0] == 'N') || (yorn_str[0] == 'n'))); } // Arx entry point function // AcRx::AppRetCode acrxEntryPoint(AcRx::AppMsgCode msg, void* appId) { switch (msg) { case AcRx::kInitAppMsg: acrxDynamicLinker->unlockApplication(appId); acrxDynamicLinker->registerAppMDIAware(appId); gpEdr = new AsdkEdReactor(); acedRegCmds->addCommand("ASDK_NOTIFY_TEST", "ASDK_WATCH", "MODWBLOCK", ACRX_CMD_TRANSPARENT, modifyWblock); break; case AcRx::kUnloadAppMsg: clearReactor(); acedRegCmds->removeGroup("ASDK_NOTIFY_TEST"); delete gpEdr; } return AcRx::kRetOK; }
28.138249
73
0.583361
kevinzhwl
cb467a2eb68adef076637f5224505c959a950816
88
cpp
C++
coding/helo.cpp
tusharkumar2005/developer
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
[ "CC0-1.0" ]
1
2021-09-21T11:49:50.000Z
2021-09-21T11:49:50.000Z
coding/helo.cpp
tusharkumar2005/developer
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
[ "CC0-1.0" ]
null
null
null
coding/helo.cpp
tusharkumar2005/developer
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
[ "CC0-1.0" ]
null
null
null
using namespace std; #include<iostream> int main(){ cout<<"hello"; }
9.777778
21
0.545455
tusharkumar2005
cb48500de4798dd97f46ba7790a7910efee7110d
12,749
cpp
C++
tests/core/data_test.cpp
DCC-UFJF/UFJF-MLTK
bb0696a5ec41e8a2b89be2a2d4e35b39fdcb85f2
[ "MIT" ]
null
null
null
tests/core/data_test.cpp
DCC-UFJF/UFJF-MLTK
bb0696a5ec41e8a2b89be2a2d4e35b39fdcb85f2
[ "MIT" ]
null
null
null
tests/core/data_test.cpp
DCC-UFJF/UFJF-MLTK
bb0696a5ec41e8a2b89be2a2d4e35b39fdcb85f2
[ "MIT" ]
null
null
null
// // Created by mateus on 12/04/2021. // #include <iostream> #include <gtest/gtest.h> #include "ufjfmltk/core/Data.hpp" #include "ufjfmltk/core/Datasets.hpp" #include "ufjfmltk/core/Kernel.hpp" #include "ufjfmltk/valid/Validation.hpp" class DataTest: public ::testing::Test { protected: void SetUp() override{ if(!mult.load("iris_mult.csv")){ std::cerr << "Error loading multiclass dataset." << std::endl; } if(!bin.load("iris.data")){ std::cerr << "Error loading binary dataset." << std::endl; } } mltk::Data<double> mult, bin; }; TEST_F(DataTest, OpenDataBinDataset) { std::vector<size_t> dist = {50, 100}; EXPECT_EQ(bin.size(), 150); EXPECT_EQ(bin.points().size(), 150); EXPECT_EQ(bin.dim(), 4); EXPECT_EQ(bin.classesDistribution(), dist); mltk::Data<double> seismic("seismic-bumps.arff", true); auto seis_dist = seismic.classesDistribution(); EXPECT_EQ(seismic.size(), 2584); EXPECT_EQ(seismic.points().size(), 2584); EXPECT_EQ(seismic.dim(), 18); EXPECT_EQ(std::accumulate(seis_dist.begin(), seis_dist.end(),0), seismic.size()); bin.write("_iris", "data"); bin.write("_iris", "csv"); bin.write("_iris", "plt"); mltk::Data<double> data("_iris.data"); EXPECT_EQ(data.size(), 150); EXPECT_EQ(data.points().size(), 150); EXPECT_EQ(data.dim(), 4); EXPECT_EQ(data.classesDistribution(), dist); mltk::Data<double> csv("_iris.csv"); EXPECT_EQ(csv.size(), 150); EXPECT_EQ(csv.points().size(), 150); EXPECT_EQ(csv.dim(), 4); EXPECT_EQ(csv.classesDistribution(), dist); dist = {540, 611}; mltk::Data<double> arff("diabetic.arff", true); EXPECT_EQ(arff.size(), 1151); EXPECT_EQ(arff.points().size(), 1151); EXPECT_EQ(arff.classes().size(), 2); EXPECT_EQ(arff.dim(), 19); EXPECT_EQ(arff.classesDistribution(), dist); mltk::Data<double> txt("teste.txt"); EXPECT_EQ(txt.size(), 4); EXPECT_EQ(txt.points().size(), 4); EXPECT_EQ(txt.classes().size(), 0); EXPECT_EQ(txt.dim(), 3); } TEST_F(DataTest, OpenCsvMultiDataset) { std::vector<size_t> dist = {50, 50, 50}; EXPECT_EQ(mult.size(), 150); EXPECT_EQ(mult.points().size(), 150); EXPECT_EQ(mult.classes().size(), 3); EXPECT_EQ(mult.dim(), 4); EXPECT_EQ(mult.classesDistribution(), dist); mult.write("_iris", "data"); mult.write("_iris", "csv"); mult.write("_iris", "plt"); mltk::Data<double> data("_iris.data"); EXPECT_EQ(data.size(), 150); EXPECT_EQ(data.points().size(), 150); EXPECT_EQ(data.classes().size(), 3); EXPECT_EQ(data.dim(), 4); EXPECT_EQ(data.classesDistribution(), dist); mltk::Data<double> csv("_iris.csv"); EXPECT_EQ(csv.size(), 150); EXPECT_EQ(csv.points().size(), 150); EXPECT_EQ(csv.classes().size(), 3); EXPECT_EQ(csv.dim(), 4); EXPECT_EQ(csv.classesDistribution(), dist); } TEST_F(DataTest, CopyBinDataset) { std::vector<size_t> dist = {50, 100}; mltk::Data<double> cp = bin, cp_zero; EXPECT_EQ(cp.size(), 150); EXPECT_EQ(cp.points().size(), 150); EXPECT_EQ(cp.dim(), 4); EXPECT_EQ(cp.classesDistribution(), dist); EXPECT_EQ(cp.classes().size(), 2); cp_zero.copyZero(bin); EXPECT_EQ(cp_zero.size(), 0); EXPECT_EQ(bin.size(), 150); EXPECT_EQ(bin.points().size(), 150); EXPECT_EQ(bin.dim(), 4); EXPECT_EQ(bin.classesDistribution(), dist); EXPECT_EQ(bin.classes().size(), 2); } TEST_F(DataTest, CopyMultDataset) { std::vector<size_t> dist = {50, 50, 50}; mltk::Data<double> cp = mult, copy_mult; copy_mult = mult.copy(); EXPECT_EQ(cp.size(), 150); EXPECT_EQ(cp.points().size(), 150); EXPECT_EQ(cp.dim(), 4); EXPECT_EQ(cp.classesDistribution(), dist); EXPECT_EQ(cp.classes().size(), 3); EXPECT_EQ(mult.size(), 150); EXPECT_EQ(mult.points().size(), 150); EXPECT_EQ(mult.dim(), 4); EXPECT_EQ(mult.classesDistribution(), dist); EXPECT_EQ(mult.classes().size(), 3); mult.shuffle(); ASSERT_TRUE(mult != copy_mult); ASSERT_FALSE(mult == copy_mult); mult.normalize(); ASSERT_EQ(mult.dim(), 5); auto spirals = mltk::datasets::make_spirals(); spirals.normalize(); std::cout << mltk::Point<int>(spirals.getFeaturesNames()) << std::endl; ASSERT_EQ(spirals.dim(), 3); } TEST_F(DataTest, PointRemoval) { std::set<int> ids_remove; std::vector<int> ids_remove_v; int n = bin.size() * 0.5; std::vector<size_t> dist = {50, 100}; mltk::random::init(10); mltk::Data<double> bin_copy; bin_copy.copy(bin); EXPECT_EQ(bin_copy.size(), 150); EXPECT_EQ(bin_copy.points().size(), 150); EXPECT_EQ(bin_copy.dim(), 4); EXPECT_EQ(bin_copy.classesDistribution(), dist); EXPECT_EQ(bin_copy.classes().size(), 2); for (int i = 0; i < n; i++) { ids_remove.insert(mltk::random::intInRange(1, n)); } if (std::find(ids_remove.begin(), ids_remove.end(), 1) == ids_remove.end()) { ids_remove.insert(1); } if (std::find(ids_remove.begin(), ids_remove.end(), bin.size() - 1) == ids_remove.end()) { ids_remove.insert(bin.size()); } for (auto idx: ids_remove) { ids_remove_v.push_back(idx); if (!bin.removePoint(idx)) { std::clog << "Point " << idx << " not removed." << std::endl; } } auto sum_dist = mltk::Point<size_t>(bin.classesDistribution()).sum(); EXPECT_EQ(bin.size(), 150 - ids_remove.size()); EXPECT_EQ(bin.points().size(), 150 - ids_remove.size()); EXPECT_EQ(bin.dim(), 4); EXPECT_EQ(bin.size(), sum_dist); EXPECT_EQ(bin.classes().size(), 2); EXPECT_EQ(bin_copy.size(), 150); EXPECT_EQ(bin_copy.points().size(), 150); EXPECT_EQ(bin_copy.dim(), 4); EXPECT_EQ(bin_copy.classesDistribution(), dist); EXPECT_EQ(bin_copy.classes().size(), 2); EXPECT_NE(bin, bin_copy); bin_copy.removePoints(ids_remove_v); sum_dist = mltk::Point<size_t>(bin_copy.classesDistribution()).sum(); EXPECT_EQ(bin_copy.size(), 150 - ids_remove_v.size()); EXPECT_EQ(bin_copy.points().size(), 150 - ids_remove_v.size()); EXPECT_EQ(bin_copy.dim(), 4); EXPECT_EQ(bin_copy.size(), sum_dist); EXPECT_EQ(bin_copy.classes().size(), 2); EXPECT_TRUE(bin == bin_copy); bin_copy.removeFeatures({1, 2}); ASSERT_TRUE(bin_copy.dim() == 2); } TEST_F(DataTest, DataInsertion){ mltk::Data<double> copy_bin; std::vector<size_t> dist = {50, 100, 1}; std::vector<int> classes = {1, -1, 2}; copy_bin.copy(bin); copy_bin.insertPoint(mult, 70); ASSERT_EQ(copy_bin.size(), bin.size()+1); ASSERT_EQ(copy_bin.classesDistribution(), dist); ASSERT_EQ(copy_bin.classes(), classes); auto red = copy_bin.insertFeatures({1,2}); auto red1 = copy_bin.selectFeatures({1,2}, -1); for(int i = 0; i < copy_bin.size(); i++){ ASSERT_EQ(copy_bin(i)[0], red1(i)[0]); ASSERT_EQ(copy_bin(i)[1], red1(i)[1]); } for(int i = 0; i < copy_bin.size(); i++){ ASSERT_EQ(copy_bin(i)[0], red1(i)[0]); ASSERT_EQ(copy_bin(i)[1], red1(i)[1]); } auto sample = mult.sampling(75); std::vector<size_t> samp_dist = {25,25,25}; ASSERT_EQ(sample.classesDistribution(), samp_dist); mltk::Data<double> floatData(5, 5); for(auto& p: floatData){ mltk::random_init(*p, 42); *p *= 10; *p = mltk::normalize(*p, 2); //std::cout << *p << std::endl; ASSERT_EQ(p->norm(), 1); } std::cout << floatData << std::endl; ASSERT_EQ(floatData.size(), 5); ASSERT_EQ(floatData.dim(), 5); auto new_point = mltk::random_init<double>(floatData.dim(), 42); floatData.insertPoint(new_point); ASSERT_EQ(floatData.size(), 6); ASSERT_EQ(floatData.dim(), 5); ASSERT_EQ(floatData.classes().size(), 1); auto new_point1 = mltk::random_init<double>(floatData.dim(), 42); new_point1.Y() = 1; std::vector<size_t> dist1 = {floatData.size(),1}; floatData.insertPoint(new_point1); std::vector<size_t> dist2 = {floatData.size()}; ASSERT_EQ(floatData.size(), 7); ASSERT_EQ(floatData.dim(), 5); ASSERT_EQ(floatData.classes().size(), 2); floatData.computeClassesDistribution(); ASSERT_EQ(floatData.classesDistribution(), dist1); floatData.updatePointValue(floatData.size()-1, 0); ASSERT_EQ(floatData.classesDistribution(), dist2); ASSERT_EQ(floatData.classes().size(), 1); ASSERT_EQ(floatData.getLabels().size(), floatData.size()); ASSERT_EQ(mltk::utils::atod("0.151"), 0.151); ASSERT_EQ(mltk::utils::atod("-0.151"), -0.151); ASSERT_GT(mltk::utils::atod(mltk::utils::dtoa(0.151).c_str()), 0.150); ASSERT_LT(mltk::utils::atod(mltk::utils::dtoa(0.151).c_str()), 0.152); ASSERT_GT(mltk::utils::atod(mltk::utils::dtoa(-0.151).c_str()), -0.152); ASSERT_LT(mltk::utils::atod(mltk::utils::dtoa(-0.151).c_str()), -0.150); ASSERT_STREQ(mltk::utils::dtoa(1e-3).c_str(), "0.001"); ASSERT_STREQ(mltk::utils::itos(1000).c_str(), "1000"); ASSERT_STREQ(mltk::utils::itos(-1000).c_str(), "-1000"); ASSERT_STREQ(mltk::utils::dtoa(1E14).c_str(), "1e+14"); ASSERT_STREQ(mltk::utils::dtoa(1E14).c_str(), "1e+14"); ASSERT_STREQ(mltk::utils::dtoa(3E-14).c_str(), "3e-14"); } TEST_F(DataTest, DataSplit){ mltk::Data<double> data("pima.data"); auto split = mltk::validation::kfoldsplit(mult, 10, true, 42); std::vector<size_t> dist_train = {45, 45, 45}; std::vector<size_t> dist_test = {5, 5, 5}; for(const auto& s: split){ ASSERT_EQ(s.train.size(), 135); ASSERT_EQ(s.test.size(), 15); ASSERT_EQ(s.train.classesDistribution(), dist_train); ASSERT_EQ(s.test.classesDistribution(), dist_test); } split = mltk::validation::kfoldsplit(mult, 10, 10, true, 42); ASSERT_EQ(split.size(), 100); for(const auto& s: split){ ASSERT_EQ(s.train.size(), 135); ASSERT_EQ(s.test.size(), 15); ASSERT_EQ(s.train.classesDistribution(), dist_train); ASSERT_EQ(s.test.classesDistribution(), dist_test); } split = mltk::validation::kfoldsplit(mult, 3, false, 42); for(const auto& s: split){ ASSERT_EQ(s.train.size(), 100); ASSERT_EQ(s.test.size(), 50); for(const auto& point: s.test){ for(auto& x: *point){ std::cout << x << " "; } std::cout << std::endl; } std::cout << mltk::Point<size_t>(s.train.classesDistribution()) <<std::endl; std::cout << mltk::Point<size_t>(s.test.classesDistribution()) <<std::endl; } } TEST_F(DataTest, DataTransformation){ auto normalization = [](mltk::PointPointer<double> point){ *point = mltk::normalize(*point, 2); }; bin.apply(normalization); for(const auto p: bin){ EXPECT_GT(p->norm(), 0.999); EXPECT_LT(p->norm(), 1.01); } } TEST_F(DataTest, DatasetsTest){ auto spirals = mltk::datasets::make_spirals(800, 5, false, 2.5); auto blobs = mltk::datasets::make_blobs(100, 5, 2).dataset; auto reg = mltk::datasets::make_regression(100).dataset; ASSERT_EQ(spirals.size(), 800); ASSERT_EQ(spirals.dim(), 2); ASSERT_EQ(spirals.classes().size(), 5); ASSERT_EQ(blobs.size(), 500); ASSERT_EQ(blobs.dim(), 2); ASSERT_EQ(blobs.classes().size(), 5); ASSERT_EQ(reg.size(), 100); ASSERT_EQ(reg.dim(), 100); ASSERT_EQ(reg.classes().size(), 0); } TEST_F(DataTest, KernelTest){ mltk::Data<double> blobs = mltk::datasets::make_blobs(100, 2, 2, 1, -10, 10, true, true, 42).dataset; mltk::Kernel kernel(mltk::INNER_PRODUCT); kernel(blobs); ASSERT_EQ((blobs(0)*blobs(1)).sum(), kernel(blobs(0), blobs(1))); mltk::Kernel ckernel(mltk::CUSTOM); auto f = [](mltk::Point<double>& a, mltk::Point<double>& b, double param){ return (a*b).sum(); }; ckernel(blobs, f); ASSERT_EQ(kernel.size(), ckernel.size()); for(int i = 0; i < ckernel.size(); i++){ for(int j = 0; j < ckernel.size(); j++){ ASSERT_EQ(ckernel[i][j], kernel[i][j]); } } mltk::Kernel gkernel(mltk::GAUSSIAN, 0.5); mltk::Kernel cgkernel(mltk::CUSTOM, 0.5); gkernel(blobs); auto gaussian = [](mltk::Point<double>& a, mltk::Point<double>& b, double param){ return std::exp(-1*((a-b)*(a-b)).sum() * param); }; cgkernel(blobs, gaussian); ASSERT_EQ(gkernel.size(), cgkernel.size()); for(int i = 0; i < cgkernel.size(); i++){ for(int j = 0; j < cgkernel.size(); j++){ ASSERT_EQ(cgkernel[i][j], gkernel[i][j]); } } }
33.374346
94
0.609695
DCC-UFJF
cb48bd399b04a33bf49054d0bcf397b0e1edc63b
1,898
cpp
C++
test/launcher/verify_bintree.cpp
baziotis/rv
e0e9373bed333cf19370d811ecfd1146d605118a
[ "Apache-2.0" ]
71
2017-03-03T01:36:28.000Z
2022-02-25T19:57:12.000Z
test/launcher/verify_bintree.cpp
baziotis/rv
e0e9373bed333cf19370d811ecfd1146d605118a
[ "Apache-2.0" ]
48
2017-04-05T16:41:47.000Z
2021-06-09T09:52:36.000Z
test/launcher/verify_bintree.cpp
baziotis/rv
e0e9373bed333cf19370d811ecfd1146d605118a
[ "Apache-2.0" ]
21
2017-03-01T16:04:35.000Z
2021-09-15T13:38:24.000Z
#include<iostream> #include <cassert> #include "launcherTools.h" struct Node { float data; int left; int right; Node() : left(-1) , right(-1) , data(0.0f) {} }; extern "C" { int foo(Node * nodes, float elem); int8 foo_SIMD(Node * nodes, float8 elem); } void insert(Node * nodes, int i, float elem, int & top) { if (top == 0) { nodes[0].data = elem; ++top; return; } if (nodes[i].data > elem) { if (nodes[i].left > 0) insert(nodes, nodes[i].left, elem, top); else { int j = top++; nodes[i].left = j; nodes[j].data = elem; } } else if (elem > nodes[i].data) { if (nodes[i].right > 0) insert(nodes, nodes[i].right, elem, top); else { int j = top++; nodes[i].right = j; nodes[j].data = elem; } } } int main(int argc, char ** argv) { Node nodes[256]; int top = 0; const uint numElems = 128; float known[numElems]; for (int i = 0; i < numElems; ++i) { known[i] = wfvRand(); insert(nodes, 0, known[i], top); } const uint rounds = 10; for (int i = 0; i < rounds; ++i) { // random lookup input // we pick some known elements to get enough hits float elems[8]; for (int l = 0; l < 8 ; ++l) { elems[l] = rand() > 0.0f ? known[rand() % numElems] : wfvRand(); } float8 elemVec = toVec<float, float8>(elems); int8 foundVec = foo_SIMD(nodes, elemVec); int found[8]; toArray<int, int8>(foundVec, found); // compare result against scalar function bool broken = false; for (int l = 0; l < 8; ++l) { int expectedRes = foo(nodes, elems[l]); if (found[l] != expectedRes) { std::cerr << "MISMATCH!\n"; std::cerr << l << " : elem = " << elems[l] << " expected result " << expectedRes << " but was " << found[l] << "\n"; broken = true; } } if (broken) return -1; } return 0; }
21.088889
124
0.536881
baziotis
cb4b073bad58f8f50607fbae531841b8474d360d
416
hpp
C++
inc/Ball.hpp
Swaift/rpg
b4e9ecb68b85c6859a3984aa1234f377c56633fa
[ "MIT" ]
2
2017-03-02T01:00:37.000Z
2017-03-02T01:00:47.000Z
inc/Ball.hpp
Swaift/pong
b4e9ecb68b85c6859a3984aa1234f377c56633fa
[ "MIT" ]
null
null
null
inc/Ball.hpp
Swaift/pong
b4e9ecb68b85c6859a3984aa1234f377c56633fa
[ "MIT" ]
null
null
null
#ifndef BALL_HPP #define BALL_HPP #include <SFML/Graphics.hpp> namespace sf { class Ball: public CircleShape { public: Ball(float radius); void reset(); float getDx(); float getDy(); void setDx(float dx); void setDy(float dy); float getCenter(); private: float dx, dy; }; } #endif // BALL_HPP
18.909091
36
0.509615
Swaift
cb4d7af798a271e1d7cce11e5ced263db8aa9735
19,465
hpp
C++
pennylane_lightning/src/gates/OpToMemberFuncPtr.hpp
AmintorDusko/pennylane-lightning
9554a95842de9d7759ce96bfa75857e0c9ca756b
[ "Apache-2.0" ]
null
null
null
pennylane_lightning/src/gates/OpToMemberFuncPtr.hpp
AmintorDusko/pennylane-lightning
9554a95842de9d7759ce96bfa75857e0c9ca756b
[ "Apache-2.0" ]
null
null
null
pennylane_lightning/src/gates/OpToMemberFuncPtr.hpp
AmintorDusko/pennylane-lightning
9554a95842de9d7759ce96bfa75857e0c9ca756b
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Xanadu Quantum Technologies Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file * Defines template classes to extract member function pointers for * metaprogramming. Also defines some utility functions that calls such * pointers. */ #pragma once #include "GateOperation.hpp" #include "cassert" #include <complex> #include <vector> namespace Pennylane::Gates { /** * @brief Return a specific member function pointer for a given gate operation. * See specialized classes. */ template <class PrecisionT, class ParamT, class GateImplementation, GateOperation gate_op> struct GateOpToMemberFuncPtr { // raises compile error when used static_assert( gate_op != GateOperation::Matrix, "GateOpToMemberFuncPtr is not defined for GateOperation::Matrix."); static_assert(gate_op == GateOperation::Matrix, "GateOpToMemberFuncPtr is not defined for the given gate. " "When you define a new GateOperation, check that you also " "have added the corresponding entry in " "GateOpToMemberFuncPtr."); constexpr static auto value = nullptr; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::Identity> { constexpr static auto value = &GateImplementation::template applyIdentity<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::PauliX> { constexpr static auto value = &GateImplementation::template applyPauliX<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::PauliY> { constexpr static auto value = &GateImplementation::template applyPauliY<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::PauliZ> { constexpr static auto value = &GateImplementation::template applyPauliZ<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::Hadamard> { constexpr static auto value = &GateImplementation::template applyHadamard<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::S> { constexpr static auto value = &GateImplementation::template applyS<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::T> { constexpr static auto value = &GateImplementation::template applyT<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::PhaseShift> { constexpr static auto value = &GateImplementation::template applyPhaseShift<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::RX> { constexpr static auto value = &GateImplementation::template applyRX<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::RY> { constexpr static auto value = &GateImplementation::template applyRY<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::RZ> { constexpr static auto value = &GateImplementation::template applyRZ<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::Rot> { constexpr static auto value = &GateImplementation::template applyRot<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CNOT> { constexpr static auto value = &GateImplementation::template applyCNOT<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CY> { constexpr static auto value = &GateImplementation::template applyCY<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CZ> { constexpr static auto value = &GateImplementation::template applyCZ<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::SWAP> { constexpr static auto value = &GateImplementation::template applySWAP<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::IsingXX> { constexpr static auto value = &GateImplementation::template applyIsingXX<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::IsingYY> { constexpr static auto value = &GateImplementation::template applyIsingYY<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::IsingZZ> { constexpr static auto value = &GateImplementation::template applyIsingZZ<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::ControlledPhaseShift> { constexpr static auto value = &GateImplementation::template applyControlledPhaseShift<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CRX> { constexpr static auto value = &GateImplementation::template applyCRX<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CRY> { constexpr static auto value = &GateImplementation::template applyCRY<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CRZ> { constexpr static auto value = &GateImplementation::template applyCRZ<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CRot> { constexpr static auto value = &GateImplementation::template applyCRot<PrecisionT, ParamT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::Toffoli> { constexpr static auto value = &GateImplementation::template applyToffoli<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::CSWAP> { constexpr static auto value = &GateImplementation::template applyCSWAP<PrecisionT>; }; template <class PrecisionT, class ParamT, class GateImplementation> struct GateOpToMemberFuncPtr<PrecisionT, ParamT, GateImplementation, GateOperation::MultiRZ> { constexpr static auto value = &GateImplementation::template applyMultiRZ<PrecisionT, ParamT>; }; /** * @brief Return a specific member function pointer for a given generator * operation. See specialized classes. */ template <class PrecisionT, class GateImplementation, GeneratorOperation gntr_op> struct GeneratorOpToMemberFuncPtr { // raises compile error when used static_assert( sizeof(GateImplementation) == -1, "GeneratorOpToMemberFuncPtr is not defined for the given generator. " "When you define a new GeneratorOperation, check that you also " "have added the corresponding entry in GeneratorOpToMemberFuncPtr."); }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::RX> { constexpr static auto value = &GateImplementation::template applyGeneratorRX<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::RY> { constexpr static auto value = &GateImplementation::template applyGeneratorRY<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::RZ> { constexpr static auto value = &GateImplementation::template applyGeneratorRZ<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::PhaseShift> { constexpr static auto value = &GateImplementation::template applyGeneratorPhaseShift<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::IsingXX> { constexpr static auto value = &GateImplementation::template applyGeneratorIsingXX<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::IsingYY> { constexpr static auto value = &GateImplementation::template applyGeneratorIsingYY<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::IsingZZ> { constexpr static auto value = &GateImplementation::template applyGeneratorIsingZZ<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::CRX> { constexpr static auto value = &GateImplementation::template applyGeneratorCRX<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::CRY> { constexpr static auto value = &GateImplementation::template applyGeneratorCRY<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::CRZ> { constexpr static auto value = &GateImplementation::template applyGeneratorCRZ<PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::ControlledPhaseShift> { constexpr static auto value = &GateImplementation::template applyGeneratorControlledPhaseShift< PrecisionT>; }; template <class PrecisionT, class GateImplementation> struct GeneratorOpToMemberFuncPtr<PrecisionT, GateImplementation, GeneratorOperation::MultiRZ> { constexpr static auto value = &GateImplementation::template applyGeneratorMultiRZ<PrecisionT>; }; /// @cond DEV namespace Internal { /** * @brief Gate operation pointer type for a statevector. See all specialized * types. */ template <class SVType, class ParamT, size_t num_params> struct GateMemFuncPtr { static_assert(num_params < 2 || num_params == 3, "The given num_params is not supported."); }; /** * @brief Function pointer type for a gate operation without parameters. */ template <class SVType, class ParamT> struct GateMemFuncPtr<SVType, ParamT, 0> { using Type = void (SVType::*)(const std::vector<size_t> &, bool); }; /** * @brief Function pointer type for a gate operation with a single parameter. */ template <class SVType, class ParamT> struct GateMemFuncPtr<SVType, ParamT, 1> { using Type = void (SVType::*)(const std::vector<size_t> &, bool, ParamT); }; /** * @brief Function pointer type for a gate operation with three parameters. */ template <class SVType, class ParamT> struct GateMemFuncPtr<SVType, ParamT, 3> { using Type = void (SVType::*)(const std::vector<size_t> &, bool, ParamT, ParamT, ParamT); }; /** * @brief A convenient alias for GateMemFuncPtr. */ template <class SVType, class ParamT, size_t num_params> using GateMemFuncPtrT = typename GateMemFuncPtr<SVType, ParamT, num_params>::Type; /** * @brief Gate operation pointer type. See all specialized types. */ template <class PrecisionT, class ParamT, size_t num_params> struct GateFuncPtr { static_assert(num_params < 2 || num_params == 3, "The given num_params is not supported."); }; /** * @brief Pointer type for a gate operation without parameters. */ template <class PrecisionT, class ParamT> struct GateFuncPtr<PrecisionT, ParamT, 0> { using Type = void (*)(std::complex<PrecisionT> *, size_t, const std::vector<size_t> &, bool); }; /** * @brief Pointer type for a gate operation with a single parameter */ template <class PrecisionT, class ParamT> struct GateFuncPtr<PrecisionT, ParamT, 1> { using Type = void (*)(std::complex<PrecisionT> *, size_t, const std::vector<size_t> &, bool, ParamT); }; /** * @brief Pointer type for a gate operation with three parameters */ template <class PrecisionT, class ParamT> struct GateFuncPtr<PrecisionT, ParamT, 3> { using Type = void (*)(std::complex<PrecisionT> *, size_t, const std::vector<size_t> &, bool, ParamT, ParamT, ParamT); }; /** * @brief Pointer type for a generator operation */ template <class PrecisionT> struct GeneratorFuncPtr { using Type = PrecisionT (*)(std::complex<PrecisionT> *, size_t, const std::vector<size_t> &, bool); }; } // namespace Internal /// @endcond /** * @brief Convenient type alias for GateFuncPtr. */ template <class PrecisionT, class ParamT, size_t num_params> using GateFuncPtrT = typename Internal::GateFuncPtr<PrecisionT, ParamT, num_params>::Type; /** * @brief Convenient type alias for GeneratorFuncPtrT. */ template <class PrecisionT> using GeneratorFuncPtrT = typename Internal::GeneratorFuncPtr<PrecisionT>::Type; /** * @defgroup Call gate operation with provided arguments * * @tparam PrecisionT Floating point type for the state-vector. * @tparam ParamT Floating point type for the gate parameters. * @param func Function pointer for the gate operation. * @param data Data pointer the gate is applied to * @param num_qubits The number of qubits of the state-vector. * @param wires Wires the gate applies to. * @param inverse If true, we apply the inverse of the gate. * @param params The list of gate parameters. */ /// @{ /** * @brief Overload for a gate operation without parameters */ template <class PrecisionT, class ParamT> inline void callGateOps(GateFuncPtrT<PrecisionT, ParamT, 0> func, std::complex<PrecisionT> *data, size_t num_qubits, const std::vector<size_t> &wires, bool inverse, [[maybe_unused]] const std::vector<ParamT> &params) { assert(params.empty()); func(data, num_qubits, wires, inverse); } /** * @brief Overload for a gate operation for a single parameter */ template <class PrecisionT, class ParamT> inline void callGateOps(GateFuncPtrT<PrecisionT, ParamT, 1> func, std::complex<PrecisionT> *data, size_t num_qubits, const std::vector<size_t> &wires, bool inverse, const std::vector<ParamT> &params) { assert(params.size() == 1); func(data, num_qubits, wires, inverse, params[0]); } /** * @brief Overload for a gate operation for three parameters */ template <class PrecisionT, class ParamT> inline void callGateOps(GateFuncPtrT<PrecisionT, ParamT, 3> func, std::complex<PrecisionT> *data, size_t num_qubits, const std::vector<size_t> &wires, bool inverse, const std::vector<ParamT> &params) { assert(params.size() == 3); func(data, num_qubits, wires, inverse, params[0], params[1], params[2]); } /// @} /** * @brief Call a generator operation. * * @tparam PrecisionT Floating point type for the state-vector. * @return Scaling factor */ template <class PrecisionT> inline PrecisionT callGeneratorOps(GeneratorFuncPtrT<PrecisionT> func, std::complex<PrecisionT> *data, size_t num_qubits, const std::vector<size_t> &wires, bool adj) { return func(data, num_qubits, wires, adj); } } // namespace Pennylane::Gates
42.407407
80
0.694631
AmintorDusko
cb4e20da2cdd41de90bbd915cb72bf33165d1b4f
516
cpp
C++
examples/SysTick/Main.cpp
marangisto/stm32
a3972918adb734597ecd122e2546670dad3cd990
[ "MIT" ]
null
null
null
examples/SysTick/Main.cpp
marangisto/stm32
a3972918adb734597ecd122e2546670dad3cd990
[ "MIT" ]
1
2019-08-31T20:54:29.000Z
2019-09-01T07:11:43.000Z
examples/SysTick/Main.cpp
marangisto/stm32f0
a3972918adb734597ecd122e2546670dad3cd990
[ "MIT" ]
null
null
null
#include <gpio.h> using namespace stm32f0; using namespace gpio; typedef output_t<PC8> led_a; typedef output_t<PC9> led_b; int main() { led_a::setup(); led_b::setup(); for (;;) { static uint32_t next_a = 0, next_b = 0; uint32_t now = sys_tick::count(); if (now >= next_a) { led_a::toggle(); next_a = now + 101; } if (now >= next_b) { led_b::toggle(); next_b = now + 103; } } }
15.636364
47
0.478682
marangisto
cb4f44cc4f4f1627f63f867b8052d51a768fcf7a
2,170
hpp
C++
include/signals/detail/connection_impl.hpp
a-n-t-h-o-n-y/signals
2db5f083a814b970dfd0f797873d9a894d80bf42
[ "MIT" ]
2
2018-09-03T03:51:41.000Z
2020-05-29T06:27:49.000Z
include/signals/detail/connection_impl.hpp
a-n-t-h-o-n-y/signals
2db5f083a814b970dfd0f797873d9a894d80bf42
[ "MIT" ]
null
null
null
include/signals/detail/connection_impl.hpp
a-n-t-h-o-n-y/signals
2db5f083a814b970dfd0f797873d9a894d80bf42
[ "MIT" ]
1
2020-11-03T05:37:27.000Z
2020-11-03T05:37:27.000Z
#ifndef SIGNALS_DETAIL_CONNECTION_IMPL_HPP #define SIGNALS_DETAIL_CONNECTION_IMPL_HPP #include <memory> #include <mutex> #include <utility> #include "../connection.hpp" #include "../slot.hpp" #include "connection_impl_base.hpp" namespace sig { class Connection; template <typename Signature> class Connection_impl; // Implementation class for Connection. This class owns the Slot involved in // the connection. Inherits from Connection_impl_base, which implements shared // connection block counts. template <typename R, typename... Args> class Connection_impl<R(Args...)> : public Connection_impl_base { public: using Extended_slot_t = Slot<R(Connection const&, Args...)>; public: Connection_impl() : slot_{}, connected_{false} {} explicit Connection_impl(Slot<R(Args...)> s) : slot_{std::move(s)}, connected_{true} {} public: // Constructs a Connection_impl with an extended slot and connection. This // binds the connection to the first parameter of the Extended_slot_t // function. The slot function type then matches the signal function type. // Then copies tracked items from the extended slot into the new slot. auto emplace_extended(Extended_slot_t const& es, Connection const& c) -> Connection_impl& { auto const lock = std::lock_guard{mtx_}; connected_ = true; slot_.slot_function() = [c, es](Args&&... args) { return es.slot_function()(c, std::forward<Args>(args)...); }; for (std::weak_ptr<void> const& wp : es.get_tracked_container()) { slot_.track(wp); } return *this; } void disconnect() override { auto const lock = std::lock_guard{mtx_}; connected_ = false; } auto connected() const -> bool override { auto const lock = std::lock_guard{mtx_}; return connected_; } auto get_slot() -> Slot<R(Args...)>& { return slot_; } auto get_slot() const -> Slot<R(Args...)> const& { return slot_; } private: Slot<R(Args...)> slot_; bool connected_; }; } // namespace sig #endif // SIGNALS_DETAIL_CONNECTION_IMPL_HPP
28.933333
78
0.659908
a-n-t-h-o-n-y
cb51b86338f4c2de18524d860ed65f32f486832f
336
cpp
C++
cpp1/cppio.cpp
CGCC-CS/csc240spring18
824026556610976b26ad0c0fa2f51ef244524180
[ "MIT" ]
null
null
null
cpp1/cppio.cpp
CGCC-CS/csc240spring18
824026556610976b26ad0c0fa2f51ef244524180
[ "MIT" ]
null
null
null
cpp1/cppio.cpp
CGCC-CS/csc240spring18
824026556610976b26ad0c0fa2f51ef244524180
[ "MIT" ]
null
null
null
#include<iostream> #include<string> using namespace std; int main() { int count; string str; cout << "Enter a number: "; cin >> count; cout << "Enter a string: "; cin >> str; // Only gets characters until the next whitespace! for(int ii=0;ii<count;ii++) { cout << ii << " : " << str << endl; } return 0; }
15.272727
66
0.574405
CGCC-CS
cb53e73c54c9762e43096e774582efa54477a5a5
10,245
cpp
C++
src/catalog/catalog_util.cpp
xinzhang1234/peloton
9b11d92dd5a2a0b32d5c39a9ba0b1aa45fe0b654
[ "Apache-2.0" ]
7
2017-03-12T01:57:48.000Z
2022-03-16T12:44:07.000Z
src/catalog/catalog_util.cpp
xinzhang1234/peloton
9b11d92dd5a2a0b32d5c39a9ba0b1aa45fe0b654
[ "Apache-2.0" ]
null
null
null
src/catalog/catalog_util.cpp
xinzhang1234/peloton
9b11d92dd5a2a0b32d5c39a9ba0b1aa45fe0b654
[ "Apache-2.0" ]
2
2017-03-30T00:43:50.000Z
2021-07-21T06:27:44.000Z
//===----------------------------------------------------------------------===// // // Peloton // // catalog_util.cpp // // Identification: src/catalog/catalog_util.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "catalog/catalog_util.h" namespace peloton { namespace catalog { /** * Inserts a tuple in a table */ void InsertTuple(storage::DataTable *table, std::unique_ptr<storage::Tuple> tuple, concurrency::Transaction *txn) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); bool single_statement_txn = false; if (txn == nullptr) { single_statement_txn = true; txn = txn_manager.BeginTransaction(); } std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); planner::InsertPlan node(table, std::move(tuple)); executor::InsertExecutor executor(&node, context.get()); executor.Init(); executor.Execute(); if (single_statement_txn) { txn_manager.CommitTransaction(txn); } } void DeleteTuple(storage::DataTable *table, oid_t id, concurrency::Transaction *txn) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); bool single_statement_txn = false; if (txn == nullptr) { single_statement_txn = true; txn = txn_manager.BeginTransaction(); } std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); LOG_TRACE("Removing tuple with id %d from table %s", (int)id, table->GetName().c_str()); LOG_TRACE("Transaction ID: %d", (int)txn->GetTransactionId()); // Delete planner::DeletePlan delete_node(table, false); executor::DeleteExecutor delete_executor(&delete_node, context.get()); // Predicate // WHERE id_in_table = id expression::TupleValueExpression *tup_val_exp = new expression::TupleValueExpression(type::Type::INTEGER, 0, 0); auto tmp_value = type::ValueFactory::GetIntegerValue(id); expression::ConstantValueExpression *const_val_exp = new expression::ConstantValueExpression(tmp_value); auto predicate = new expression::ComparisonExpression( ExpressionType::COMPARE_EQUAL, tup_val_exp, const_val_exp); // Seq scan std::vector<oid_t> column_ids = {0, 1}; std::unique_ptr<planner::SeqScanPlan> seq_scan_node( new planner::SeqScanPlan(table, predicate, column_ids)); executor::SeqScanExecutor seq_scan_executor(seq_scan_node.get(), context.get()); // Parent-Child relationship delete_node.AddChild(std::move(seq_scan_node)); delete_executor.AddChild(&seq_scan_executor); delete_executor.Init(); delete_executor.Execute(); if (single_statement_txn) { txn_manager.CommitTransaction(txn); } } /** * Generate a database catalog tuple * Input: The table schema, the database id, the database name * Returns: The generated tuple */ std::unique_ptr<storage::Tuple> GetDatabaseCatalogTuple( const catalog::Schema *schema, oid_t database_id, std::string database_name, type::AbstractPool *pool) { std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true)); auto val1 = type::ValueFactory::GetIntegerValue(database_id); auto val2 = type::ValueFactory::GetVarcharValue(database_name, nullptr); tuple->SetValue(0, val1, pool); tuple->SetValue(1, val2, pool); return std::move(tuple); } /** * Generate a database metric tuple * Input: The table schema, the database id, number of txn committed, * number of txn aborted, the timestamp * Returns: The generated tuple */ std::unique_ptr<storage::Tuple> GetDatabaseMetricsCatalogTuple( const catalog::Schema *schema, oid_t database_id, int64_t commit, int64_t abort, int64_t time_stamp) { std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true)); auto val1 = type::ValueFactory::GetIntegerValue(database_id); auto val2 = type::ValueFactory::GetIntegerValue(commit); auto val3 = type::ValueFactory::GetIntegerValue(abort); auto val4 = type::ValueFactory::GetIntegerValue(time_stamp); tuple->SetValue(0, val1, nullptr); tuple->SetValue(1, val2, nullptr); tuple->SetValue(2, val3, nullptr); tuple->SetValue(3, val4, nullptr); return std::move(tuple); } /** * Generate a table metric tuple * Input: The table schema, the database id, the table id, number of tuples * read, updated, deleted inserted, the timestamp * Returns: The generated tuple */ std::unique_ptr<storage::Tuple> GetTableMetricsCatalogTuple( const catalog::Schema *schema, oid_t database_id, oid_t table_id, int64_t reads, int64_t updates, int64_t deletes, int64_t inserts, int64_t time_stamp) { std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true)); auto val1 = type::ValueFactory::GetIntegerValue(database_id); auto val2 = type::ValueFactory::GetIntegerValue(table_id); auto val3 = type::ValueFactory::GetIntegerValue(reads); auto val4 = type::ValueFactory::GetIntegerValue(updates); auto val5 = type::ValueFactory::GetIntegerValue(deletes); auto val6 = type::ValueFactory::GetIntegerValue(inserts); auto val7 = type::ValueFactory::GetIntegerValue(time_stamp); tuple->SetValue(0, val1, nullptr); tuple->SetValue(1, val2, nullptr); tuple->SetValue(2, val3, nullptr); tuple->SetValue(3, val4, nullptr); tuple->SetValue(4, val5, nullptr); tuple->SetValue(5, val6, nullptr); tuple->SetValue(6, val7, nullptr); return std::move(tuple); } /** * Generate a index metric tuple * Input: The table schema, the database id, the table id, the index id, * number of tuples read, deleted inserted, the timestamp * Returns: The generated tuple */ std::unique_ptr<storage::Tuple> GetIndexMetricsCatalogTuple( const catalog::Schema *schema, oid_t database_id, oid_t table_id, oid_t index_id, int64_t reads, int64_t deletes, int64_t inserts, int64_t time_stamp) { std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true)); auto val1 = type::ValueFactory::GetIntegerValue(database_id); auto val2 = type::ValueFactory::GetIntegerValue(table_id); auto val3 = type::ValueFactory::GetIntegerValue(index_id); auto val4 = type::ValueFactory::GetIntegerValue(reads); auto val5 = type::ValueFactory::GetIntegerValue(deletes); auto val6 = type::ValueFactory::GetIntegerValue(inserts); auto val7 = type::ValueFactory::GetIntegerValue(time_stamp); tuple->SetValue(0, val1, nullptr); tuple->SetValue(1, val2, nullptr); tuple->SetValue(2, val3, nullptr); tuple->SetValue(3, val4, nullptr); tuple->SetValue(4, val5, nullptr); tuple->SetValue(5, val6, nullptr); tuple->SetValue(6, val7, nullptr); return std::move(tuple); } /** * Generate a query metric tuple * Input: The table schema, the query string, database id, number of * tuples read, updated, deleted inserted, the timestamp * Returns: The generated tuple */ std::unique_ptr<storage::Tuple> GetQueryMetricsCatalogTuple( const catalog::Schema *schema, std::string query_name, oid_t database_id, int64_t num_params, stats::QueryMetric::QueryParamBuf type_buf, stats::QueryMetric::QueryParamBuf format_buf, stats::QueryMetric::QueryParamBuf val_buf, int64_t reads, int64_t updates, int64_t deletes, int64_t inserts, int64_t latency, int64_t cpu_time, int64_t time_stamp, type::AbstractPool *pool) { std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true)); auto val1 = type::ValueFactory::GetVarcharValue(query_name, nullptr); auto val2 = type::ValueFactory::GetIntegerValue(database_id); auto val3 = type::ValueFactory::GetIntegerValue(num_params); type::Value param_type = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY); type::Value param_format = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY); type::Value param_value = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY); if (num_params != 0) { param_type = type::ValueFactory::GetVarbinaryValue(type_buf.buf, type_buf.len, false); param_format = type::ValueFactory::GetVarbinaryValue(format_buf.buf, format_buf.len, false); param_value = type::ValueFactory::GetVarbinaryValue(val_buf.buf, val_buf.len, false); } auto val7 = type::ValueFactory::GetIntegerValue(reads); auto val8 = type::ValueFactory::GetIntegerValue(updates); auto val9 = type::ValueFactory::GetIntegerValue(deletes); auto val10 = type::ValueFactory::GetIntegerValue(inserts); auto val11 = type::ValueFactory::GetIntegerValue(latency); auto val12 = type::ValueFactory::GetIntegerValue(cpu_time); auto val13 = type::ValueFactory::GetIntegerValue(time_stamp); tuple->SetValue(0, val1, pool); tuple->SetValue(1, val2, nullptr); tuple->SetValue(2, val3, nullptr); tuple->SetValue(3, param_type, pool); tuple->SetValue(4, param_format, pool); tuple->SetValue(5, param_value, pool); tuple->SetValue(6, val7, nullptr); tuple->SetValue(7, val8, nullptr); tuple->SetValue(8, val9, nullptr); tuple->SetValue(9, val10, nullptr); tuple->SetValue(10, val11, nullptr); tuple->SetValue(11, val12, nullptr); tuple->SetValue(12, val13, nullptr); return std::move(tuple); } /** * Generate a table catalog tuple * Input: The table schema, the table id, the table name, the database id, and * the database name * Returns: The generated tuple */ std::unique_ptr<storage::Tuple> GetTableCatalogTuple( const catalog::Schema *schema, oid_t table_id, std::string table_name, oid_t database_id, std::string database_name, type::AbstractPool *pool) { std::unique_ptr<storage::Tuple> tuple(new storage::Tuple(schema, true)); auto val1 = type::ValueFactory::GetIntegerValue(table_id); auto val2 = type::ValueFactory::GetVarcharValue(table_name, nullptr); auto val3 = type::ValueFactory::GetIntegerValue(database_id); auto val4 = type::ValueFactory::GetVarcharValue(database_name, nullptr); tuple->SetValue(0, val1, pool); tuple->SetValue(1, val2, pool); tuple->SetValue(2, val3, pool); tuple->SetValue(3, val4, pool); return std::move(tuple); } } }
37.665441
85
0.711957
xinzhang1234
cb54519037742793b0c149c87545388006a38b6a
2,343
cpp
C++
tf2_bot_detector_updater/Update_MSIX.cpp
Magicrafter13/tf2_bot_detector
4cb43ae7e90fc5a084bef7d572af5bee1b10f389
[ "MIT" ]
1
2021-01-06T17:57:33.000Z
2021-01-06T17:57:33.000Z
tf2_bot_detector_updater/Update_MSIX.cpp
cyrusParvereshi/tf2_bot_detector
4cb43ae7e90fc5a084bef7d572af5bee1b10f389
[ "MIT" ]
null
null
null
tf2_bot_detector_updater/Update_MSIX.cpp
cyrusParvereshi/tf2_bot_detector
4cb43ae7e90fc5a084bef7d572af5bee1b10f389
[ "MIT" ]
null
null
null
#include "Update_MSIX.h" #include "Common.h" #include <mh/source_location.hpp> #include <mh/text/codecvt.hpp> #include <mh/text/format.hpp> #include <iostream> #include <Windows.h> #undef max #undef min #include <winrt/Windows.ApplicationModel.h> #include <winrt/Windows.Management.Deployment.h> #include <winrt/Windows.Foundation.h> #include <winrt/Windows.Foundation.Collections.h> #pragma comment(lib, "windowsapp") using namespace tf2_bot_detector::Updater; using namespace winrt::Windows::ApplicationModel; using namespace winrt::Windows::Foundation; using namespace winrt::Windows::Foundation::Collections; using namespace winrt::Windows::Management::Deployment; int tf2_bot_detector::Updater::Update_MSIX() try { std::cerr << "Attempting to install via API..." << std::endl; const auto mainBundleURL = mh::change_encoding<wchar_t>(s_CmdLineArgs.m_SourcePath); std::wcerr << "Main bundle URL: " << mainBundleURL; const Uri uri = Uri(winrt::param::hstring(mainBundleURL)); IVector<Uri> deps{ winrt::single_threaded_vector<Uri>() }; unsigned bits = 86; { SYSTEM_INFO sysInfo; GetNativeSystemInfo(&sysInfo); if (sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) bits = 64; } const auto depURL = mh::format(L"https://tf2bd-util.pazer.us/AppInstaller/vcredist.x{}.msix", bits); std::wcerr << "Dependency URL: " << depURL << std::endl; deps.Append(Uri(depURL)); PackageManager mgr; std::cerr << "Starting async update..." << std::endl; auto task = mgr.AddPackageAsync(uri, deps, DeploymentOptions::ForceApplicationShutdown); std::cerr << "Waiting for results..." << std::endl; auto waitStatus = task.wait_for(TimeSpan::max()); if (waitStatus != AsyncStatus::Completed) { std::wcerr << "Error encountered during async update: " << task.ErrorCode() << ": " << task.get().ErrorText().c_str(); return false; } else if (waitStatus == AsyncStatus::Completed) { std::cerr << "Update complete" << std::endl; } else { std::cerr << "Unknown update result" << std::endl; } std::cerr << "Reopening tool..." << std::endl; ShellExecuteA(nullptr, "open", "tf2bd:", nullptr, nullptr, SW_SHOWNORMAL); return 0; } catch (const std::exception& e) { std::cerr << mh::format("Unhandled exception ({}) in {}: {}", typeid(e).name(), __FUNCTION__, e.what()) << std::endl; return 2; }
28.228916
101
0.706359
Magicrafter13
cb54869797df94699ba268bbf56f585d276f56a4
7,876
cpp
C++
test/test_string_stream_u16.cpp
mhx/etl
9931339605511ab4641fcd7bf47293a17bd551fa
[ "MIT" ]
1,159
2015-01-05T13:18:58.000Z
2022-03-31T16:43:48.000Z
test/test_string_stream_u16.cpp
mhx/etl
9931339605511ab4641fcd7bf47293a17bd551fa
[ "MIT" ]
383
2015-04-26T08:04:40.000Z
2022-03-31T09:25:56.000Z
test/test_string_stream_u16.cpp
mhx/etl
9931339605511ab4641fcd7bf47293a17bd551fa
[ "MIT" ]
248
2015-01-13T07:50:30.000Z
2022-03-31T21:55:37.000Z
/****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl https://www.etlcpp.com Copyright(c) 2020 jwellbelove 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 "unit_test_framework.h" #include <ostream> #include <sstream> #include <iomanip> #include "etl/u16string_stream.h" #include "etl/u16string.h" #include "etl/format_spec.h" #undef STR #define STR(x) u##x namespace { using String = etl::u16string<50>; using IString = etl::iu16string; using Stream = etl::u16string_stream; using Format = etl::u16format_spec; //*********************************** struct Custom { int x; int y; }; //*********************************** Stream& operator <<(Stream& ss, const Custom& value) { ss << STR("X = ") << value.x << STR(" : Y = ") << value.y; return ss; } } namespace etl { //*********************************** std::ostream& operator << (std::ostream& os, const IString& str) { for (auto c : str) { os << c; } return os; } } namespace { SUITE(test_string_stream) { //************************************************************************* TEST(test_default_format_from_const_char) { String str; Stream ss(str); int value = 123; String hello(STR("Hello")); ss << hello << STR(" World ") << value; String result = ss.str(); CHECK_EQUAL(String(STR("Hello World 123")), result); } //************************************************************************* TEST(test_default_format_from_char) { String str; Stream ss(str); int value = 123; String hello(STR("Hello")); ss << hello << const_cast<char16_t*>(STR(" World ")) << value; String result = ss.str(); CHECK_EQUAL(String(STR("Hello World 123")), result); } //************************************************************************* TEST(test_custom_format) { String str; Format format = Format().base(10).width(10).fill(STR('#')); Stream ss(str); int value = 123; String hello(STR("Hello")); ss << format << hello << STR("World") << value; String result = ss.str(); CHECK_EQUAL(String(STR("#####Hello#####World#######123")), result); } //************************************************************************* TEST(test_custom_multi_format) { String str; Format format1 = Format().base(10).width(10).fill(STR('#')); Format format2 = Format().base(10).width(8).fill(STR('*')).left(); Format format3 = Format().base(16).width(4).fill(STR(' ')).right(); Stream ss(str); int value = 123; String hello(STR("Hello")); ss << format1 << hello << format2 << STR("World") << format3 << value; String result = ss.str(); CHECK_EQUAL(String(STR("#####HelloWorld*** 7b")), result); } //************************************************************************* TEST(test_custom_inline_format) { String str; Stream ss(str); int value = 123456; ss << etl::setw(20) << etl::setfill(STR('-')) << etl::left; ss << etl::bin << value; CHECK_EQUAL(String(STR("11110001001000000---")), ss.str()); ss.str().clear(); ss << etl::oct << value; CHECK_EQUAL(String(STR("361100--------------")), ss.str()); ss.str().clear(); ss << etl::dec << value; CHECK_EQUAL(String(STR("123456--------------")), ss.str()); ss.str().clear(); ss << etl::hex << etl::uppercase << value; CHECK_EQUAL(String(STR("1E240---------------")), ss.str()); ss.str().clear(); ss << etl::hex << etl::nouppercase << value; CHECK_EQUAL(String(STR("1e240---------------")), ss.str()); ss.str().clear(); ss << etl::setw(0); ss << etl::noboolalpha << false << STR(" ") << true << STR(" ") << etl::boolalpha << false << STR(" ") << true; CHECK_EQUAL(String(STR("0 1 false true")), ss.str()); ss.str().clear(); ss << etl::setprecision(4) << 3.1415927; CHECK_EQUAL(String(STR("3.1416")), ss.str()); ss.str().clear(); ss << STR("abcdef") << STR(" ") << etl::uppercase << STR("abcdef"); CHECK_EQUAL(String(STR("abcdef abcdef")), ss.str()); } //************************************************************************* TEST(test_custom_multi_inline_format) { String str; Stream ss(str); int value = 123; String hello(STR("Hello")); ss << etl::dec << etl::setw(10) << etl::setfill(STR('#')) << hello << etl::setw(8) << etl::setfill(STR('*')) << etl::left << STR("World") << etl::hex << etl::setw(4) << etl::setfill(STR(' ')) << etl::right << value; String result = ss.str(); CHECK_EQUAL(String(STR("#####HelloWorld*** 7b")), result); } //************************************************************************* TEST(test_custom_class_default_format) { String str; Stream ss(str); String value_str(STR("Value: ")); IString& ivalue_str = value_str; Custom value = { 1, 2 }; ss << ivalue_str << value; String result = ss.str(); CHECK_EQUAL(String(STR("Value: X = 1 : Y = 2")), result); } //************************************************************************* TEST(test_get_format) { String str; Format format = Format().base(16).width(4).fill(STR(' ')).right(); Stream ss(str, format); Format format2 = ss.get_format(); CHECK(format == format2); } //************************************************************************* TEST(test_set_from_character_pointer) { String str; Stream ss(str); ss.str(STR("Hello")); CHECK_EQUAL(String(STR("Hello")), ss.str()); } //************************************************************************* TEST(test_set_from_string) { String str; Stream ss(str); ss.str(String(STR("Hello"))); CHECK_EQUAL(String(STR("Hello")), ss.str()); } //************************************************************************* TEST(test_get_istring) { String str; Stream ss(str); ss.str(String(STR("Hello"))); IString& istr = ss.str(); istr.resize(istr.size() - 1); CHECK_EQUAL(String(STR("Hell")), istr); } //************************************************************************* TEST(test_get_const_istring) { String str; Stream ss(str); ss.str(String(STR("Hello"))); const IString& istr = ss.str(); CHECK_EQUAL(String(STR("Hello")), istr); } }; }
26.972603
117
0.492636
mhx
cb5a5ca587bd579fbe52257d6cb4da8eda15682c
4,552
cpp
C++
leetcode/docu/468.cpp
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
leetcode/docu/468.cpp
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
leetcode/docu/468.cpp
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
#include "cpp_header.h" class Solution { public: string validIPAddress(string IP) { int dot_nums = count(IP.begin(), IP.end(), '.'); if(dot_nums == 3) if(consider_v4(IP)) return "IPv4"; int colon_nums = count(IP.begin(), IP.end(), ':'); if(colon_nums == 7) if(consider_v6(IP)) return "IPv6"; return "Neither"; } bool consider_v6(string & s) { if(s.length() > 39) return false; string ns; for(auto x : s) { if(x >= 'A' && x <= 'F') ns += ('Z' - 'A' + 'a'); else if(x >= '0' && x <= '9') ns += x; else if(x == ':') ns += x; else if(x >= 'a' && x <= 'f') ns += x; } if(ns.length() != s.length()) return false; int i = 0, j = 0; int sep = 0; while(j < ns.length()) { while(j < ns.length() && ns[j] != ':') j++; if(i == j) return false; if(j - i > 4) return false; j++; i = j; sep++; } if(sep != 8) return false; return true; } bool consider_v4(string &s) { if(s[0] == '0') return false; if(s.length() > 15) return false; int i = 0, j = 0; int sep = 0; while(j < s.length()) { while(j < s.length() && s[j] != '.') j++; if(i == j) return false; if(j - i > 3) return false; if(check_v4_num(s, i, j) == false) return false; i++; j++; sep++; } if(sep != 4) return false; return true; } bool check_v4_num(string& s, int & i, int & j) { if(j - i == 3) { if(s[i] == '1' && s[i+1] >= '0' && s[i+1] <= '9' && s[i+2] >= '0' && s[i+2] <= '9') i = j; else if(s[i] == '2' && s[i+1] >= '0' && s[i+1] <= '4' && s[i+2] >= '0' && s[i+2] <= '9') i = j; else if(s[i] == '2' && s[i+1] == '5' && s[i+2] >= '0' && s[i+2] <= '5') i = j; } else if(j - i == 2) { if(s[i] >= '1' && s[i] <= '9' && s[i+1] >= '0' && s[i+1] <= '9') i = j; } else if(j - i == 1) { if(s[i] >= '0' && s[i] <= '9') i = j; } if(i != j) return false; return true; } }; int testcase(string IP, string res, int casenum) { Solution sol; if(sol.validIPAddress(IP) == res) { cout << casenum << " pass\n"; } else { cout << casenum << " no pass\n"; } } int main() { string IP; string res; int casenum; IP = "0.0.0.0"; res = "Neither"; casenum = 1; testcase(IP, res, casenum); IP = "1.0.0.0"; res = "IPv4"; casenum = 2; testcase(IP, res, casenum); IP = "1.01.0.0"; res = "Neither"; casenum = 3; testcase(IP, res, casenum); IP = "1.01.0.0."; res = "Neither"; casenum = 4; testcase(IP, res, casenum); IP = ".1.01.0"; res = "Neither"; casenum = 5; testcase(IP, res, casenum); IP = "256.256.256.256"; res = "Neither"; casenum = 6; testcase(IP, res, casenum); IP = "254.254.254.256"; res = "Neither"; casenum = 7; testcase(IP, res, casenum); IP = "254.254.256.254"; res = "Neither"; casenum = 8; testcase(IP, res, casenum); IP = "254.256.254.254"; res = "Neither"; casenum = 9; testcase(IP, res, casenum); IP = "256.254.254.254"; res = "Neither"; casenum = 10; testcase(IP, res, casenum); IP = "176.123.23.2"; res = "IPv4"; casenum = 11; testcase(IP, res, casenum); IP = "76.223.23.0"; res = "IPv4"; casenum = 12; testcase(IP, res, casenum); IP = "76:223:23:0:12ff:a123:123:a"; res = "IPv6"; casenum = 13; testcase(IP, res, casenum); IP = "00076:223:23:0:12ff:a123:123:a"; res = "Neither"; casenum = 14; testcase(IP, res, casenum); IP = "0076:00223:23:0:12ff:a123:123:a"; res = "Neither"; casenum = 15; testcase(IP, res, casenum); IP = "0076:0223:23::12ff:a123:123:a"; res = "Neither"; casenum = 16; testcase(IP, res, casenum); IP = "0076:0223:23:0000:12ff:a123:123:a"; res = "IPv6"; casenum = 17; testcase(IP, res, casenum); IP = "0076:0223:23:0000:12ff:a123:123:0000"; res = "IPv6"; casenum = 18; testcase(IP, res, casenum); IP = ":0076:0223:23:0000:12ff:a123:123"; res = "Neither"; casenum = 19; testcase(IP, res, casenum); IP = "0076:0223:23:0000:12ff:a123:123:FFFf"; res = "IPv6"; casenum = 20; testcase(IP, res, casenum); IP = "1.0.1."; res = "Neither"; casenum = 21; testcase(IP, res, casenum); IP = "0076:0223:23:0000:12ff:a123:123:"; res = "Neither"; casenum = 22; testcase(IP, res, casenum); IP = "0076:0223:23:0000:12ff:a123::"; res = "Neither"; casenum = 23; testcase(IP, res, casenum); IP = "0076:0G23:23:0000:12ff:a123:0:0"; res = "Neither"; casenum = 24; testcase(IP, res, casenum); IP = "219.219.219.219"; res = "IPv4"; casenum = 25; testcase(IP, res, casenum); }
16.199288
56
0.517355
sczzq
cb5e295f4d074243ce2d069626fcbbe325c1e3c2
52
cpp
C++
c++/CMakeProject1/query/boost_timer_demo.cpp
Minyi1750/test
08409df49fb576114c8b70677face827023d9cb5
[ "Apache-2.0" ]
1
2018-03-03T21:04:45.000Z
2018-03-03T21:04:45.000Z
c++/CMakeProject1/query/boost_timer_demo.cpp
Minyi1750/test
08409df49fb576114c8b70677face827023d9cb5
[ "Apache-2.0" ]
null
null
null
c++/CMakeProject1/query/boost_timer_demo.cpp
Minyi1750/test
08409df49fb576114c8b70677face827023d9cb5
[ "Apache-2.0" ]
null
null
null
#include<boost/timer.cpp> int main() { return 0; }
10.4
25
0.653846
Minyi1750
cb61fcd77c4c80c87c3085044ffefcc4e036db75
8,298
cpp
C++
libs/nav/src/reactive/CMultiObjectiveMotionOptimizerBase.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
libs/nav/src/reactive/CMultiObjectiveMotionOptimizerBase.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
null
null
null
libs/nav/src/reactive/CMultiObjectiveMotionOptimizerBase.cpp
yhexie/mrpt
0bece2883aa51ad3dc88cb8bb84df571034ed261
[ "OLDAP-2.3" ]
1
2021-08-16T11:50:47.000Z
2021-08-16T11:50:47.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "nav-precomp.h" // Precomp header #include <mrpt/nav/reactive/CMultiObjectiveMotionOptimizerBase.h> #include <mrpt/system/string_utils.h> using namespace mrpt::nav; using namespace mrpt::utils; IMPLEMENTS_VIRTUAL_MRPT_OBJECT(CMultiObjectiveMotionOptimizerBase, CObject, mrpt::nav) CMultiObjectiveMotionOptimizerBase::CMultiObjectiveMotionOptimizerBase(TParamsBase & params) : m_params_base(params) { } int CMultiObjectiveMotionOptimizerBase::decide(const std::vector<mrpt::nav::TCandidateMovementPTG>& movs, TResultInfo & extra_info) { auto & score_values = extra_info.score_values; score_values.resize(movs.size()); // For each movement: for (unsigned int mov_idx = 0; mov_idx< movs.size();++mov_idx) { const auto &m = movs[mov_idx]; // Mark all vars as NaN so we detect uninitialized values: for (auto &p : m_expr_vars) { p.second = std::numeric_limits<double>::quiet_NaN(); } for (const auto &prop : m.props) { double & var = m_expr_vars[prop.first]; var = prop.second; } // Upon first iteration: compile expressions if (m_score_exprs.size() != m_params_base.formula_score.size()) { m_score_exprs.clear(); for (const auto &f : m_params_base.formula_score) { auto &se = m_score_exprs[f.first]; se.compile(f.second, m_expr_vars, std::string("score: ") + f.first); } } // Upon first iteration: compile expressions if (m_movement_assert_exprs.size() != m_params_base.movement_assert.size()) { const size_t N = m_params_base.movement_assert.size(); m_movement_assert_exprs.clear(); m_movement_assert_exprs.resize(N); for (size_t i=0;i<N;i++) { const auto &str = m_params_base.movement_assert[i]; auto &ce = m_movement_assert_exprs[i]; ce.compile(str, m_expr_vars, "assert" ); } } // For each assert, evaluate it: bool assert_failed = false; { for (auto &ma : m_movement_assert_exprs) { const double val = ma.eval(); if (val == 0) { assert_failed = true; break; } } } // For each score: evaluate it for (auto &sc : m_score_exprs) { // Evaluate: double val; if (m.speed <= 0 || assert_failed) // Invalid candidate { val = .0; } else { val = sc.second.eval(); } if (val != val /* NaN */) { THROW_EXCEPTION_FMT("Undefined value evaluating score `%s` for mov_idx=%u!", sc.first.c_str(), mov_idx); } // Store: score_values[mov_idx][sc.first] = val; } } // Optional score post-processing: normalize highest value to 1.0 for (const auto& sScoreName : m_params_base.scores_to_normalize) { // Find max: double maxScore = .0; for (const auto &s : score_values) { const auto it = s.find(sScoreName); if (it != s.cend()) mrpt::utils::keep_max(maxScore, it->second); } // Normalize: if (maxScore > 0 && maxScore!=1.0 /* already normalized! */) { double K = 1.0 / maxScore; for (auto &s : score_values) { auto it = s.find(sScoreName); if (it != s.end()) { it->second *= K; } } } } // Run algorithm: return impl_decide(movs, extra_info); } void CMultiObjectiveMotionOptimizerBase::clear() { m_score_exprs.clear(); } CMultiObjectiveMotionOptimizerBase * CMultiObjectiveMotionOptimizerBase::Create(const std::string &className) MRPT_NO_THROWS { try { mrpt::utils::registerAllPendingClasses(); // Factory: const mrpt::utils::TRuntimeClassId *classId = mrpt::utils::findRegisteredClass(className); if (!classId) return nullptr; CMultiObjectiveMotionOptimizerBase *holo = dynamic_cast<CMultiObjectiveMotionOptimizerBase*>(classId->createObject()); return holo; } catch (...) { return nullptr; } } CMultiObjectiveMotionOptimizerBase::TParamsBase::TParamsBase() { // Default scores: formula_score["collision_free_distance"] = "collision_free_distance"; formula_score["path_index_near_target"] = "var dif:=abs(target_k-move_k); if (dif>(num_paths/2)) { dif:=num_paths-dif; }; exp(-abs(dif / (num_paths/10.0)));"; formula_score["euclidean_nearness"] = "(ref_dist - dist_eucl_final) / ref_dist"; formula_score["hysteresis"] = "hysteresis"; formula_score["clearance"] = "clearance"; // Default: scores_to_normalize.push_back("clearance"); } void CMultiObjectiveMotionOptimizerBase::TParamsBase::loadFromConfigFile(const mrpt::utils::CConfigFileBase &c, const std::string &s) { // Load: formula_score { formula_score.clear(); int idx = 1; for (;;idx++) { const std::string sKeyName = mrpt::format("score%i_name",idx), sKeyValue = mrpt::format("score%i_formula", idx); const std::string sName = c.read_string(s, sKeyName, ""); const std::string sValue = c.read_string(s, sKeyValue, ""); const bool none = (sName.empty() && sValue.empty()); const bool both = (!sName.empty() && !sValue.empty()); if (none && idx == 1) THROW_EXCEPTION_FMT("Expect at least a first `%s` and `%s` pair defining one score in section `[%s]`", sKeyName.c_str(), sKeyValue.c_str(), s.c_str()); if (none) break; if (!both) { THROW_EXCEPTION_FMT("Both `%s` and `%s` must be provided in section `[%s]`", sKeyName.c_str(), sKeyValue.c_str(), s.c_str()); } formula_score[sName] = sValue; } } // Load: movement_assert { movement_assert.clear(); int idx = 1; for (;; idx++) { const std::string sKey = mrpt::format("movement_assert%i", idx); const std::string sValue = c.read_string(s, sKey, ""); if (sValue.empty()) break; movement_assert.push_back(sValue); } } { scores_to_normalize.clear(); std::string sLst = c.read_string(s, "scores_to_normalize", ""); if (!sLst.empty()) { mrpt::system::tokenize(sLst, ", \t", scores_to_normalize); } } } void CMultiObjectiveMotionOptimizerBase::TParamsBase::saveToConfigFile(mrpt::utils::CConfigFileBase &c, const std::string &s) const { // Save: formula_score { const std::string sComment = "\n" "# Next follows a list of `score%i_{name,formula}` pairs for i=1,...,N\n" "# Each one defines one of the scores that will be evaluated for each candidate movement.\n" "# Multiobjective optimizers will then use those scores to select the best candidate, \n" "# possibly using more parameters that follow below.\n" ; c.write(s, "dummy", "", mrpt::utils::MRPT_SAVE_NAME_PADDING, mrpt::utils::MRPT_SAVE_VALUE_PADDING, sComment); int idx = 0; for (const auto &p : this->formula_score) { ++idx; const std::string sKeyName = mrpt::format("score%i_name", idx), sKeyValue = mrpt::format("score%i_formula", idx); c.write(s, sKeyName, p.first, mrpt::utils::MRPT_SAVE_NAME_PADDING, mrpt::utils::MRPT_SAVE_VALUE_PADDING); c.write(s, sKeyValue, p.second, mrpt::utils::MRPT_SAVE_NAME_PADDING, mrpt::utils::MRPT_SAVE_VALUE_PADDING); } } // Load: movement_assert { const std::string sComment = "\n" "# Next follows a list of `movement_assert%i` exprtk expressions for i=1,...,N\n" "# defining expressions for conditions that any candidate movement must fulfill\n" "# in order to get through the evaluation process. *All* assert conditions must be satisfied.\n" ; c.write(s, "dummy2", "", mrpt::utils::MRPT_SAVE_NAME_PADDING, mrpt::utils::MRPT_SAVE_VALUE_PADDING, sComment); for (unsigned int idx=0;idx<movement_assert.size();idx++) { const std::string sKey = mrpt::format("movement_assert%i", idx+1); c.write(s, sKey, movement_assert[idx], mrpt::utils::MRPT_SAVE_NAME_PADDING, mrpt::utils::MRPT_SAVE_VALUE_PADDING); } } { std::string sLst; for (const auto& s : scores_to_normalize) { sLst += s; sLst += std::string(","); } c.write(s, "scores_to_normalize", sLst); } }
29.956679
159
0.650398
yhexie
cb63e51ad8fbd81ebe284c3f7dd86cb81de18814
793
cpp
C++
Yogesh Gaur/implelement_in_cpp/algorithms/Sorting/bubble_sort.cpp
sanskriti2023/Hacktoberfest-KIIT-2020
fcb670b3bd7a8351af1b3bbbbef7a1f3e8d037c4
[ "MIT" ]
8
2019-10-05T18:40:46.000Z
2019-10-25T16:26:41.000Z
Yogesh Gaur/implelement_in_cpp/algorithms/Sorting/bubble_sort.cpp
sanskriti2023/Hacktoberfest-KIIT-2020
fcb670b3bd7a8351af1b3bbbbef7a1f3e8d037c4
[ "MIT" ]
13
2020-09-30T19:27:29.000Z
2021-09-08T02:31:48.000Z
Yogesh Gaur/implelement_in_cpp/algorithms/Sorting/bubble_sort.cpp
sanskriti2023/Hacktoberfest-KIIT-2020
fcb670b3bd7a8351af1b3bbbbef7a1f3e8d037c4
[ "MIT" ]
84
2020-09-30T19:00:05.000Z
2021-09-30T04:17:34.000Z
#include <iostream> using namespace std; void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { arr[j] = arr[j] + arr[j + 1]; arr[j + 1] = arr[j] - arr[j + 1]; arr[j] = arr[j] - arr[j + 1]; } } } for (i = 0; i < n; i++) { cout << arr[i] << " "; cout << endl; } } int main() { int *a, size; cout << "Enter the size of Array :\n"; cin >> size; a = new int[size]; cout << "Enter the Array : \n"; for (int i = 0; i < size; i++) { cin >> a[i]; } cout << "Sorted Array is : \n"; bubbleSort(a, size); return 0; }
19.825
49
0.364439
sanskriti2023
cb63ee8f1e1cefcede8e1b6533fbc6251167ca9e
3,775
cpp
C++
Demo.cpp
michal-z/SimplePbr
629a0addae04b03630e0aaed6890da8f044dedb1
[ "MIT" ]
1
2021-11-07T07:21:52.000Z
2021-11-07T07:21:52.000Z
Demo.cpp
michal-z/SimplePbr
629a0addae04b03630e0aaed6890da8f044dedb1
[ "MIT" ]
null
null
null
Demo.cpp
michal-z/SimplePbr
629a0addae04b03630e0aaed6890da8f044dedb1
[ "MIT" ]
null
null
null
#include "External.h" #include "Common.h" void *operator new[](size_t Size, const char* /*Name*/, int /*Flags*/, unsigned /*DebugFlags*/, const char* /*File*/, int /*Line*/) { return malloc(Size); } void *operator new[](size_t Size, size_t Alignment, size_t AlignmentOffset, const char* /*Name*/, int /*Flags*/, unsigned /*DebugFlags*/, const char* /*File*/, int /*Line*/) { return _aligned_offset_malloc(Size, Alignment, AlignmentOffset); } static void BeginFrame() { ID3D12CommandAllocator* CmdAlloc = Dx::GCmdAlloc[Dx::GFrameIndex]; Dx::TGraphicsCommandList* CmdList = Dx::GCmdList; CmdAlloc->Reset(); CmdList->Reset(CmdAlloc, nullptr); Dx::SetDescriptorHeap(); CmdList->RSSetViewports(1, &CD3DX12_VIEWPORT(0.0f, 0.0f, (float)Dx::GResolution[0], (float)Dx::GResolution[1])); CmdList->RSSetScissorRects(1, &CD3DX12_RECT(0, 0, Dx::GResolution[0], Dx::GResolution[1])); ID3D12Resource* BackBuffer; D3D12_CPU_DESCRIPTOR_HANDLE BackBufferHandle; Dx::GetBackBuffer(BackBuffer, BackBufferHandle); CmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(BackBuffer, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); Dx::GCmdList->OMSetRenderTargets(1, &BackBufferHandle, FALSE, &Dx::GDepthBufferHandle); Dx::GCmdList->ClearRenderTargetView(BackBufferHandle, XMVECTORF32{ 1.0f, 1.0f, 1.0f, 0.0f }, 0, nullptr); Dx::GCmdList->ClearDepthStencilView(Dx::GDepthBufferHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr); } static void EndFrame() { ID3D12Resource* BackBuffer; D3D12_CPU_DESCRIPTOR_HANDLE BackBufferHandle; Dx::GetBackBuffer(BackBuffer, BackBufferHandle); Dx::GCmdList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(BackBuffer, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)); VHR(Dx::GCmdList->Close()); Dx::GCmdQueue->ExecuteCommandLists(1, (ID3D12CommandList**)&Dx::GCmdList); } static void Update(double Time, float DeltaTime) { ImGui::ShowDemoWindow(); } static void Initialize() { } static void Shutdown() { } int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { const char* WindowName = "Demo1"; const unsigned WindowWidth = 1920; const unsigned WindowHeight = 1080; SetProcessDPIAware(); ImGui::CreateContext(); Dx::Initialize(Lib::InitializeWindow(WindowName, WindowWidth, WindowHeight)); Gui::Initialize(); Initialize(); // Upload resources to the GPU. VHR(Dx::GCmdList->Close()); Dx::GCmdQueue->ExecuteCommandLists(1, (ID3D12CommandList**)&Dx::GCmdList); Dx::WaitForGpu(); for (ID3D12Resource* Resource : Dx::GIntermediateResources) SAFE_RELEASE(Resource); Dx::GIntermediateResources.clear(); for (;;) { MSG Message = {}; if (PeekMessage(&Message, 0, 0, 0, PM_REMOVE)) { DispatchMessage(&Message); if (Message.message == WM_QUIT) break; } else { double Time; float DeltaTime; Lib::UpdateFrameStats(Dx::GWindow, WindowName, Time, DeltaTime); Gui::Update(DeltaTime); BeginFrame(); ImGui::NewFrame(); Update(Time, DeltaTime); ImGui::Render(); Gui::Render(); EndFrame(); Dx::PresentFrame(); } } Dx::WaitForGpu(); Shutdown(); Gui::Shutdown(); Dx::Shutdown(); return 0; } #include "Directx12.cpp" #include "Gui.cpp" #include "Library.cpp" // vim: set ts=4 sw=4 expandtab:
27.962963
122
0.630199
michal-z
cb648166f7bb6279b559ed8ea745ce07943624dd
12,572
cc
C++
src/relay/op/nn/convolution.cc
qqsun8819/tvm
53ac89ede7cddd1649b01b2ff10cc67a963757ce
[ "Apache-2.0" ]
null
null
null
src/relay/op/nn/convolution.cc
qqsun8819/tvm
53ac89ede7cddd1649b01b2ff10cc67a963757ce
[ "Apache-2.0" ]
null
null
null
src/relay/op/nn/convolution.cc
qqsun8819/tvm
53ac89ede7cddd1649b01b2ff10cc67a963757ce
[ "Apache-2.0" ]
null
null
null
/*! * Copyright (c) 2018 by Contributors * \file convolution.cc * \brief Convolution operators */ #include <tvm/relay/op.h> #include <tvm/relay/attrs/nn.h> #include <vector> #include "../layout.h" namespace tvm { namespace relay { TVM_REGISTER_NODE_TYPE(Conv2DAttrs); bool Conv2DRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 3); const auto* data = types[0].as<TensorTypeNode>(); const auto* weight = types[1].as<TensorTypeNode>(); if (data == nullptr) return false; static const Layout kNCHW("NCHW"); static const Layout kOIHW("OIHW"); const Conv2DAttrs* param = attrs.as<Conv2DAttrs>(); CHECK(param != nullptr); const Layout in_layout(param->data_layout); const Layout kernel_layout(param->weight_layout); CHECK(in_layout.Convertible(kNCHW)) << "Conv only support input layouts that are convertible from NCHW." << " But got " << in_layout; CHECK(kernel_layout.Convertible(kOIHW)) << "Conv only support kernel layouts that are convertible from OIHW." << " But got "<< kernel_layout; Layout out_layout(param->out_layout); if (!out_layout.defined()) out_layout = in_layout; CHECK(out_layout.Convertible(kNCHW)) << "Conv only support output layouts that are convertible from NCHW." << " But got " << out_layout; std::vector<IndexExpr> dshape_nchw = ConvertLayout( data->shape, in_layout, kNCHW); IndexExpr channels, dilated_ksize_y, dilated_ksize_x; // infer weight if the kernel_size and channels are defined if (param->kernel_size.defined() && param->channels.defined()) { CHECK_EQ(param->kernel_size.size(), 2); CHECK_EQ(param->dilation.size(), 2); std::vector<IndexExpr> wshape( {param->channels / param->groups, dshape_nchw[1] / param->groups, param->kernel_size[0], param->kernel_size[1]}); wshape = ConvertLayout(wshape, kOIHW, kernel_layout); wshape[kernel_layout.Indexof('O')] *= param->groups; channels = param->channels; dilated_ksize_y = 1 + (param->kernel_size[0] - 1) * param->dilation[0]; dilated_ksize_x = 1 + (param->kernel_size[1] - 1) * param->dilation[1]; // assign result to reporter reporter->Assign(types[1], TensorTypeNode::make(wshape, data->dtype)); } else { // use weight to infer the conv shape. if (weight == nullptr) return false; auto wshape = ConvertLayout(weight->shape, kernel_layout, kOIHW); if (param->kernel_size.defined()) { CHECK_EQ(param->kernel_size.size(), 2); // check the size CHECK(reporter->AssertEQ(param->kernel_size[0], wshape[2]) && reporter->AssertEQ(param->kernel_size[1], wshape[3])) << "Conv2D: shape of weight is inconsistent with kernel_size, " << " kernel_size=" << param->kernel_size << " wshape=" << Array<IndexExpr>(wshape); } if (param->channels.defined()) { CHECK(reporter->AssertEQ(param->channels, wshape[0])) << "Conv2D: shape of weight is inconsistent with channels, " << " channels=" << param->channels << " wshape=" << Array<IndexExpr>(wshape); } CHECK(reporter->AssertEQ(dshape_nchw[1] / param->groups, wshape[1])); channels = wshape[0]; dilated_ksize_y = 1 + (wshape[2] - 1) * param->dilation[0]; dilated_ksize_x = 1 + (wshape[3] - 1) * param->dilation[1]; } // dilation std::vector<IndexExpr> oshape({dshape_nchw[0], channels, 0, 0}); oshape[2] = (dshape_nchw[2] + param->padding[0] * 2 - dilated_ksize_y) / param->strides[0] + 1; oshape[3] = (dshape_nchw[3] + param->padding[1] * 2 - dilated_ksize_x) / param->strides[1] + 1; DataType out_dtype = param->out_dtype; if (out_dtype.bits() == 0) { out_dtype = data->dtype; } oshape = ConvertLayout(oshape, kNCHW, out_layout); // assign output type reporter->Assign(types[2], TensorTypeNode::make(oshape, out_dtype)); return true; } // Positional relay function to create conv2d operator // used by frontend FFI. Expr MakeConv2D(Expr data, Expr weight, Array<IndexExpr> strides, Array<IndexExpr> padding, Array<IndexExpr> dilation, int groups, IndexExpr channels, Array<IndexExpr> kernel_size, std::string data_layout, std::string weight_layout, std::string out_layout, DataType out_dtype) { auto attrs = make_node<Conv2DAttrs>(); attrs->strides = std::move(strides); attrs->padding = std::move(padding); attrs->dilation = std::move(dilation); attrs->groups = groups; attrs->channels = channels; attrs->kernel_size = kernel_size; attrs->data_layout = std::move(data_layout); attrs->weight_layout = std::move(weight_layout); attrs->out_layout = std::move(out_layout); attrs->out_dtype = std::move(out_dtype); static const Op& op = Op::Get("nn.conv2d"); return CallNode::make(op, {data, weight}, Attrs(attrs), {}); } TVM_REGISTER_API("relay.op.nn._make.conv2d") .set_body([](const TVMArgs& args, TVMRetValue* rv) { runtime::detail::unpack_call<Expr, 12>(MakeConv2D, args, rv); }); RELAY_REGISTER_OP("nn.conv2d") .describe(R"code(2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. - **data**: This depends on the `layout` parameter. Input is 4D array of shape (batch_size, in_channels, height, width) if `layout` is `NCHW`. - **weight**: (channels, in_channels, kernel_size[0], kernel_size[1]) - **out**: This depends on the `layout` parameter. Output is 4D array of shape (batch_size, channels, out_height, out_width) if `layout` is `NCHW`. )code" TVM_ADD_FILELINE) .set_attrs_type_key("relay.attrs.Conv2DAttrs") .set_num_inputs(2) .add_argument("data", "Tensor", "The input tensor.") .add_argument("weight", "Tensor", "The weight tensor.") .set_support_level(2) .add_type_rel("Conv2D", Conv2DRel); // Conv2DTranspose TVM_REGISTER_NODE_TYPE(Conv2DTransposeAttrs); bool Conv2DTransposeRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { CHECK_EQ(types.size(), 3); const auto* data = types[0].as<TensorTypeNode>(); const auto* weight = types[1].as<TensorTypeNode>(); if (data == nullptr) return false; static const Layout kNCHW("NCHW"); static const Layout kOIHW("OIHW"); const Conv2DTransposeAttrs* param = attrs.as<Conv2DTransposeAttrs>(); CHECK(param != nullptr); const Layout in_layout(param->data_layout); const Layout kernel_layout(param->weight_layout); CHECK(in_layout.Convertible(kNCHW)) << "Conv only support input layouts that are convertible from NCHW." << " But got " << in_layout; CHECK(kernel_layout.Convertible(kOIHW)) << "Conv only support kernel layouts that are convertible from OIHW." << " But got "<< kernel_layout; IndexExpr channels, dilated_ksize_y, dilated_ksize_x; auto dshape_nchw = ConvertLayout(data->shape, in_layout, kNCHW); // infer weight if the kernel_size and channels are defined if (param->kernel_size.defined() && param->channels.defined()) { CHECK_EQ(param->kernel_size.size(), 2); CHECK_EQ(param->dilation.size(), 2); std::vector<IndexExpr> wshape({dshape_nchw[1], param->channels / param->groups, param->kernel_size[0], param->kernel_size[1]}); wshape = ConvertLayout(wshape, kOIHW, kernel_layout); dilated_ksize_y = 1 + (param->kernel_size[0] - 1) * param->dilation[0]; dilated_ksize_x = 1 + (param->kernel_size[1] - 1) * param->dilation[1]; channels = param->channels; // assign result to reporter reporter->Assign(types[1], TensorTypeNode::make(wshape, data->dtype)); } else { // use weight to infer the conv shape. if (weight == nullptr) return false; auto wshape = ConvertLayout(weight->shape, kernel_layout, kOIHW); if (param->kernel_size.defined()) { CHECK_EQ(param->kernel_size.size(), 2); // check the size CHECK(reporter->AssertEQ(param->kernel_size[0], wshape[2]) && reporter->AssertEQ(param->kernel_size[1], wshape[3])) << "Conv2D: shape of weight is inconsistent with kernel_size, " << " kernel_size=" << param->kernel_size << " wshape=" << Array<IndexExpr>(wshape); } if (param->channels.defined()) { CHECK(reporter->AssertEQ(param->channels, wshape[1])) << "Conv2D: shape of weight is inconsistent with channels, " << " channels=" << param->channels << " wshape=" << Array<IndexExpr>(wshape); } CHECK(reporter->AssertEQ(dshape_nchw[1] / param->groups, wshape[0])); channels = wshape[1]; dilated_ksize_y = 1 + (wshape[2] - 1) * param->dilation[0]; dilated_ksize_x = 1 + (wshape[3] - 1) * param->dilation[1]; } // dilation std::vector<IndexExpr> oshape({dshape_nchw[0], channels, 0, 0}); oshape[2] = (param->strides[0] * (dshape_nchw[2] - 1) + dilated_ksize_y - 2 * param->padding[0] + param->output_padding[0]); oshape[3] = (param->strides[1] * (dshape_nchw[3] - 1) + dilated_ksize_x - 2 * param->padding[1] + param->output_padding[1]); DataType out_dtype = param->out_dtype; if (out_dtype.bits() == 0) { out_dtype = data->dtype; } oshape = ConvertLayout(oshape, kNCHW, in_layout); reporter->Assign(types[2], TensorTypeNode::make(oshape, out_dtype)); return true; } Expr MakeConv2DTranspose(Expr data, Expr weight, Array<IndexExpr> strides, Array<IndexExpr> padding, Array<IndexExpr> dilation, int groups, IndexExpr channels, Array<IndexExpr> kernel_size, std::string data_layout, std::string weight_layout, Array<IndexExpr> output_padding, DataType out_dtype) { auto attrs = make_node<Conv2DTransposeAttrs>(); attrs->channels = channels; attrs->kernel_size = kernel_size; attrs->strides = std::move(strides); attrs->padding = std::move(padding); attrs->output_padding = std::move(output_padding); attrs->dilation = std::move(dilation); attrs->groups = groups; attrs->data_layout = std::move(data_layout); attrs->weight_layout = std::move(weight_layout); attrs->out_dtype = std::move(out_dtype); static const Op& op = Op::Get("nn.conv2d_transpose"); return CallNode::make(op, {data, weight}, Attrs(attrs), {}); } TVM_REGISTER_API("relay.op.nn._make.conv2d_transpose") .set_body([](const TVMArgs& args, TVMRetValue* rv) { runtime::detail::unpack_call<Expr, 12>(MakeConv2DTranspose, args, rv); }); RELAY_REGISTER_OP("nn.conv2d_transpose") .describe(R"code(Transposed 2D convolution layer (sometimes called Deconvolution). The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution. - **data**: This depends on the `layout` parameter. Input is 4D array of shape (batch_size, in_channels, height, width) if `layout` is `NCHW`. - **weight**: (in_channels, channels, kernel_size[0], kernel_size[1]) - **bias**: (channels,) - **out**: This depends on the `layout` parameter. Output is 4D array of shape v (batch_size, channels, out_height, out_width) if `layout` is `NCHW`. out_height and out_width are calculated as:: out_height = (height-1)*strides[0]-2*padding[0]+kernel_size[0]+output_padding[0] out_width = (width-1)*strides[1]-2*padding[1]+kernel_size[1]+output_padding[1] )code" TVM_ADD_FILELINE) .set_attrs_type_key("relay.attrs.Conv2DTransposeAttrs") .set_num_inputs(2) .add_argument("data", "Tensor", "The input tensor.") .add_argument("weight", "Tensor", "The weight tensor.") .set_support_level(2) .add_type_rel("Conv2DTranspose", Conv2DTransposeRel); } // namespace relay } // namespace tvm
40.038217
97
0.650255
qqsun8819
cb65760ade206a9a00afdc8ac77f46abff891cf3
8,882
hpp
C++
include/Thoth/Attribute.hpp
DerekCresswell/Thoth
e2ce891a45dffdf7c767ab7ddca13076f51ae567
[ "MIT" ]
null
null
null
include/Thoth/Attribute.hpp
DerekCresswell/Thoth
e2ce891a45dffdf7c767ab7ddca13076f51ae567
[ "MIT" ]
null
null
null
include/Thoth/Attribute.hpp
DerekCresswell/Thoth
e2ce891a45dffdf7c767ab7ddca13076f51ae567
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <string> #include <sstream> #include <vector> /* * * @TODO * Figure out defining attributes at run time * Implement other common attributes * Expand adding / deleting values to include more convience * Add optional safety for overwriting * Clearing values * Dealing with empty values * Use conditional_t and is_fundemental_t to increase preformance of * passing DataType by ref or not * Ensure DataType can become string * Add checks for attributes specific to one type of element * Should commons be in "Thoth::Common" or "Thoth::Attributes" * */ namespace Thoth { // Forward Declaration for RenderElement class RenderElement; namespace Detail { /* * * AttributeBase : * Defines the base feature set that is an attribute that can be attached * to a RenderElement. * Rendering capablities are accessible through the RenderElement. * * All classes inheriting from this must have a defualt construtor. * */ class AttributeBase { // Public variables public: // The name of the attribute // I.E. "class", "id" const std::string name; // Protected functions protected: // Main constructor for attributes AttributeBase(const std::string& name); // Returns the attribute as it should be rendered // This should include name, quotation marks, etc. virtual std::string Format() = 0; // Friends public: friend RenderElement; }; } // namespace Detail /* * * StandAloneAttribute : * Base class for an attribute with no values. * By default this will render as 'name' (less quotes). * */ class StandAloneAttribute : public Detail::AttributeBase { // Public functions public: // Main constructor of StandAloneAttribute StandAloneAttribute(const std::string& name); // Protected functions protected: // Override of AttributeBase::Format virtual std::string Format() override; }; /* * * SingleValueAttribute : * Base class for attributes that have a single data value. * By default it renders as 'name="value"' (less outer quotes). * * The typename 'DataType' determines the type of the value. * This type must be able to convert to a string or have an overridden * 'Format' function. * */ template<typename DataType> class SingleValueAttribute : public Detail::AttributeBase { // Public functions public: // Main constructors for SingleValueAttribute SingleValueAttribute(const std::string& name); SingleValueAttribute(const std::string& name, const DataType& value); // Sets the value of this attribute virtual SingleValueAttribute& SetValue(const DataType& value); // Protected variables protected: // The value of this attribute DataType value; // Protected functions protected: // Override of AttributeBase::Format virtual std::string Format() override; }; /* * * MultiValueAttribute : * Base class for attributes with multiple values. * By default renders like 'name=""' (less outer quotes) but requires * 'FormatValue' to put each value into the list. * * The typename 'DataType' determines the type of the value. * */ template<typename DataType> class MultiValueAttribute : public Detail::AttributeBase { // Public functions public: // Main constructors for MultiValueAttribute MultiValueAttribute(const std::string& name); MultiValueAttribute(const std::string& name, const std::vector<DataType>& values); // Sets the values vector directly // Does not perserve previous values virtual MultiValueAttribute& SetValues(const std::vector<DataType>& values); // Adds a value to this attributes values // Optionally specify a position for it to be put in at (default is last) virtual MultiValueAttribute& AddValue(const DataType& value, int position = -1); // Removes a value from this attributes values by position or value virtual MultiValueAttribute& RemoveValue(int position); virtual MultiValueAttribute& RemoveValue(const DataType& value); // Protected variables protected: // Stores the values of this attribute std::vector<DataType> values; // Protected functions protected: // Overrides AttributeBase::Format virtual std::string Format() override; // Defines how an individual value is formatted // and returns it as a string virtual std::string FormatValue(const DataType& value) = 0; }; } // namespace Thoth /* --- Template Definitions --- */ namespace Thoth { /* -- SingleValueAttribute -- */ /* Public */ // Constructs an empty SingleValueAttribute template<typename DataType> SingleValueAttribute<DataType>::SingleValueAttribute(const std::string& name) : Detail::AttributeBase(name) {} // Constructs a SingleValueAttribute with a value template<typename DataType> SingleValueAttribute<DataType>::SingleValueAttribute(const std::string& name, const DataType& value) : Detail::AttributeBase(name), value(value) {} // Sets the value of this attribute template<typename DataType> SingleValueAttribute<DataType>& SingleValueAttribute<DataType>::SetValue( const DataType& value) { this->value = value; return *this; } /* Protected */ // Default formatting of SingleValueAttibute // 'name="value"' template<typename DataType> std::string SingleValueAttribute<DataType>::Format() { return name + "=\"" + value + "\""; } /* -- MultiValueAttribute -- */ /* Public */ // Constructs an empty MultiValueAttribute template<typename DataType> MultiValueAttribute<DataType>::MultiValueAttribute(const std::string& name) : Detail::AttributeBase(name) {} // Constructs MultiValueAttribute with a default value list template<typename DataType> MultiValueAttribute<DataType>::MultiValueAttribute(const std::string& name, const std::vector<DataType>& values) : Detail::AttributeBase(name), values(values) {} // Directly sets the value list of this attribute template<typename DataType> MultiValueAttribute<DataType>& MultiValueAttribute<DataType>::SetValues( const std::vector<DataType>& values) { this->values = values; return *this; } // Adds a value to this attributes list template<typename DataType> MultiValueAttribute<DataType>& MultiValueAttribute<DataType>::AddValue( const DataType& value, int position) { // If position is not set use 'push_back' if(position < 0) { values.push_back(value); } else { values.insert(values.begin() + position, value); } return *this; } // Removes a value from this attributes list by position template<typename DataType> MultiValueAttribute<DataType>& MultiValueAttribute<DataType>::RemoveValue( int position) { // Ensure the position is valid if(position >= 0 && position < values.size()) { values.erase(values.begin() + position); } return *this; } // Removes a value from this attribute by value // @TODO // allow removing multiple, + ensure working proper // Add checks for seeing if element was removed template<typename DataType> MultiValueAttribute<DataType>& MultiValueAttribute<DataType>::RemoveValue( const DataType& value) { // Try erasing value auto it = values.erase(std::remove(values.begin(), values.end(), value), values.end()); // Check if value was found return *this; } /* Protected */ // Renders this attribute and returns it as a string template<typename DataType> std::string MultiValueAttribute<DataType>::Format() { if(values.size() == 0) return ""; std::stringstream strm; strm << name << "=\""; // Last element must be isolated to prevent the last space being added auto lastIt = values.end(); lastIt--; // Loop through every value except the last for(auto it = values.begin(); it != lastIt; it++) { strm << FormatValue(*it) << " "; } strm << FormatValue(*lastIt) << "\""; return strm.str(); } } // namespace Thoth
26.99696
95
0.633641
DerekCresswell
cb6762f2e42a636b2598c8716be291e7a0eeb2d8
6,528
hpp
C++
libs/math/test/compile_test/test_compile_result.hpp
Talustus/boost_src
ffe074de008f6e8c46ae1f431399cf932164287f
[ "BSL-1.0" ]
null
null
null
libs/math/test/compile_test/test_compile_result.hpp
Talustus/boost_src
ffe074de008f6e8c46ae1f431399cf932164287f
[ "BSL-1.0" ]
null
null
null
libs/math/test/compile_test/test_compile_result.hpp
Talustus/boost_src
ffe074de008f6e8c46ae1f431399cf932164287f
[ "BSL-1.0" ]
null
null
null
// Copyright John Maddock 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Note this header must NOT include any other headers, for its // use to be meaningful (because we use it in tests designed to // detect missing includes). // static const float f = 0; static const double d = 0; static const long double l = 0; static const unsigned u = 0; static const int i = 0; //template <class T> //inline void check_result_imp(T, T){} inline void check_result_imp(float, float){} inline void check_result_imp(double, double){} inline void check_result_imp(long double, long double){} inline void check_result_imp(int, int){} inline void check_result_imp(long, long){} #ifdef BOOST_HAS_LONG_LONG inline void check_result_imp(boost::long_long_type, boost::long_long_type){} #endif inline void check_result_imp(bool, bool){} // // If the compiler warns about unused typedefs then enable this: // #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7))) # define BOOST_MATH_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused)) #else # define BOOST_MATH_ASSERT_UNUSED_ATTRIBUTE #endif template <class T, class U> struct local_is_same { enum{ value = false }; }; template <class T> struct local_is_same<T, T> { enum{ value = true }; }; template <class T1, class T2> inline void check_result_imp(T1, T2) { // This is a static assertion that should always fail to compile... #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedef" #endif typedef BOOST_MATH_ASSERT_UNUSED_ATTRIBUTE int static_assertion[local_is_same<T1, T2>::value ? 1 : 0]; #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8))) #pragma GCC diagnostic pop #endif } template <class T1, class T2> inline void check_result(T2) { T1 a = T1(); T2 b = T2(); return check_result_imp(a, b); } union max_align_type { char c; short s; int i; long l; double d; long double ld; #ifdef BOOST_HAS_LONG_LONG long long ll; #endif }; template <class Distribution> struct DistributionConcept { static void constraints() { typedef typename Distribution::value_type value_type; const Distribution& dist = DistributionConcept<Distribution>::get_object(); value_type x = 0; // The result values are ignored in all these checks. check_result<value_type>(cdf(dist, x)); check_result<value_type>(cdf(complement(dist, x))); check_result<value_type>(pdf(dist, x)); check_result<value_type>(quantile(dist, x)); check_result<value_type>(quantile(complement(dist, x))); check_result<value_type>(mean(dist)); check_result<value_type>(mode(dist)); check_result<value_type>(standard_deviation(dist)); check_result<value_type>(variance(dist)); check_result<value_type>(hazard(dist, x)); check_result<value_type>(chf(dist, x)); check_result<value_type>(coefficient_of_variation(dist)); check_result<value_type>(skewness(dist)); check_result<value_type>(kurtosis(dist)); check_result<value_type>(kurtosis_excess(dist)); check_result<value_type>(median(dist)); // // we can't actually test that at std::pair is returned from these // because that would mean including some std lib headers.... // range(dist); support(dist); check_result<value_type>(cdf(dist, f)); check_result<value_type>(cdf(complement(dist, f))); check_result<value_type>(pdf(dist, f)); check_result<value_type>(quantile(dist, f)); check_result<value_type>(quantile(complement(dist, f))); check_result<value_type>(hazard(dist, f)); check_result<value_type>(chf(dist, f)); check_result<value_type>(cdf(dist, d)); check_result<value_type>(cdf(complement(dist, d))); check_result<value_type>(pdf(dist, d)); check_result<value_type>(quantile(dist, d)); check_result<value_type>(quantile(complement(dist, d))); check_result<value_type>(hazard(dist, d)); check_result<value_type>(chf(dist, d)); check_result<value_type>(cdf(dist, l)); check_result<value_type>(cdf(complement(dist, l))); check_result<value_type>(pdf(dist, l)); check_result<value_type>(quantile(dist, l)); check_result<value_type>(quantile(complement(dist, l))); check_result<value_type>(hazard(dist, l)); check_result<value_type>(chf(dist, l)); check_result<value_type>(cdf(dist, i)); check_result<value_type>(cdf(complement(dist, i))); check_result<value_type>(pdf(dist, i)); check_result<value_type>(quantile(dist, i)); check_result<value_type>(quantile(complement(dist, i))); check_result<value_type>(hazard(dist, i)); check_result<value_type>(chf(dist, i)); unsigned long li = 1; check_result<value_type>(cdf(dist, li)); check_result<value_type>(cdf(complement(dist, li))); check_result<value_type>(pdf(dist, li)); check_result<value_type>(quantile(dist, li)); check_result<value_type>(quantile(complement(dist, li))); check_result<value_type>(hazard(dist, li)); check_result<value_type>(chf(dist, li)); } private: static void* storage() { static max_align_type storage[sizeof(Distribution)]; return storage; } static Distribution* get_object_p() { return static_cast<Distribution*>(storage()); } static Distribution& get_object() { // will never get called: return *get_object_p(); } }; // struct DistributionConcept #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #define TEST_DIST_FUNC(dist)\ DistributionConcept< boost::math::dist##_distribution<float> >::constraints();\ DistributionConcept< boost::math::dist##_distribution<double> >::constraints();\ DistributionConcept< boost::math::dist##_distribution<long double> >::constraints(); #else #define TEST_DIST_FUNC(dist)\ DistributionConcept< boost::math::dist##_distribution<float> >::constraints();\ DistributionConcept< boost::math::dist##_distribution<double> >::constraints(); #endif
35.478261
106
0.67739
Talustus
cb6b046099cff431135f96e7c489c4700de1c176
3,174
cpp
C++
Day1/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
4
2021-12-06T17:14:00.000Z
2021-12-10T06:29:35.000Z
Day1/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
null
null
null
Day1/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
null
null
null
#include "aoc21/helpers.h" /* --- Day 1: Sonar Sweep --- You're minding your own business on a ship at sea when the overboard alarm goes off! You rush to see if you can help. Apparently, one of the Elves tripped and accidentally sent the sleigh keys flying into the ocean! Before you know it, you're inside a submarine the Elves keep ready for situations like this. It's covered in Christmas lights (because of course it is), and it even has an experimental antenna that should be able to track the keys if you can boost its signal strength high enough; there's a little meter that indicates the antenna's signal strength by displaying 0-50 stars. Your instincts tell you that in order to save Christmas, you'll need to get all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! As the submarine drops below the surface of the ocean, it automatically performs a sonar sweep of the nearby sea floor. On a small screen, the sonar sweep report (your puzzle input) appears: each line is a measurement of the sea floor depth as the sweep looks further and further away from the submarine. For example, suppose you had the following report: 199 200 208 210 200 207 240 269 260 263 This report indicates that, scanning outward from the submarine, the sonar sweep found depths of 199, 200, 208, 210, and so on. The first order of business is to figure out how quickly the depth increases, just so you know what you're dealing with - you never know if the keys will get carried into deeper water by an ocean current or a fish or something. To do this, count the number of times a depth measurement increases from the previous measurement. (There is no measurement before the first measurement.) In the example above, the changes are as follows: 199 (N/A - no previous measurement) 200 (increased) 208 (increased) 210 (increased) 200 (decreased) 207 (increased) 240 (increased) 269 (increased) 260 (decreased) 263 (increased) In this example, there are 7 measurements that are larger than the previous measurement. How many measurements are larger than the previous measurement? */ int main(int argc, char** argv) { aoc::AutoTimer t; auto f = aoc::open_argv_1(argc, argv); int deeper_count = 0; int last_depth = INT_MAX; std::pair<int, int> edges; const size_t window_size = 3; size_t count = 0; int last_running_sum = INT_MAX; int deeper_running_sum_count = 0; int running_sum = 0; const auto calculate_depths = [&](int depth) { deeper_count += (depth > last_depth); last_depth = depth; running_sum += depth; if (count == 0) { edges.first = depth; } count++; if (count >= window_size) { deeper_running_sum_count += (running_sum > last_running_sum); last_running_sum = running_sum; running_sum -= edges.first; edges.first = edges.second; } edges.second = depth; }; aoc::parse_as_integers(f, calculate_depths); aoc::print_results(deeper_count, deeper_running_sum_count); return 0; }
35.266667
374
0.744802
baldwinmatt
cb6be6db8face42eec6aeb6687376a39e9bfc890
113
cpp
C++
Coocoo3DGraphics/RayTracingShaderTable.cpp
sselecirPyM/Coocoo3D
edefdc5a65c2784a3be2bdcb5cd575c149ecaaa9
[ "BSD-3-Clause" ]
50
2020-07-14T06:51:26.000Z
2022-03-27T12:51:15.000Z
Coocoo3DGraphics/RayTracingShaderTable.cpp
sselecirPyM/Coocoo3D
edefdc5a65c2784a3be2bdcb5cd575c149ecaaa9
[ "BSD-3-Clause" ]
1
2021-08-05T06:30:15.000Z
2021-11-23T04:41:08.000Z
Coocoo3DGraphics/RayTracingShaderTable.cpp
sselecirPyM/Coocoo3D
edefdc5a65c2784a3be2bdcb5cd575c149ecaaa9
[ "BSD-3-Clause" ]
8
2020-11-30T02:48:37.000Z
2022-03-14T13:23:07.000Z
#include "pch.h" #include "RayTracingShaderTable.h" #include "DirectXHelper.h" using namespace Coocoo3DGraphics;
22.6
34
0.80531
sselecirPyM
cb6c66c75ee21994c0f7cc1e3c511325fd25dfba
1,180
cpp
C++
reverse.cpp
nainwalsanju/codechef
6baaab3e6b76ec60054fe427274be31d6de60c12
[ "MIT" ]
1
2021-12-17T14:43:15.000Z
2021-12-17T14:43:15.000Z
reverse.cpp
nainwalsanju/codechef
6baaab3e6b76ec60054fe427274be31d6de60c12
[ "MIT" ]
null
null
null
reverse.cpp
nainwalsanju/codechef
6baaab3e6b76ec60054fe427274be31d6de60c12
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; string reverse_words(string s) { reverse(s.begin(), s.end()); string tmp; string res; for(int i=0;i<s.size();i++) { if (s[i]==' ') { reverse(tmp.begin(), tmp.end()); res+=tmp; res+=' '; tmp.clear(); } else { tmp+=s[i]; } } reverse(tmp.begin(), tmp.end()); res+=tmp; return res; } string new_string(string str) { string ans=""; int n=str.length(); for(int i=0;i<n;i++) { if(str[i] != '.' && str[i] != '\'' && str[i] != ',' && str[i] != ';' && str[i] != ':') { ans += str[i]; } } return ans; } int main() { int n; cin>>n; n=n+1; vector<string>text(n); for(int i=0;i<n;++i) { getline(cin,text[i]); } for(int i=n-1;i>=0;--i) { string str=text[i]; string ans=new_string(str); cout<<reverse_words(ans)<<endl; } }
18.4375
99
0.360169
nainwalsanju
cb7401366ea1a35e697ca49934aed1a26c6cfb95
3,949
cpp
C++
Master/cores/esp8266/core_esp8266_main.cpp
morlantechnologies/Arduino-Libraries
128313d34f746bee660c0234050bae1af99745df
[ "MIT" ]
null
null
null
Master/cores/esp8266/core_esp8266_main.cpp
morlantechnologies/Arduino-Libraries
128313d34f746bee660c0234050bae1af99745df
[ "MIT" ]
null
null
null
Master/cores/esp8266/core_esp8266_main.cpp
morlantechnologies/Arduino-Libraries
128313d34f746bee660c0234050bae1af99745df
[ "MIT" ]
null
null
null
/* main.cpp - platform initialization and context switching emulation Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ //This may be used to change user task stack size: //#define CONT_STACKSIZE 4096 #include <Arduino.h> #include "Schedule.h" extern "C" { #include "ets_sys.h" #include "os_type.h" #include "osapi.h" #include "mem.h" #include "user_interface.h" #include "cont.h" } #include <core_version.h> #include "gdb_hooks.h" #define LOOP_TASK_PRIORITY 1 #define LOOP_QUEUE_SIZE 1 #define OPTIMISTIC_YIELD_TIME_US 16000 struct rst_info resetInfo; extern "C" { extern const uint32_t __attribute__((section(".ver_number"))) core_version = ARDUINO_ESP8266_GIT_VER; const char* core_release = #ifdef ARDUINO_ESP8266_RELEASE ARDUINO_ESP8266_RELEASE; #else NULL; #endif } // extern "C" int atexit(void (*func)()) { (void) func; return 0; } extern "C" void ets_update_cpu_frequency(int freqmhz); void initVariant() __attribute__((weak)); void initVariant() { } extern void loop(); extern void setup(); void preloop_update_frequency() __attribute__((weak)); void preloop_update_frequency() { #if defined(F_CPU) && (F_CPU == 160000000L) REG_SET_BIT(0x3ff00014, BIT(0)); ets_update_cpu_frequency(160); #endif } extern void (*__init_array_start)(void); extern void (*__init_array_end)(void); cont_t g_cont __attribute__ ((aligned (16))); static os_event_t g_loop_queue[LOOP_QUEUE_SIZE]; static uint32_t g_micros_at_task_start; extern "C" void esp_yield() { if (cont_can_yield(&g_cont)) { cont_yield(&g_cont); } } extern "C" void esp_schedule() { ets_post(LOOP_TASK_PRIORITY, 0, 0); } extern "C" void __yield() { if (cont_can_yield(&g_cont)) { esp_schedule(); esp_yield(); } else { panic(); } } extern "C" void yield(void) __attribute__ ((weak, alias("__yield"))); extern "C" void optimistic_yield(uint32_t interval_us) { if (cont_can_yield(&g_cont) && (system_get_time() - g_micros_at_task_start) > interval_us) { yield(); } } static void loop_wrapper() { static bool setup_done = false; preloop_update_frequency(); if(!setup_done) { setup(); setup_done = true; } loop(); run_scheduled_functions(); esp_schedule(); } static void loop_task(os_event_t *events) { (void) events; g_micros_at_task_start = system_get_time(); cont_run(&g_cont, &loop_wrapper); if (cont_check(&g_cont) != 0) { panic(); } } static void do_global_ctors(void) { void (**p)(void) = &__init_array_end; while (p != &__init_array_start) (*--p)(); } void init_done() { system_set_os_print(1); gdb_init(); do_global_ctors(); esp_schedule(); } extern "C" void user_init(void) { struct rst_info *rtc_info_ptr = system_get_rst_info(); memcpy((void *) &resetInfo, (void *) rtc_info_ptr, sizeof(resetInfo)); uart_div_modify(0, UART_CLK_FREQ / (115200)); init(); initVariant(); cont_init(&g_cont); ets_task(loop_task, LOOP_TASK_PRIORITY, g_loop_queue, LOOP_QUEUE_SIZE); system_init_done_cb(&init_done); }
23.646707
101
0.697392
morlantechnologies
cb75886e88f17263a61db65197759a158a653fd0
3,583
cc
C++
src/net/TcpServer.cc
GGGGITFKBJG/wethands
169b2c4e8758657de10fa5850d1749014338a31d
[ "MIT" ]
3
2020-12-03T13:18:17.000Z
2021-11-12T12:15:36.000Z
src/net/TcpServer.cc
GGGGITFKBJG/wethands
169b2c4e8758657de10fa5850d1749014338a31d
[ "MIT" ]
null
null
null
src/net/TcpServer.cc
GGGGITFKBJG/wethands
169b2c4e8758657de10fa5850d1749014338a31d
[ "MIT" ]
null
null
null
// Copyright (c) 2020 GGGGITFKBJG // // Date: 2020-06-04 10:09:40 // Description: #include "src/net/TcpServer.h" #include <cassert> #include <utility> #include "src/logger/Logger.h" namespace wethands { namespace details { void DefaultConnectionCallback(const TcpConnectionPtr& conn) { LOG_TRACE << "DefaultConnectionCallback()."; } void DefaultMessageCallback(const TcpConnectionPtr& conn, Buffer* buffer, Timestamp when) { buffer->RetrieveAll(); LOG_TRACE << "DefaultMessageCallback()."; } } // namespace details } // namespace wethands using wethands::TcpServer; using std::placeholders::_1; using std::placeholders::_2; TcpServer::TcpServer(EventLoop* loop, const InetAddress& listenAddr, const std::string& name, bool resuePort) : loop_(loop), acceptor_(new Acceptor(loop, listenAddr, resuePort)), name_(name), ipPort_(listenAddr.ToString(true)), threadPool_(new EventLoopThreadPool(loop, name_)), started_(false), connCount_(0), threadInitCallback_(), connectionCallback_(details::DefaultConnectionCallback), writeCompleteCallback_(), messageCallback_(details::DefaultMessageCallback), connections_() { assert(loop_); acceptor_->SetNewConnectionCallback( std::bind(&TcpServer::NewConnection, this, _1, _2)); } TcpServer::~TcpServer() { assert(loop_->IsInLoopThread()); for (std::pair<std::string, TcpConnectionPtr> item : connections_) { TcpConnectionPtr conn = item.second; conn->OwerLoop()->RunInLoop( std::bind(&TcpConnection::ConnectionDestroyed, conn)); } } void TcpServer::Start(int numThreads) { assert(loop_->IsInLoopThread()); assert(numThreads >= 0); if (started_) return; threadPool_->Start(numThreads, threadInitCallback_); acceptor_->Listen(); } void TcpServer::NewConnection(SocketPtr connSocket, const InetAddress& peerAddr) { // Acceptor 的回调函数. assert(loop_->IsInLoopThread()); EventLoop* ioLoop = threadPool_->NextLoop(); // 取出一个 I/O 子线程. // 连接名: 对端地址#序号. std::string connName = peerAddr.ToString(true) + "#" + std::to_string(++connCount_); InetAddress localAddr(connSocket->LocalAddress()); TcpConnectionPtr conn(new TcpConnection(ioLoop, // 新连接由子线程管理. connName, std::move(connSocket), localAddr, peerAddr)); connections_[connName] = conn; // 将连接记录在列表中. // 三个由用户定义的回调. 事件直接在 I/O 线程中处理. conn->SetConnectionCallback(connectionCallback_); conn->SetMessageCallback(messageCallback_); conn->SetWriteCompleteCallback(writeCompleteCallback_); // 对端关闭事件, 交由主 loop 线程处理. // 如果连接关闭了, I/O 线程就通知 TcpServer(主loop线程)将其从列表中删除. conn->SetCloseCallback( std::bind(&TcpServer::RemoveConnection, this, _1)); // 通知 I/O 子线程有新连接, 让其做一些初始化工作. ioLoop->RunInLoop(std::bind(&TcpConnection::ConnectionEstablished, conn)); } void TcpServer::RemoveConnection(const TcpConnectionPtr& conn) { loop_->RunInLoop(std::bind(&TcpServer::RemoveConnectionInLoop, this, conn)); } void TcpServer::RemoveConnectionInLoop(const TcpConnectionPtr& conn) { assert(loop_->IsInLoopThread()); connections_.erase(conn->Name()); EventLoop* ioLoop = conn->OwerLoop(); // 主 loop 线程已经将 conn 从列表中移除, 通知 conn 做清理工作. ioLoop->RunInLoop(std::bind(&TcpConnection::ConnectionDestroyed, conn)); }
32.87156
78
0.657829
GGGGITFKBJG
cb78078a2e040a3fada0567c1872975d87bdddf7
143,715
cpp
C++
solarpilot/SolarField.cpp
sacorbet97/ssc
6887d1e011de4f9ead8b283276c8c49f0f1dba2e
[ "MIT" ]
3
2017-09-04T12:19:13.000Z
2017-09-12T15:44:38.000Z
solarpilot/SolarField.cpp
sacorbet97/ssc
6887d1e011de4f9ead8b283276c8c49f0f1dba2e
[ "MIT" ]
1
2018-03-26T06:50:20.000Z
2018-03-26T06:50:20.000Z
solarpilot/SolarField.cpp
sacorbet97/ssc
6887d1e011de4f9ead8b283276c8c49f0f1dba2e
[ "MIT" ]
2
2018-02-12T22:23:55.000Z
2018-08-23T07:32:54.000Z
/******************************************************************************************************* * Copyright 2017 Alliance for Sustainable Energy, LLC * * NOTICE: This software was developed at least in part by Alliance for Sustainable Energy, LLC * (“Alliance”) under Contract No. DE-AC36-08GO28308 with the U.S. Department of Energy and the U.S. * The Government retains for itself and others acting on its behalf a nonexclusive, paid-up, * irrevocable worldwide license in the software to reproduce, prepare derivative works, distribute * copies to the public, perform publicly and display publicly, and to permit others to do so. * * 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, the above government * rights notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, the above government * rights notice, this list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. The entire corresponding source code of any redistribution, with or without modification, by a * research entity, including but not limited to any contracting manager/operator of a United States * National Laboratory, any institution of higher learning, and any non-profit organization, must be * made publicly available under this license for as long as the redistribution is made available by * the research entity. * * 4. Redistribution of this software, without modification, must refer to the software by the same * designation. Redistribution of a modified version of this software (i) may not refer to the modified * version by the same designation, or by any confusingly similar designation, and (ii) must refer to * the underlying software originally provided by Alliance as “System Advisor Model” or “SAM”. Except * to comply with the foregoing, the terms “System Advisor Model”, “SAM”, or any confusingly similar * designation may not be used to refer to any modified version of this software or any modified * version of the underlying software originally provided by Alliance without the prior written consent * of Alliance. * * 5. The name of the copyright holder, contributors, the United States Government, the United States * Department of Energy, or any of their employees may not 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, * CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR * EMPLOYEES, 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 <assert.h> #include <algorithm> #include <math.h> #include "exceptions.hpp" #include "SolarField.h" #include "sort_method.h" #include "Heliostat.h" #include "Receiver.h" #include "Financial.h" #include "Ambient.h" #include "Land.h" #include "Flux.h" #include "heliodata.h" #include "OpticalMesh.h" using namespace std; //Sim params sim_params::sim_params() { dni = 0.; //W/m2 Tamb = 0.; //C Patm = 0.; //atm Vwind = 0.; //m/s TOUweight = 1.; //- Simweight = 1.; is_layout = false; } //-------Access functions //"GETS" SolarField::clouds *SolarField::getCloudObject(){return &_clouds;} vector<Receiver*> *SolarField::getReceivers(){return &_active_receivers;} Land *SolarField::getLandObject(){return &_land;} //Ambient *SolarField::getAmbientObject(){return &_ambient;} Flux *SolarField::getFluxObject(){return _flux;} Financial *SolarField::getFinancialObject(){return &_financial;} FluxSimData *SolarField::getFluxSimObject(){return &_fluxsim;} htemp_map *SolarField::getHeliostatTemplates(){return &_helio_templates;} Hvector *SolarField::getHeliostats(){return &_heliostats;} layout_shell *SolarField::getLayoutShellObject(){return &_layout;} unordered_map<int,Heliostat*> *SolarField::getHeliostatsByID(){return &_helio_by_id;} vector<Heliostat> *SolarField::getHeliostatObjects(){return &_helio_objects;} var_map *SolarField::getVarMap(){return _var_map;} bool SolarField::getAimpointStatus(){return _is_aimpoints_updated;} double SolarField::getSimulatedPowerToReceiver(){return _sim_p_to_rec;} double *SolarField::getHeliostatExtents(){return _helio_extents;} simulation_info *SolarField::getSimInfoObject(){return &_sim_info;} simulation_error *SolarField::getSimErrorObject(){return &_sim_error;} optical_hash_tree *SolarField::getOpticalHashTree(){return &_optical_mesh;} //-------"SETS" /*min/max field radius.. function sets the value in units of [m]. Can be used as follows: 1) SetMinFieldRadius(_tht, 0.75); 2) SetMinFieldRadius(100, 1.0); */ void SolarField::setAimpointStatus(bool state){_is_aimpoints_updated = state;} void SolarField::setSimulatedPowerToReceiver(double val){_sim_p_to_rec = val;} void SolarField::setHeliostatExtents(double xmax, double xmin, double ymax, double ymin){ _helio_extents[0] = xmax; _helio_extents[1] = xmin; _helio_extents[2] = ymax; _helio_extents[3] = ymin; }; //Scripts bool SolarField::ErrCheck(){return _sim_error.checkForErrors();} void SolarField::CancelSimulation(){ _cancel_flag = true; _sim_error.addSimulationError("Simulation cancelled by user",true,false); } bool SolarField::CheckCancelStatus(){ bool stat = _cancel_flag; //_cancel_flag = false; return stat;} //any time this is called, reset the flag since the cancellation will be handled immediately //Constructor / destructor SolarField::SolarField(){ //_flux = new Flux(); _flux = 0; _var_map = 0; _is_created = false; //The Create() method hasn't been called yet. _estimated_annual_power = 0.; }; SolarField::~SolarField(){ if(_flux != (Flux*)NULL) delete _flux; //If the flux object is allocated memory, delete //Delete receivers for(unsigned int i=0; i<_receivers.size(); i++){ delete _receivers.at(i); } } //Copy constructor SolarField::SolarField( const SolarField &sf ) : _q_to_rec( sf._q_to_rec ), //[MW] Power to the receiver during performance runs _sim_p_to_rec( sf._sim_p_to_rec ), _estimated_annual_power( sf._estimated_annual_power ), _q_des_withloss( sf._q_des_withloss ), _is_aimpoints_updated( sf._is_aimpoints_updated ), _cancel_flag( sf._cancel_flag ), _is_created( sf._is_created ), _layout( sf._layout ), _helio_objects( sf._helio_objects ), //This contains the heliostat objects. The heliostat constructor will handle all internal pointer copy operations _helio_template_objects( sf._helio_template_objects ), //This contains the heliostat template objects. _land( sf._land ), _financial( sf._financial ), _fluxsim( sf._fluxsim ), _sim_info( sf._sim_info ), _sim_error( sf._sim_error ), _var_map( sf._var_map ) //point to original variable map { //------- Reconstruct pointer maps, etc ---------- for(int i=0; i<4; i++){ _helio_extents[i] = sf._helio_extents[i]; } //Create a map between the original heliostat object addresses and the new address unordered_map<Heliostat*, Heliostat*> hp_map; for(unsigned int i=0; i<_helio_objects.size(); i++){ hp_map[ const_cast<Heliostat*>( &sf._helio_objects.at(i) ) ] = &_helio_objects.at(i); } //Create a temporary pointer map between the old and new heliostat template objects unordered_map<Heliostat*,Heliostat*> htemp_ptr_map; for(int i=0; i<(int)_helio_template_objects.size(); i++){ htemp_ptr_map[ const_cast<Heliostat*>( &(sf._helio_template_objects.at(i)) ) ] = &(_helio_template_objects.at(i)); } //Reassign the integer->Heliostat* map _helio_templates.clear(); for(unsigned int i=0; i<_helio_template_objects.size(); i++){ _helio_templates[i] = &_helio_template_objects.at(i); } //Set up the heliostat pointer array /* The ID's are originally set according to the position in the heliostat object matrix. Use this feature to reconstruct the pointer map. */ int npos = (int)sf._heliostats.size(); _heliostats.resize(npos); for(int i=0; i<npos; i++){ _heliostats.at(i) = hp_map[ sf._heliostats.at(i) ]; _heliostats.at(i)->setMasterTemplate( htemp_ptr_map[ _heliostats.at(i)->getMasterTemplate()] ); } _helio_by_id.clear(); for(unsigned int i=0; i<sf._helio_by_id.size(); i++){ //Do a separate loop for ID's since they are not necessarily assigned right away int id = sf._heliostats.at(i)->getId(); _helio_by_id[ id ] = hp_map[ const_cast<Heliostat*>( const_cast<SolarField*>(&sf)->_helio_by_id[id] ) ]; } //Heliostat groups int nr, nc; nr = (int)sf._helio_groups.nrows(); nc = (int)sf._helio_groups.ncols(); _helio_groups.resize_fill(nr, nc, Hvector()); //NULL)); for(int i=0; i<nr; i++){ for(int j=0; j<nc; j++){ int nh = (int)sf._helio_groups.at(i,j).size(); _helio_groups.at(i,j).resize(nh); for(int k=0; k<nh; k++){ _helio_groups.at(i,j).at(k) = hp_map[ sf._helio_groups.at(i,j).at(k) ]; } } } //Layout groups _layout_groups.resize(sf._layout_groups.size()); for(int j=0; j<(int)sf._layout_groups.size(); j++){ int nh = (int)sf._layout_groups.at(j).size(); _layout_groups.at(j).resize(nh); for(int k=0; k<nh; k++){ _layout_groups.at(j).at(k) = hp_map[ sf._layout_groups.at(j).at(k) ]; } } //Neighbors nr = (int)sf._neighbors.nrows(); nc = (int)sf._neighbors.ncols(); _neighbors.resize_fill(nr, nc, Hvector()); //0, NULL)); for(int i=0; i<nr; i++){ for(int j=0; j<nc; j++){ int nh = (int)sf._neighbors.at(i,j).size(); _neighbors.at(i,j).resize(nh); for(int k=0; k<nh; k++){ _neighbors.at(i,j).at(k) = hp_map[ sf._neighbors.at(i,j).at(k)]; } } } for(int i=0; i<npos; i++){ //Each heliostat needs to have the neighbor group assigned to it Heliostat *hptr = _heliostats.at(i); hptr->setNeighborList( &_neighbors.at( hptr->getGroupId()[0], hptr->getGroupId()[1] ) ); } //Create receivers unordered_map<Receiver*, Receiver*> r_map; //map old receiver -> new receiver int nrec = (int)sf._receivers.size(); _active_receivers.clear(); for(int i=0; i<nrec; i++){ Receiver *rec = new Receiver( *sf._receivers.at(i) ); _receivers.push_back( rec ); r_map[ sf._receivers.at(i) ] = rec; //map //When copying the receiver class, update the flux surfaces to point to the correct receiver FluxSurfaces *fs = rec->getFluxSurfaces(); for(unsigned int j=0; j<fs->size(); j++){ fs->at(j).setParent( rec ); } //Recreate the active receivers list if(rec->getVarMap()->is_enabled.val) _active_receivers.push_back( rec ); } //Assign the correct receiver to each heliostat for(int i=0; i<npos; i++){ _heliostats.at(i)->setWhichReceiver( r_map[ _heliostats.at(i)->getWhichReceiver() ] ); } //Flux //if(_flux != (Flux*)NULL ) delete _flux; _flux = new Flux( *sf._flux ); } //Scripts void SolarField::Create(var_map &V){ /* Create a solar field instance, set the variable values according to the map provided by the GUI. This simply instantiates all the needed objects for the solar field but does not do any analysis. */ _sim_info.addSimulationNotice("Creating solar field geometry"); _var_map = &V; //point to te variables used to create this variable //_layout_data = V.sf.layout_data.val; //copy string layout data //Clean out possible existing variables Clean(); //Go through and set all of the relevant variables, constructing objects as needed along the way. //Ambient //_ambient.Create(V); //Create the flux object if(_flux != 0 ){ delete _flux; } //If the flux object already exists, delete and start over _flux = new Flux(); _flux->Setup(); setAimpointStatus(false); //the aimpoints have not yet been calculated //Heliostat variables, Instantiate the template objects in order int nh = (int)V.hels.size(); _helio_template_objects.resize(nh); V.sf.temp_which.combo_clear(); for(int j=0; j<nh; j++) { _helio_template_objects.at(j).Create( V, j ); _helio_templates[ j ] = &_helio_template_objects.at(j); std::string js = my_to_string(j); V.sf.temp_which.combo_add_choice( V.hels.at(j).helio_name.val, js ); } //Land _land.Create(V); //Parse the layout string into a layout object if(! V.sf.layout_data.val.empty() ) { //V.sf.layout_method.combo_select_by_mapval( var_solarfield::LAYOUT_METHOD::USERDEFINED ); //Convert the string contents to a layout_shell object SolarField::parseHeliostatXYZFile( V.sf.layout_data.val, _layout ); vector<sp_point> lpt; for(int i=0; i<(int)_layout.size(); i++) lpt.push_back( _layout.at(i).location ); _land.calcLandArea(V.land, lpt); //update the land bound area value //update the solar field area calculation _sf_area = calcHeliostatArea(); } //Receiver variables int Nset = (int)V.recs.size(); _active_receivers.clear(); for(int i=0; i<Nset; i++) { Receiver *rec = new Receiver(); _receivers.push_back( rec ); _receivers.at(i)->Create( V.recs.at(i), V.sf.tht.val ); if( V.recs.at(i).is_enabled.val ) _active_receivers.push_back(rec); } //Clouds double ext[2]; _land.getExtents(V, ext); _clouds.Create(V, ext); //Fluxsim _fluxsim.Create(V); //local solar field parameters updateCalculatedParameters(V); //Cost - financial _financial.Create(V); _is_created = true; } void SolarField::updateCalculatedParameters( var_map &V ) { /* Update any local values that are reported in the var_map This method is not threadsafe unless var_map is threadsafe! */ //sun position at design double azzen[2]; CalcDesignPtSunPosition(V.sf.sun_loc_des.mapval(), azzen[0], azzen[1]); V.sf.sun_az_des.Setval( azzen[0] ); V.sf.sun_el_des.Setval( 90.-azzen[1] ); //receiver area double arec = 0.; for(int i=0; i<(int)V.recs.size(); i++) arec += V.recs.at(0).absorber_area.Val(); V.sf.rec_area.Setval( arec ); //heliostat area V.sf.sf_area.Setval( _sf_area ); //average attenuation if(_heliostats.size() > 0 ) { double atten_ave = 0.; //calculate for each heliostat for(int i=0; i<(int)_heliostats.size(); i++) { double slant = _heliostats.at(i)->getSlantRange(); atten_ave += Ambient::calcAttenuation(V, slant); } V.amb.atm_atten_est.Setval( 100.*(1. - atten_ave / (double)_heliostats.size() ) ); } else { //calculate for land area //make sure land calculations have been updated already double radave = (V.land.radmin_m.Val() + V.land.radmax_m.Val())/2.; V.amb.atm_atten_est.Setval( 100.*(1. - Ambient::calcAttenuation(V, radave) ) ); } } void SolarField::updateAllCalculatedParameters(var_map &V) { /* Update all of the calculated values in all of the child classes and in solarfield */ for( int i=0; i<(int)_helio_template_objects.size(); i++) _helio_template_objects.at(i).updateCalculatedParameters(V, i); _land.updateCalculatedParameters(V); for( int i=0; i<(int)_receivers.size(); i++) _receivers.at(i)->updateCalculatedParameters(V.recs.at(i), V.sf.tht.val ); _fluxsim.updateCalculatedParameters(V); updateCalculatedParameters(V); _financial.updateCalculatedParameters(V); //optimization settings V.opt.aspect_display.Setval( V.recs[0].rec_aspect.Val() ); V.opt.gs_refine_ratio.Setval( pow(1./1.61803398875, V.opt.max_gs_iter.val ) ); } void SolarField::Clean(){ /* Clean out existing solar field and subcomponent arrays for a new start. These are the variables that aren't set in the "Create()" methods. */ for(int i=0; i<4; i++) _helio_extents[i] = 0.; _layout.clear(); _helio_objects.clear(); _helio_templates.clear(); _helio_template_objects.clear(); _heliostats.clear(); _helio_groups.clear(); _helio_by_id.clear(); _neighbors.clear(); _receivers.clear(); _is_created = false; _cancel_flag = false; //initialize the flag for cancelling the simulation _optical_mesh.reset(); _sf_area = 0.; } double SolarField::calcHeliostatArea(){ /* Sum up the total aperture area of all active heliostats in the solar field */ int Npos = (int)_heliostats.size(); double Asf=0.; for(int i=0; i<Npos; i++){ if(_heliostats.at(i)->IsInLayout()) Asf += _heliostats.at(i)->getArea(); } _sf_area = Asf; return Asf; } double SolarField::calcReceiverTotalArea(){ /* Sum and return the total absorber surface area for all receivers */ int nrec = (int)getReceivers()->size(); double Atot = 0.; for(int i=0; i<nrec; i++){ Receiver* Rec = getReceivers()->at(i); if(! Rec->isReceiverEnabled() ) continue; Atot += Rec->getAbsorberArea(); } return Atot; } double SolarField::calcAverageAttenuation() { if(_heliostats.size() > 0) { double att_ave=0; for(int i=0; i<(int)_heliostats.size(); i++) { att_ave += _heliostats.at(i)->getEfficiencyAtten(); } return att_ave / (double)_heliostats.size(); } else { double r_ave = _var_map->land.radmin_m.Val() + _var_map->land.radmax_m.Val(); r_ave *= 0.5; return Ambient::calcAttenuation(*_var_map, r_ave); } } bool SolarField::UpdateNeighborList(double lims[4], double zen){ /* Update the neighbors associated with each heliostat based on the shadow extent. Determine this range based on the current sun position lims: 0 : xmin 1 : xmax 2 : ymin 3 : ymax */ double xmax = lims[0], xmin = lims[1], ymax = lims[2], ymin = lims[3]; //add a little buffer to the min/max extents if(xmax>0.) {xmax *= 1.01;} else {xmax *= 0.99;} if(xmin<0.) {xmin *= 1.01;} else {xmin *= 0.99;} if(ymax>0.) {ymax *= 1.01;} else {ymax *= 0.99;} if(ymin<0.) {ymin *= 1.01;} else {ymin *= 0.99;} //How many nodes should be in the mesh? Determine the shadow length at some low sun position (say 15deg) //and use this to size the nodes. Shadowing will be evaluated among heliostats in the current node //and surrounding 8 nodes. double rcol = 0.; double hm = 0.; for(htemp_map::iterator it = _helio_templates.begin(); it != _helio_templates.end(); it++){ var_heliostat* Hv = it->second->getVarMap(); rcol += it->second->getCollisionRadius(); hm += Hv->height.val/2.; } rcol *= 1./(double)_helio_templates.size(); hm *= 1./(double)_helio_templates.size(); // This is the shadowing radius at 15deg. Use this as the x and y dimension of the mesh. // Multiply the cell width by 0.5 since several adjacent cells will participate in the shadowing. We don't // need each cell to be the full shadowing radius wide. double r_shad_max = fmax(2.*rcol/tan(PI/2.-zen), 3.*rcol); double r_block_max = 10.*hm; //by similar triangles and assuming the maximum heliostat-to-tower distance is 10 tower heights, calculate max. blocking interaction radius double r_interact = max(r_shad_max, r_block_max); r_interact = fmin(r_interact, 2.*hm*100); //limit to a reasonable value int ncol, nrow; double dcol, drow; ncol = max(1, int((xmax - xmin)/r_interact)); //The number of column nodes nrow = max(1, int((ymax - ymin)/r_interact)); //The number of row nodes dcol = (xmax - xmin)/float(ncol); drow = (ymax - ymin)/float(nrow); //The column and row node width //resize the mesh array accordingly _helio_groups.resize_fill(nrow, ncol, Hvector()); int col, row; //indicates which node the heliostat is in int Npos = (int)_helio_objects.size(); for(int i=0; i<Npos; i++){ Heliostat *hptr = &_helio_objects.at(i); //Find which node to add this heliostat to row = (int)(floor((hptr->getLocation()->y - ymin)/drow)); row = (int)fmax(0., fmin(row, nrow-1)); col = (int)(floor((hptr->getLocation()->x - xmin)/dcol)); col = (int)fmax(0., fmin(col, ncol-1)); //Add the heliostat ID to the mesh node _helio_groups.at(row,col).push_back(hptr); //Add the mesh node ID to the heliostat information hptr->setGroupId(row,col); } //Go over each node and compile a list of neighbors from the block of 9 adjacent cells. if(CheckCancelStatus()) return false; //check for cancelled simulation int nh; _neighbors.resize_fill(nrow, ncol, Hvector()); for(int i=0; i<nrow; i++){ //Loop over each row for(int j=0; j<ncol; j++){ //Loop over each column for(int k=i-1;k<i+2;k++){ //At each node position, get the surrounding nodes in the +/-y direction if(k<0 || k>nrow-1) continue; //If the search goes out of bounds in the y direction, loop to the next position for(int l=j-1;l<j+2;l++){ //At each node position, get the surrounding nodes in the +/-x direction if(l<0 || l>ncol-1) continue; //If the search goes out of bounds in the x direction, loop to the next position nh = (int)_helio_groups.at(k,l).size(); //How many heliostats are in this cell? for(int m=0; m<nh; m++){ //Add each heliostat element in the mesh to the list of neighbors for the current cell at (i,j) _neighbors.at(i,j).push_back( _helio_groups.at(k,l).at(m) ); } } } } } if(CheckCancelStatus()) return false; //check for cancelled simulation //For each heliostat, assign the list of neighbors that are stored in the _neighbors grid for(int i=0;i<Npos;i++){ Heliostat *hptr = &_helio_objects.at(i); hptr->setNeighborList( &_neighbors.at( hptr->getGroupId()[0], hptr->getGroupId()[1] ) ); //Set the neighbor list according to the stored _neighbors indices } return true; } bool SolarField::UpdateLayoutGroups(double lims[4]){ /* Create an "optical mesh" of the field based on changes in the local view factor and intercept factor (approximate) throughout the field. Certain areas in the heliostat field will experience more rapid rates of change of optical performance, and we can choose the grouping of heliostats carefully to minimize the number of required zone calculations while making sure that we don't group together heliostats that are ac- tually different in performance. The method here uses the derivative of intercept factor and of view factor to dete- rmine the allowable grid size. Each region is evaluated and divided 'n' times until the change in the efficiency over the azimuthal and radial spans of the zone falls below the allowed tolerance. Zones are assigned a unique binary code that represents their position in the field. The code is determined by dividing each variable space in half, and 0 corresponds to the lower region while 1 is the upper. Divisions are made alternatingly between radial (first) and azimuthal dimensions. Once the division has reached satisfactory resolution in one dimension, subsequent potential divisions are denoted with 'x', as no division actually takes place. The remaining dimension continues division until the required tolerance is met. At the end of the division chain, the flat 't' indi- cates that the node is terminal and contains data. For example: 10001x1xt represents: [r1] outer [a1] ccw [r2] inner [a2] ccw [r3] outer [a3] no division [r4] outer [a4] no division terminal In words, (1) divide a circle into outer and inner radial sections - take the outer, (2) divide region 1 into two slices (halves) - take the counterclockwise one, (3) divide region 2 into outer and inner radial sections - take the inner, .... the terminal node contains an array of data (heliostat pointers). Likewise, each heliostat can be assigned a unique binary tag using this method. Simply take the location of the heliostat and place it within the domain by subse- quent division. Continue until both 'r' and 'az' dimensions have sufficient resol- ution. The heliostat key will be entirely comprised of 0's and 1's. A heliostat can be placed in a zone by comparing the zone and heliostat location keys bitwise until the termination flag is reached. Where the zone key has an 'x', the zone does not split, and so the heliostat will continue down the mesh tree on the only available path. Once the 't' flag is reached, the heliostat is dropped into the data container. This method has been implemented as a means for quickly sorting a large number of heliostats that are known in x-y coordinates into a grid with variable mesh spacing that is defined in cylindrical coordinates. This method can probably be applied to sorting in other coordinate systems, but it's application here is specific to this problem. */ double xmax = lims[0], xmin = lims[1], ymax = lims[2], ymin = lims[3]; //add a little buffer to the min/max extents xmax = xmax > 0. ? xmax * 1.01 : xmax * 0.99; xmin = xmin > 0. ? xmin * 1.01 : xmin * 0.99; ymax = ymax > 0. ? ymax * 1.01 : ymax * 0.99; ymin = ymin > 0. ? ymin * 1.01 : ymin * 0.99; var_solarfield *Sv = &_var_map->sf; var_receiver *Rv = &_var_map->recs.front(); //create objects needed LayoutData mesh_data; mesh_data.extents_az[0] = Sv->accept_min.val; mesh_data.extents_az[1] = Sv->accept_max.val; mesh_data.tht = Sv->tht.val; mesh_data.alpha = Rv->rec_azimuth.val*D2R; mesh_data.theta = Rv->rec_elevation.val*D2R; //double width; Receiver *rec = _receivers.front(); mesh_data.w_rec = Rv->rec_width.val; //sqrt(powf(_receivers.front()->getReceiverWidth(),2) + powf(_receivers.front()->getReceiverHeight(),2)); mesh_data.flat = rec->getGeometryType() != Receiver::REC_GEOM_TYPE::CYLINDRICAL_CLOSED && rec->getGeometryType() != Receiver::REC_GEOM_TYPE::CYLINDRICAL_OPEN; mesh_data.f_tol = Sv->zone_div_tol.val; mesh_data.max_zsize_a = Sv->max_zone_size_az.val*Sv->tht.val; mesh_data.max_zsize_r = Sv->max_zone_size_rad.val*Sv->tht.val; mesh_data.min_zsize_a = Sv->min_zone_size_az.val*Sv->tht.val; mesh_data.min_zsize_r = Sv->min_zone_size_rad.val*Sv->tht.val; //mesh separately for each heliostat template int ntemp = (int)_helio_templates.size(); vector<vector<opt_element> > all_nodes(ntemp); _layout_groups.clear(); for(htemp_map::iterator it=_helio_templates.begin(); it!=_helio_templates.end(); it++){ var_heliostat* Hv = it->second->getVarMap(); double trange[2], arange[2]; TemplateRange(it->first, Sv->template_rule.mapval(), trange, arange); mesh_data.extents_r[0] = trange[0]; mesh_data.extents_r[1] = trange[1]; mesh_data.extents_az[0] = arange[0]; mesh_data.extents_az[1] = arange[1]; int fmethod = Hv->focus_method.mapval(); mesh_data.onslant = fmethod == 1; switch(fmethod) { //case 0: case var_heliostat::FOCUS_METHOD::FLAT: mesh_data.L_f = 1.e9; //infinite break; //case 1: case var_heliostat::FOCUS_METHOD::AT_SLANT: break; //on slant. this is handled internally //case 2: case var_heliostat::FOCUS_METHOD::GROUP_AVERAGE: //average of group mesh_data.L_f = (trange[0] + trange[1])/2.; break; //case 3: case var_heliostat::FOCUS_METHOD::USERDEFINED: //user specified mesh_data.L_f = sqrt(pow(it->second->getFocalX(),2) + pow(it->second->getFocalY(),2)); break; }; mesh_data.H_h = Hv->height.val; mesh_data.H_w = Hv->width.val; if( Hv->is_faceted.val ){ mesh_data.nph = Hv->n_cant_y.val; mesh_data.npw = Hv->n_cant_x.val; } else{ mesh_data.nph = mesh_data.npw = 1; } //calculate the total reflected beam error distribution double err[2], errnorm=0., errsurf; err[0] = Hv->err_azimuth.val; err[1] = Hv->err_elevation.val; errnorm = err[0]*err[0] + err[1]*err[1]; err[0] = Hv->err_surface_x.val; err[1] = Hv->err_surface_y.val; errnorm += err[0]*err[0] + err[1]*err[1]; err[0] = Hv->err_reflect_x.val; err[1] = Hv->err_reflect_y.val; errsurf = err[0]*err[0] + err[1]*err[1]; mesh_data.s_h = sqrt(4.*errnorm + errsurf); //Set the maximum error in the binary tag location mesh_data.t_res = fmin(mesh_data.H_h, mesh_data.H_w)/10.; //Create the mesh _optical_mesh.reset(); _optical_mesh.create_mesh(&mesh_data); //Add all of the heliostats with this template type to the mesh for( vector<Heliostat>::iterator hit = _helio_objects.begin(); hit != _helio_objects.end(); hit++){ if( hit->getMasterTemplate() != it->second ) continue; sp_point *loc = hit->getLocation(); _optical_mesh.add_object( &(*hit), loc->x, loc->y); } //Now add all of the layout groups with heliostats to the main array vector<vector<void* >* > tgroups = _optical_mesh.get_terminal_data(); for(int i=0; i<(int)tgroups.size(); i++){ int ntgroup = (int)tgroups.at(i)->size(); if(ntgroup == 0) continue; _layout_groups.push_back(Hvector()); for(int j=0; j<ntgroup; j++){ _layout_groups.back().push_back( (Heliostat*)tgroups.at(i)->at(j) ); } } } //report to the log window the heliostat simulation reduction ratio char msg[200]; sprintf(msg, "Identified %d optical zones (%.1f avg size)", (int)_layout_groups.size(), (double)_heliostats.size()/(double)_layout_groups.size()); _sim_info.addSimulationNotice(msg); if(CheckCancelStatus()) return false; //check for cancelled simulation return true; } bool SolarField::FieldLayout(){ /* This should only be called by the API. If using the GUI, manually call PrepareFieldLayout(), DoLayout(), and ProcessLayoutResults() from the interface. This call is not capable of multithreading. */ WeatherData wdata; //Weather data object will be filled in PrepareFieldLayout(...) bool needs_sim = PrepareFieldLayout(*this, &wdata); if( needs_sim){ //vector<double> results; sim_results results; int sim_first, sim_last; sim_first = 0; sim_last = (int)wdata.DNI.size(); if(! DoLayout(this, &results, &wdata, sim_first, sim_last) ) return false; //For the map-to-annual case, run a simulation here if(_var_map->sf.des_sim_detail.mapval() == var_solarfield::DES_SIM_DETAIL::EFFICIENCY_MAP__ANNUAL) SolarField::AnnualEfficiencySimulation( _var_map->amb.weather_file.val, this, results); //, (double*)NULL, (double*)NULL, (double*)NULL); ProcessLayoutResults(&results, sim_last - sim_first); } else { //update the layout data ProcessLayoutResultsNoSim(); } return true; } bool SolarField::PrepareFieldLayout(SolarField &SF, WeatherData *wdata, bool refresh_only){ /* This algorithm is used to prepare the solar field object for layout simulations. A simulation is performed in this algorithm only if loading specified coordinates or if the heliostats are not filtered by performance. After calling this method, call DoLayout(...) to run the simulation for the given weather data steps, then call ProcessLayoutResults(...) to filter the heliostats by performance. This method uses set geometry values (no optimization within this algorithm), so receiver, heliostat, and tower height geometries should be specified a priori. This method can also be called in "refresh_only=true" mode, where solar field geometry parameters are updated without recalculating the heliostat positions. *****Procedure for laying out the field************** -> Choose a tower height and receiver geometry -> Determine all of the available positions for heliostats - Enforce any land constraints -> Create an unordered_map of heliostats to fill these positions - Update each heliostat object with the appropriate slant range - Update each heliostat's tracking vector to the time/day desired for canting (if applicable) - "Install" the panels on each heliostat, assigning canting and focal point -> Analyze each heliostat for optical efficiency at a range of timesteps -> Apply a filtering algorithm to determine which heliostats should be removed -> Do an annual performance run to find total productivity -> Calculate the estimated project IRR - Include market factors -> Adjust independent variables and repeat the process to find optimal system ***************************************************** */ if(!refresh_only && !wdata ) throw spexception("Prepare field layout called without a weather data object."); if(! SF.getSimInfoObject()->addSimulationNotice("Generating solar field heliostat layout") ) { SF.CancelSimulation(); return false; } if(SF.CheckCancelStatus()) return false; //check for cancelled simulation //variables vector<sp_point> HelPos; //Vector pointer for heliostat positions var_map *V = SF.getVarMap(); //If the analysis method is Hermite Polynomial, initialize polynomial coefs SF.getFluxObject()->initHermiteCoefs( *V ); //Calculate the Hermite geometry coefficients for each template for(htemp_map::iterator htemp=SF.getHeliostatTemplates()->begin(); htemp != SF.getHeliostatTemplates()->end(); htemp++) { if( htemp->second->IsEnabled() ) SF.getFluxObject()->hermiteMirrorCoefs(*htemp->second, V->sf.tht.val ); } //Calculate available heliostat positions SF.getSimInfoObject()->addSimulationNotice("Calculating available heliostat positions"); if(SF.CheckCancelStatus()) return false; //check for cancelled simulation int layout_method = V->sf.layout_method.mapval(); layout_shell *layout = SF.getLayoutShellObject(); if(!refresh_only && layout_method == var_solarfield::LAYOUT_METHOD::RADIAL_STAGGER) { //Radial stagger SF.radialStaggerPositions(HelPos); } else if(!refresh_only && layout_method == var_solarfield::LAYOUT_METHOD::CORNFIELD){ //Cornfield rows (eSolar type) SF.cornfieldPositions(HelPos); } else if(layout_method == var_solarfield::LAYOUT_METHOD::USERDEFINED || refresh_only){ //User-defined field /* Take a previously defined layout and build up the heliostat objects */ int nh = (int)layout->size(); //Number of heliostats //Resize the HelPos array HelPos.resize(nh); //Assign the xyz location.. leave assignment of the other information provided in the user //data for later. for(int i=0; i<nh; i++){ HelPos.at(i) = layout->at(i).location; } } //Weed out the heliostats that lie outside of the land boundary //Exclude any points that aren't within the land boundaries if(! SF.getSimInfoObject()->addSimulationNotice("Checking for land boundary exclusions") ){ SF.CancelSimulation(); return false; } if(SF.CheckCancelStatus()) return false; //check for cancelled simulation if( V->land.is_bounds_array.val ) { vector<int> dels; //Find which points lie outside the bounds for(unsigned int j=0; j<HelPos.size(); j++){ if(! SF.getLandObject()->InBounds(V->land, HelPos.at(j), V->sf.tht.val) ){ dels.push_back(j); } } //Delete in reverse order int nd = (int)dels.size(); for(int i=0; i<nd; i++){ HelPos.erase( HelPos.begin()+ dels.at(nd-1-i) ); } //check for problems here if(HelPos.size() == 0 ) throw spexception("The specified land boundaries resulted in an infeasible design. " "No heliostats could be placed in the layout set. Please review " "your settings for land constraints."); } /* enforce other exclusions (receiver acceptance, receiver cylinder */ //receiver diameter - delete heliostats that fall within the diameter of the receiver //solar field span angles - delete heliostats that are outside of the allowable angular range if(SF.getReceivers()->size() == 1 && SF.getReceivers()->front()->getVarMap()->rec_type.mapval() == var_receiver::REC_TYPE::EXTERNAL_CYLINDRICAL) { double azmin = SF.getVarMap()->sf.accept_min.val*D2R; double azmax = SF.getVarMap()->sf.accept_max.val*D2R; vector<int> dels; for(size_t j=0; j<HelPos.size(); j++){ double x = HelPos.at(j).x; double y = HelPos.at(j).y; //radial position check double h_rad = sqrt(x*x + y*y); if( h_rad < SF._var_map->recs.front().rec_diameter.val/2.) { dels.push_back((int)j); continue; //can't delete twice } //azimuthal position check double az = atan2(x,y); if( (az > azmax) || (az < azmin) ) dels.push_back((int)j); } //Delete in reverse order int nd = (int)dels.size(); for(int i=0; i<nd; i++){ HelPos.erase( HelPos.begin()+ dels.at(nd-1-i) ); } } //Receiver span angles if(SF.getReceivers()->size() == 1){ vector<int> dels; //receiver acceptance angle Receiver *Rec = SF.getReceivers()->front(); var_receiver *Rv = Rec->getVarMap(); int rectype = Rv->rec_type.mapval(); int j=0; for(vector<sp_point>::iterator hpos = HelPos.begin(); hpos != HelPos.end(); hpos++){ if(rectype == var_receiver::REC_TYPE::FLAT_PLATE){ // Receiver::REC_TYPE::FLAT_PLATE || rectype == Receiver::REC_TYPE::CAVITY){ PointVect rnv; Rec->CalculateNormalVector(rnv); //calculate the vector from the receiver to the heliostat sp_point offset; offset.Set( Rv->rec_offset_x.val, Rv->rec_offset_y.val, Rv->rec_offset_z.val); double tht = SF.getVarMap()->sf.tht.val; Vect hv_r; hv_r.i = hpos->x - offset.x; hv_r.j = hpos->y - offset.y; hv_r.k = hpos->z - tht; Toolbox::unitvect(hv_r); //Rotate into receiver aperture coordinates double raz = Rv->rec_azimuth.val*R2D; double rel = Rv->rec_elevation.val*R2D; Toolbox::rotation(PI - raz, 2, hv_r); Toolbox::rotation(PI - rel, 0, hv_r); double theta_x = atan2(hv_r.i, hv_r.j); double theta_y = atan2(hv_r.k, sqrt(hv_r.i*hv_r.i + hv_r.j*hv_r.j)); //check whether the angles are within the allowable range double acc_x = Rv->accept_ang_x.val*R2D, acc_y = Rv->accept_ang_y.val*R2D; acc_x *= 0.5; acc_y *= 0.5; if(Rv->accept_ang_type.mapval() == var_receiver::ACCEPT_ANG_TYPE::RECTANGULAR){ //Rectangular if(! (fabs(theta_x) < acc_x && fabs(theta_y) < acc_y)) dels.push_back(j); } else{ //Elliptical if( (theta_x*theta_x / (acc_x * acc_x) + theta_y*theta_y / (acc_y * acc_y)) > 1. ) dels.push_back(j); } } j++; } //Delete in reverse order int nd = (int)dels.size(); for(int i=0; i<nd; i++){ HelPos.erase( HelPos.begin()+ dels.at(nd-1-i) ); } } //-------------------- if(layout_method == var_solarfield::LAYOUT_METHOD::USERDEFINED || refresh_only) //update the layout positions in the land object here since the post-process call isn't made after this //SF.getLandObject()->setLayoutPositions(HelPos); SF.getLandObject()->calcLandArea( V->land, HelPos ); //----For all of the heliostat positions, create the heliostat objects and assign the correct canting/focusing int Npos = (int)HelPos.size(); if(! SF.getSimInfoObject()->addSimulationNotice("Calculating heliostat canting and aim point information") ){ SF.CancelSimulation(); return false; } if(SF.CheckCancelStatus()) return false; //check for cancelled simulation //Clear out the _heliostats array, we'll reconstruct it here Hvector *heliostats = SF.getHeliostats(); heliostats->clear(); heliostats->resize(Npos); //Set up the locations array vector<Heliostat> *helio_objects = SF.getHeliostatObjects(); helio_objects->resize(Npos); Heliostat *hptr; //A temporary pointer to avoid retrieving with "at()" over and over int focus_method; //A temporary point to pass to the template function sp_point P; P.x = 0; P.z = 0; sp_point Aim; //The aim point [m] //Keep track of the min/max field extents too double xmin=9.e99, xmax=-9.e99, ymin=9.e99, ymax=-9.e99; double hpx, hpy, hpz; //For each heliostat position for(int i=0; i<Npos; i++){ hpx = HelPos.at(i).x; hpy = HelPos.at(i).y; hpz = HelPos.at(i).z; //P.y = sqrt(pow(hpx, 2) + pow(hpy, 2)); //Determine the radial position. Set to y. Heliostat *htemp; if( layout_method == var_solarfield::LAYOUT_METHOD::USERDEFINED ) { try { htemp = SF.getHeliostatTemplates()->at( layout->at(i).helio_type ); } catch(...) { htemp = SF.getHeliostatTemplates()->begin()->second; } } else { htemp = SF.whichTemplate(V->sf.template_rule.mapval(), HelPos.at(i)); } helio_objects->at(i) = *htemp; //Copy the template to the heliostat hptr = &helio_objects->at(i); //Save a pointer for future quick reference //Save a pointer to the template for future reference hptr->setMasterTemplate( htemp ); var_heliostat *Hv = hptr->getVarMap(); //Set up the heliostat int layout_method = V->sf.layout_method.mapval(); if(layout_method != var_solarfield::LAYOUT_METHOD::USERDEFINED){ //algorithmic layouts (not user defined) focus_method = Hv->focus_method.mapval(); } else{ //User defined layouts - need to check for user defined canting and focusing if(layout->at(i).is_user_cant) { hptr->IsUserCant( true ); Vect cant; cant.Set( layout->at(i).cant.i, layout->at(i).cant.j, layout->at(i).cant.k ); hptr->setCantVector( cant ); } else{ hptr->IsUserCant( false ); } if(layout->at(i).is_user_focus) { focus_method = 3; //user defined hptr->setFocalLengthX( layout->at(i).focal_x ); hptr->setFocalLengthY( layout->at(i).focal_y ); } else{ focus_method = hptr->getVarMap()->focus_method.mapval(); } } hptr->setLocation(hpx, hpy, hpz); //Set the position if(hpx < xmin){xmin = hpx;} if(hpx > xmax){xmax = hpx;} if(hpy < ymin){ymin = hpy;} if(hpy > ymax){ymax = hpy;} //Track the min/max field extents //Quickly determine the aim point for initial calculations if(layout_method == var_solarfield::LAYOUT_METHOD::USERDEFINED || refresh_only){ //For user defined layouts... if(layout->at(i).is_user_aim){ //Check to see if the aim point is also supplied. SF.getFluxObject()->simpleAimPoint(*hptr, SF); //Calculate simple aim point first to associate heliostat with receiver. Aim = layout->at(i).aim; //Assign the specified aim point hptr->setAimPoint(Aim); //update the image plan aim point SF.getFluxObject()->keepExistingAimPoint(*hptr, SF, 0); } else{ SF.getFluxObject()->simpleAimPoint(*hptr, SF); Aim = *hptr->getAimPoint(); } //set status hptr->IsEnabled(layout->at(i).is_enabled); hptr->setInLayout(layout->at(i).is_in_layout); } else{ //Otherwise, //Determine the simple aim point - doesn't account for flux limitations SF.getFluxObject()->simpleAimPoint(*hptr, SF); Aim = *hptr->getAimPoint(); } //Aim points have been set SF.setAimpointStatus(true); //calculate and update the heliostat-to-tower vector Vect htow; htow.Set( Aim.x - hpx, Aim.y - hpy, Aim.z - hpz); //Calculate the slant range.. This should be the exact slant range. //double slant = sqrt(pow(Aim.x - hpx,2) + pow(Aim.y - hpy,2) + pow(Aim.z - hpz,2)); double slant = Toolbox::vectmag( htow ); //update the tower vector as a unit vector Toolbox::unitvect(htow); //Set the tower vector hptr->setTowerVector( htow ); hptr->setSlantRange( slant ); //Choose how to focus the heliostat switch(focus_method) { case 0: //Flat with no focusing hptr->setFocalLength( 1.e9 ); break; case 1: //Each at a focal length equal to their slant range hptr->setFocalLength( hptr->getSlantRange() ); break; case 2: //Average focal length in template group throw spexception("Average template focal length not currently implemented."); break; case 3: //User defined focusing method break; } //Construct the panel(s) on the heliostat hptr->installPanels(); //Assign a unique ID to the heliostat hptr->setId(i); //Update progress //_sim_info.setSimulationProgress(double(i)/double(Npos)); if(SF.CheckCancelStatus()) return false; //check for cancelled simulation } //----Determine nearest neighbors--- //First go through and put each heliostat into a regional group. The groups are in a cartesian mesh. //Save the heliostat field extents [xmax, xmin, ymax, ymin] SF.setHeliostatExtents(xmax, xmin, ymax, ymin); if(! SF.getSimInfoObject()->addSimulationNotice("Determining nearest neighbors for each heliostat") ){ SF.CancelSimulation(); return false; } //Update the neighbor list based on zenith. Also initialize the layout groups. double *helio_extents = SF.getHeliostatExtents(); bool isok = SF.UpdateNeighborList(helio_extents, 0. ); //_ambient.getSolarZenith()); don't include shadowing effects in layout (zenith = 0.) if(SF.CheckCancelStatus() || !isok) return false; //check for cancelled simulation if(V->sf.is_opt_zoning.val ){ if(! SF.getSimInfoObject()->addSimulationNotice("Calculating layout optical groups") ){ SF.CancelSimulation(); return false; } isok = SF.UpdateLayoutGroups(helio_extents); //Assign heliostats to groups for simplified intercept factor calculations if(SF.CheckCancelStatus() || !isok) return false; SF.getSimInfoObject()->addSimulationNotice("Optical group calculations complete"); } //----Over each heliostat, calculate optical efficiency for the set of design points //which simulation criteria should we use to filter the heliostats? int des_sim_detail = V->sf.des_sim_detail.mapval(); unordered_map<int, Heliostat*> *helio_by_id = SF.getHeliostatsByID(); if(des_sim_detail == var_solarfield::DES_SIM_DETAIL::DO_NOT_FILTER_HELIOSTATS || refresh_only){ //Do not filter any heliostats //Simulate the default design point to ensure equal comparison vector<string> vdata = split(Ambient::getDefaultSimStep(), ","); int hour, dom, month; to_integer(vdata.at(0), &dom); to_integer(vdata.at(1), &hour); to_integer(vdata.at(2), &month); sim_params P; //dni, T, P, V, Wt to_double(vdata.at(3), &P.dni); to_double(vdata.at(4), &P.Tamb); to_double(vdata.at(5), &P.Patm); to_double(vdata.at(6), &P.Vwind); to_double(vdata.at(7), &P.Simweight); DTobj dt; dt.setZero(); dt._mday = dom; dt._hour = hour; dt._month = month; //Calculate the sun position vector double az, zen; Ambient::calcSunPosition(*V, dt, &az, &zen); Vect sunvect = Ambient::calcSunVectorFromAzZen(az, zen); //Add all of the heliostat locations to the final vector heliostats->resize(Npos); for(int i=0; i<Npos; i++){ heliostats->at(i) = &helio_objects->at(i); //heliostats->at(i)->setInLayout(true); //All of the heliostats are included in the final layout //Update the tracking vector. This defines corner geometry for plotting. heliostats->at(i)->updateTrackVector(sunvect); } SF.SimulateTime(hour, dom, month, P); //Save the heliostats in an array by ID# helio_by_id->clear(); for(int i=0; i<Npos; i++){ (*helio_by_id)[ heliostats->at(i)->getId() ] = heliostats->at(i); } } else if(des_sim_detail != var_solarfield::DES_SIM_DETAIL::DO_NOT_FILTER_HELIOSTATS){ //1 :: Subset of days and hours, specified //2 :: Subset of days, all hours during the days //3 :: Full annual simulation from Weather file //4 :: Limited annual simulation from weather file //5 :: Representative profiles //Copy the previously calculated weather data into the object passed to this method SF.copySimulationStepData(*wdata); //Check to see if at least one data value is available in the weather data object int nsim = wdata->size(); if( nsim == 0 ){ SF.getSimErrorObject()->addSimulationError((string)"No design-point data was provided for calculation of the solar field power output. Use setStep(...) to assign DNI, day, and hour info.",true,false); return false; } else{ //if needed, determine clear sky DNI and replace the weather file DNI if (V->amb.insol_type.mapval() != var_ambient::INSOL_TYPE::WEATHER_FILE_DATA){ //DateTime *dtc = ambient->getDateTimeObj(); DateTime dt; double dom, hour, month, dni, tdb, pres, wind, az, zen, step_weight; for(int i=0; i<wdata->size(); i++){ //Get the design-point day, hour, and DNI wdata->getStep(i, dom, hour, month, dni, tdb, pres, wind, step_weight); //Convert the day of the month to a day of year int doy = dt.GetDayOfYear(2011,int(month),int(dom)); //Calculate the sun position Ambient::setDateTime(dt, hour, doy); //latitude, longitude, and elevation should be set in the input file Ambient::calcSunPosition(*V, dt, &az, &zen, true); //calculate DNI double dniclr = Ambient::calcInsolation(*V, az*D2R, zen*D2R, doy); //Set to the new value wdata->setStep(i, dom, hour, month, dniclr, tdb, pres, wind, step_weight); } //reset to the old date time //ambient->setDateTime(dtc->_hour, dtc->GetDayOfYear()); } //Set up the _heliostats array for(int i=0; i<Npos; i++){ heliostats->at(i) = &helio_objects->at(i); //At first, the heliostats array will contain all of the positions in the field heliostats->at(i)->resetMetrics(); //Reset all of the heliostat metrics to the original state } } SF.getSimInfoObject()->setTotalSimulationCount(nsim); return true; //Return a flag indicating that additional simulation is required } return false; //if not a detailed design, we don't need additional simulation. } bool SolarField::DoLayout( SolarField *SF, sim_results *results, WeatherData *wdata, int sim_first, int sim_last){ /* This algorithm is static (i.e. it only refers to arguments passed to it and not to the "this" SolarField object. The algorithm will simulate the performance of all heliostats in the SF heliostats array for timesteps in wdata from sim_first to sim_last. If sim_first arg is not set, it will be set to 0. if sim_last arg is not set, it will be set to wdata->size() Threading note: This method is duplicated in the LayoutSimThread class. Ensure both methods are substantively consistent for predictable simulation behavior. */ if(! SF->getSimInfoObject()->addSimulationNotice("Simulating design-point conditions") ){ SF->CancelSimulation(); return false; } double dni, dom, doy, hour, month, tdb, pres, wind, step_weight; int hoy=0; bool is_pmt_factors = SF->getVarMap()->fin.is_pmt_factors.val; vector<double> *tous = &SF->getVarMap()->fin.pricing_array.Val(); //int Npos = SF->getHeliostats()->size(); //Simulate for each time //int nsim_actual=0; //keep track of the day of the year for _des_sim_detail = 3 //double dni_ave=0.; //keep track of the average DNI value if(SF->CheckCancelStatus()) return false; //check for cancelled simulation if(sim_first < 0) sim_first = 0; if(sim_last < 0) sim_last = wdata->size(); int nsim = sim_last - sim_first + 1; //reserve memory try { results->reserve(nsim); } catch(...) { SF->getSimInfoObject()->addSimulationNotice("Error allocating memory for layout results vector"); } DateTime DT; SF->getSimInfoObject()->setTotalSimulationCount(nsim); for(int i=sim_first; i<sim_last; i++){ if(! SF->getSimInfoObject()->setCurrentSimulation(i+1) ) return false; //Get the design-point day, hour, and DNI wdata->getStep(i, dom, hour, month, dni, tdb, pres, wind, step_weight); //Convert the day of the month to a day of year doy = DT.GetDayOfYear(2011,int(month),int(dom)); //Calculate the sun position Ambient::setDateTime(DT, hour, doy); if(is_pmt_factors) hoy = DT.GetHourOfYear(); //latitude, longitude, and elevation should be set in the input file double az; double zen; Ambient::calcSunPosition(*SF->getVarMap(), DT, &az, &zen, true); //If the sun is not above the horizon, don't continue if( zen > 90. ) continue; az *= D2R; zen *= D2R; //Simulate field performance sim_params P; P.dni = dni; P.Tamb = tdb; P.Vwind = wind; P.Patm = pres/1000.; P.Simweight = step_weight; if(is_pmt_factors) P.TOUweight = tous->at(hoy); P.is_layout = true; SF->Simulate(az, zen, P); //nsim_actual ++; dni_ave+=dni; //store the results results->push_back( sim_result() ); double azzen[] = {az,zen}; results->back().process_analytical_simulation( *SF, 0, azzen); //2); if(SF->CheckCancelStatus()) return false; //check for cancelled simulation } return true; } void SolarField::ProcessLayoutResultsNoSim() { ProcessLayoutResults(0,0); } void SolarField::ProcessLayoutResults( sim_results *results, int nsim_total){ /* The sort metrics are mapped from the GUI in the following order: 0 | Power to the receiver 1 | Total efficiency 2 | Cosine efficiency 3 | Attenuation efficiency 4 | Intercept efficiency 5 | Blocking efficiency 6 | Shadowing efficiency 7 | Market-weighted power to the receiver Default is 7. */ bool needs_processing = results != 0 && nsim_total > 0; int Npos = (int)_heliostats.size(); int nresults = 0; //initialize if( needs_processing ) { _sim_info.ResetValues(); if(! _sim_info.addSimulationNotice("Ranking and filtering heliostats") ) { CancelSimulation(); return; } //Update each heliostat with the ranking metric and sort the heliostats by the value vector<double> hsort(Npos); double rmet; //, nsimd=(float)nsim_total; //Save the heliostats in an array by ID# _helio_by_id.clear(); for(int i=0; i<Npos; i++){ _helio_by_id[ _heliostats.at(i)->getId() ] = _heliostats.at(i); } //Of all of the results provided, calculate the average of the ranking metric int rid = _var_map->sf.hsort_method.mapval(); nresults = (int)results->size(); //compile the results from each simulation by heliostat for(int i=0; i<Npos; i++){ int hid = _heliostats.at(i)->getId(); //use the heliostat ID from the first result to collect all of the other results rmet = 0.; //ranking metric for(int j=0; j<nresults; j++) rmet += results->at(j).data_by_helio[ hid ].getDataByIndex( rid ); //accumulate ranking metric as specified in rid //normalize for available heliostat power if applicable double afact = 1.; if( rid == helio_perf_data::PERF_VALUES::POWER_TO_REC || rid == helio_perf_data::PERF_VALUES::POWER_VALUE ) afact = _heliostats.at(i)->getArea(); double rank_val = rmet / (afact*(float)nresults); //Calculate the normalized ranking metric. Divide by heliostat area if needed _helio_by_id[hid]->setRankingMetricValue( rank_val ); //store the value hsort.at(i) = rank_val; //also store in the sort array } //quicksort by ranking metric value. Correlate _heliostats vector quicksort(hsort, _heliostats, 0, Npos-1); } //Simulate the default design point to ensure equal comparison double az_des, zen_des; if(! CalcDesignPtSunPosition(_var_map->sf.sun_loc_des.mapval(), az_des, zen_des) ) return; sim_params P; P.dni = _var_map->sf.dni_des.val; P.Tamb = 25.; P.Patm = 1.; P.Vwind = 0.; P.Simweight = 1.; P.is_layout = true; if( zen_des > 90. ) { throw spexception("The design point sun position is invalid. Simulation could not be completed."); return; } else { Simulate(az_des*D2R, zen_des*D2R, P); } _q_to_rec = 0.; for(int i=0; i<Npos; i++){ _q_to_rec += _heliostats.at(i)->getPowerToReceiver(); } //Calculate the required incident power before thermal losses double q_loss_tot = 0.; for(int i=0; i<(int)_receivers.size(); i++){ _receivers.at(i)->CalculateThermalLoss(1., 0.); double ql = _receivers.at(i)->getReceiverThermalLoss(), qp = _receivers.at(i)->getReceiverPipingLoss(); q_loss_tot += ql + qp; } double q_inc_des = _var_map->sf.q_des.val + q_loss_tot; _q_des_withloss = q_inc_des; //save this //Check that the total power available is at least as much as the design point requirement. If not, notify //the user that their specified design power is too high for the layout parameters. if(_q_to_rec < q_inc_des*1.e6 && needs_processing) { string units; double xexp = log10(_q_to_rec), xmult; if(xexp>9.) { units = "GW"; xmult = 0.001; } else if(xexp>6.) { units = "MW"; xmult = 1.; } else{ units = "kW"; xmult = 1000.; } char msg[1000]; sprintf(msg, "The maximum available power for this field layout is %.2f %s, and the required design power is %.2f %s." "The field cannot generate sufficient power to meet the design requirement. Consider adjusting design point conditions " "to generate a satisfactory design.", (float)(_q_to_rec*1.e-6*xmult), units.c_str(), (float)(q_inc_des*xmult), units.c_str()); _q_des_withloss = q_inc_des; _sim_error.addSimulationError(string(msg)); //, true, true); //return; } if( needs_processing ) { double filter_frac = _var_map->sf.is_prox_filter.val ? _var_map->sf.prox_filter_frac.val : 0.; //Determine the heliostats that will be used for the plant double q_cutoff=_q_to_rec; //[W] countdown variable to decide which heliostats to include int isave; int nfilter=0; double q_replace=0.; for(isave=0; isave<Npos; isave++){ // double q = _heliostats.at(isave)->getPowerToReceiver(); q_cutoff += -q; if(q_cutoff < q_inc_des*1.e6) { nfilter++; q_replace += q; } if(q_cutoff < q_inc_des*1.e6*(1.-filter_frac)){break;} } //The value of isave is 1 entry more than satisfied the criteria. if(_var_map->sf.is_prox_filter.val){ //sort the last nfilter*2 heliostats by proximity to the reciever and use the closest ones. Hvector hfilter; vector<double> prox; for(int i=max(isave-2*(nfilter-1), 0); i<isave; i++){ hfilter.push_back( _heliostats.at(i) ); prox.push_back( hfilter.back()->getRadialPos() ); } quicksort(prox, hfilter, 0, (int)prox.size()-1); //swap out the heliostats in the main vector with the closer ones. double q_replace_new=0.; int ireplace = isave-1; int nhf = (int)hfilter.size(); int irct=0; while(q_replace_new < q_replace && irct < nhf){ _heliostats.at(ireplace) = hfilter.at(irct); q_replace_new += _heliostats.at(ireplace)->getPowerToReceiver(); ireplace--; irct++; } //update the isave value isave = ireplace+1; } //Delete all of the entries up to isave-1. _heliostats.erase(_heliostats.begin(), _heliostats.begin()+isave); //Remove any heliostat in the layout that does not deliver any power to the receiver isave = 0; for(size_t i=0; i<_heliostats.size(); i++){ if(_heliostats.at(i)->getPowerToReceiver() > 0.) { isave = (int)i; break; } } if(isave > 0) _heliostats.erase(_heliostats.begin(), _heliostats.begin()+isave); Npos = (int)_heliostats.size(); } //end needs_processing //Save the heliostats in an array by ID# _helio_by_id.clear(); for(int i=0; i<Npos; i++){ _helio_by_id[ _heliostats.at(i)->getId() ] = _heliostats.at(i); } _sf_area = 0.; //calculate total reflector area //Mark these heliostats as contained in the final layout and recalculate the field extents _helio_extents[0] = -9e9; //xmax _helio_extents[1] = 9e9; //xmin _helio_extents[2] = -9e9; //ymax _helio_extents[3] = 9e9; //ymin for(int i=0; i<Npos; i++){ _heliostats.at(i)->setInLayout(true); //Set as in the layout _sf_area += _heliostats.at(i)->getArea(); //Refactor the extents sp_point *loc = _heliostats.at(i)->getLocation(); if(loc->x > _helio_extents[0]) _helio_extents[0] = loc->x; if(loc->x < _helio_extents[1]) _helio_extents[1] = loc->x; if(loc->y > _helio_extents[2]) _helio_extents[2] = loc->y; if(loc->y < _helio_extents[3]) _helio_extents[3] = loc->y; } //Limit the extents to always include the plot origin if(_helio_extents[0] < 0.) _helio_extents[0] = 0.; if(_helio_extents[1] > 0.) _helio_extents[1] = 0.; if(_helio_extents[2] < 0.) _helio_extents[2] = 0.; if(_helio_extents[3] > 0.) _helio_extents[3] = 0.; //Create an estimate of the annual energy output based on the filtered heliostat list _estimated_annual_power = 0.; if(needs_processing) { for(int i=0; i<Npos; i++){ int hid = _heliostats.at(i)->getId(); for(int j=0; j<nresults; j++){ _estimated_annual_power += results->at(j).data_by_helio[ hid ].getDataByIndex( helio_perf_data::PERF_VALUES::POWER_VALUE ); //this include receiver efficiency penalty } } } else { _estimated_annual_power = _q_to_rec; } UpdateLayoutAfterChange(); return; } void SolarField::UpdateLayoutAfterChange() { /* This method is called upon completion of the layout, and ties up loose ends with: - making sure area calculations are complete - updating the layout information stored in the variable map - updating the layout information stored in the _layout class member - calling the method to update all solar field calculated variables */ //update calculated heliostat area calcHeliostatArea(); //update the layout positions in the land area calculation std::vector<sp_point> lpos; lpos.reserve( _heliostats.size() ); for(int i=0; i<(int)_heliostats.size(); i++) { if( _heliostats.at(i)->IsInLayout() ) //only include heliostats that are in the layout lpos.push_back( *_heliostats.at(i)->getLocation() ); } _land.calcLandArea(_var_map->land, lpos ); //update the layout data interop::UpdateMapLayoutData(*_var_map, &_heliostats); //update the layout shell _layout.clear(); _layout.reserve( _heliostats.size() ); for(int i=0; i<(int)_heliostats.size(); i++) { layout_obj lo; Heliostat* H = _heliostats.at(i); lo.location = *H->getLocation(); lo.aim = *H->getAimPoint(); lo.cant = *H->getCantVector(); lo.focal_x = H->getFocalX(); lo.focal_y = H->getFocalY(); lo.is_user_aim = false; lo.is_user_cant = H->IsUserCant(); lo.is_user_focus = false; lo.is_enabled = H->IsEnabled(); lo.is_in_layout = H->IsInLayout(); _layout.push_back( lo ); } //update costs updateAllCalculatedParameters(*_var_map); return; } void SolarField::AnnualEfficiencySimulation( SolarField &SF, sim_results &results){ string wf = SF.getVarMap()->amb.weather_file.val; SolarField::AnnualEfficiencySimulation( wf, &SF, results); } void SolarField::AnnualEfficiencySimulation( string weather_file, SolarField *SF, sim_results &results) //, double *azs, double *zens, double *met) //overload { /* Take the simulations provided in the "results" array and create an annual simulation from the specified weather file. Each heliostat is evaluated based on the efficiency values provided in the results along with the associated solar position. */ //Create arrays of the available sun positions int nresult = (int)results.size(); vector<double> solaz(nresult), solzen(nresult); for(int i=0; i<nresult; i++){ solaz.at(i) = results.at(i).solar_az; solzen.at(i) = results.at(i).solar_zen; } var_map *V = SF->getVarMap(); Ambient::readWeatherFile( *V ); //wdannual, weather_file, amb); int rindex = V->sf.hsort_method.mapval(); int Npos = (int)SF->getHeliostats()->size(); //Clear the existing ranking metric value from the heliostats Hvector *helios = SF->getHeliostats(); for(int i=0; i<Npos; i++){ helios->at(i)->setRankingMetricValue(0.); } vector<double> pfs = V->fin.pmt_factors.val; bool is_pmt_factors = V->fin.is_pmt_factors.val; //Get design point DNI for some simulations double dni_des = V->sf.dni_des.val; unordered_map<int, helio_perf_data> *resmap[3]; WeatherData *wdannual = &V->amb.wf_data.val; //Simulate each step int nsim = wdannual->size(); double nsimd = 1./(double)nsim; unordered_map<int, double> rank_temp; //initialize temp rank value array for(int j=0; j<Npos; j++) rank_temp[helios->at(j)->getId()] = 0.; simulation_info *siminfo = SF->getSimInfoObject(); siminfo->setTotalSimulationCount(nsim); siminfo->setCurrentSimulation(0); if(! siminfo->addSimulationNotice("Simulating hourly weather profile...") ){ SF->CancelSimulation(); return; } DateTime DT; for(int i=0; i<nsim; i++){ //Calculate the solar position based on the time step //Convert the day of the month to a day of year int month = (int)wdannual->Month.at(i); int mday = (int)wdannual->Day.at(i); int doy = DateTime::CalculateDayOfYear(2011, month, mday); double hour = wdannual->Hour.at(i)+0.5; //Calculate the sun position Ambient::setDateTime(DT, hour, (double)doy); //latitude, longitude, and elevation should be set in the input file double az, zen; Ambient::calcSunPosition(*V, DT, &az, &zen); //no time correction because 'hour' is adjusted above double dni = wdannual->DNI.at(i); //If the sun is not above the horizon, don't process if( zen > PI*0.5) continue; //Find the 3 efficiency values closest to the current sun position int jsave[3]={0,0,0}; double rdiff[3] = {9.e9, 9.e9, 9.e9}; for(int j=0; j<nresult; j++){ double rdiff2 = sqrt( std::pow(az-solaz.at(j),2) + std::pow(zen-solzen.at(j),2) ); int k=3; while( rdiff2 < rdiff[k-1] && k>0) k+= -1; //rdiff is in order of closest to farthest. find where the new point should go //If a position is found within the array... if(k<3){ //shift values in the arrays for(int kk=2; kk>k; kk+= -1){ if(kk>0){ rdiff[kk] = rdiff[kk-1]; jsave[kk] = jsave[kk-1]; } } //insert new value rdiff[k] = rdiff2; jsave[k] = j; } } //Calculate the XYZ plane based on cross-product of the two vectors. Normal vector components are multipliers on plane fit. Vect t1, t2, cp; for(int j=0; j<3; j++) resmap[j] = &results.at(jsave[j]).data_by_helio; double rm_az[3], rm_zen[3]; for(int j=0; j<3; j++){ rm_az[j] = results.at(jsave[j]).solar_az; rm_zen[j] = results.at(jsave[j]).solar_zen; } for(unordered_map<int, helio_perf_data>::iterator it = resmap[0]->begin(); it != resmap[0]->end(); it++){ //For each heliostat int hid = it->first; double zdat[3]; for(int j=0; j<3; j++) zdat[j] = (*resmap[j])[hid].getDataByIndex( rindex ); t1.Set( rm_az[1] - rm_az[0], rm_zen[1] - rm_zen[0], zdat[1] - zdat[0]); t2.Set( rm_az[2] - rm_az[0], rm_zen[2] - rm_zen[0], zdat[2] - zdat[0]); cp = Toolbox::crossprod(t1, t2); if(cp.k < 0.){ cp.i = - cp.i; cp.j = - cp.j; cp.k = - cp.k; } //find min and max double zmin = 9.e9, zmax = -9.e9; for(int j=0; j<3; j++){ if(zdat[j] < zmin) zmin = zdat[j]; if(zdat[j] > zmax) zmax = zdat[j]; } //Now based on the location of the point in az,el coordinates, we can calculate an interpolated efficiency double z_interp = zdat[0] - (cp.i*(az-rm_az[0]) + cp.j*(zen-rm_zen[0]))/cp.k; if(z_interp < zmin) z_interp = zmin; if(z_interp > zmax) z_interp = zmax; //Calculate the ranking metric. double payfactor = 1., zval ; switch(rindex) { case helio_perf_data::PERF_VALUES::POWER_VALUE: if(is_pmt_factors) { vector<int> *TOD = SF->getFinancialObject()->getScheduleArray(); payfactor = pfs[TOD->at(i)-1]; } case helio_perf_data::PERF_VALUES::POWER_TO_REC: zval = dni/dni_des * payfactor * z_interp * nsimd; break; default: zval = z_interp * nsimd; } rank_temp[hid] += zval; } if(i%200==0){ if(! siminfo->setCurrentSimulation(i) ) break; } } siminfo->setCurrentSimulation(0); //Clear the results array and set up a dummy result that can be used to sort the field if(nsim > 1) results.erase( results.begin() + 1, results.end()); for(unordered_map<int,double>::iterator it = rank_temp.begin(); it != rank_temp.end(); it++) results.begin()->data_by_helio[it->first].setDataByIndex( rindex, it->second ); } Heliostat *SolarField::whichTemplate(int method, sp_point &pos){ /* This function takes as arguments an integer indicating the method for determining which heliostat template to use (method) and the current point {x,y,z} location of the heliostat. The method uses information attributes of the current SolarField object to determine which heliostat template is appropriate. --Methods description-- 0 = Use single template 1 = Specified range 2 = Even radial distribution The heliostat field is broken into equidistant sections depending on the number of heliostat templates provided. Heliostats are assigned to templates depending on which section they fall into. */ int Nht = (int)_helio_templates.size(); //count the number of enabled templates int Nht_active = 0; for(int i=0; i<(int)_helio_templates.size(); i++) if( _helio_templates.at(i)->IsEnabled() ) Nht_active++; //get the field limits from the land class double rad[2]; double rpos = sqrt(pow(pos.x,2) + pow(pos.y,2)), // /_var_map->sf.tht.val, azpos = atan2(pos.x, pos.y); _land.getExtents(*_var_map, rad); double radmin = rad[0], radmax = rad[1]; switch(method) { //case SolarField::TEMPLATE_RULE::SINGLE: case var_solarfield::TEMPLATE_RULE::USE_SINGLE_TEMPLATE: //Use single template return _helio_templates.find( _var_map->sf.temp_which.mapval() )->second; /*for(int i=0; i<(int)_helio_templates.size(); i++) { if( _temp_which == _helio_templates.at(i)->getId() ) return _helio_templates.at(i); }*/ //case SolarField::TEMPLATE_RULE::SPEC_RANGE: case var_solarfield::TEMPLATE_RULE::SPECIFIED_RANGE: { double tradmax, tradmin, tazmax, tazmin; for(int i=0; i<Nht; i++) { var_heliostat *Hv = _helio_templates.at(i)->getVarMap(); tradmin = Hv->temp_rad_min.val; tradmax = Hv->temp_rad_max.val; tazmin = Hv->temp_az_min.val * D2R; tazmax = Hv->temp_az_max.val * D2R; if(rpos >= tradmin && rpos < tradmax && azpos >= tazmin && azpos < tazmax) return _helio_templates.at(i); } //none caught.. return the first template return _helio_templates.at(0); break; } //case SolarField::TEMPLATE_RULE::EVEN_DIST: case var_solarfield::TEMPLATE_RULE::EVEN_RADIAL_DISTRIBUTION: { //calculate which template is being used by comparing the current position to the radial range of each template. int ht = int(floor((rpos - radmin)/( (radmax+0.0001-radmin)/double(Nht_active) ))); int ht_ct = -1; //Counter for number of enabled templates int ht_save = 0; //Save the value of the applicable template for(int i=0; i<Nht; i++) { if( _helio_templates.at(i)->IsEnabled() ) ht_ct++; //only count enabled templates if( ht_ct == ht ) { //once the template count matches the calculated number, save and move on ht_save = i; break; } } return _helio_templates.at(ht_save); } default: break; } throw spexception("An error occurred while calculating heliostat template placement. Please contact support for debugging help."); } void SolarField::TemplateRange(int pos_order, int method, double *rrange, double *arange){ /* This function is the inverse of 'SolarField::whichTemplate'. Provide a heliostat template index within the larger set and a method for dividing the field, and this calculates the valid range of the template. >> pos_order = the position of this template in the field. Lower is nearer the receiver. << rrange[2] . Sets the values of len=2 array : {rmin,rmax} --Methods description-- 0 = Use single template 1 = Specified range 2 = Even radial distribution */ int Nht = (int)_helio_templates.size(); //get the field limits from the land class double rad[2]; _land.getExtents(*_var_map, rad); double radmin = rad[0], radmax = rad[1]; double drad; switch(method) { case 0: //Use single template rrange[0] = radmin; rrange[1] = radmax; arange[0] = -PI; arange[1] = PI; return; break; case 1: //Specified range { var_heliostat *Hv = _helio_templates.at(pos_order)->getVarMap(); rrange[0] = Hv->temp_rad_min.val; rrange[1] = Hv->temp_rad_max.val; arange[0] = Hv->temp_az_min.val *D2R; arange[1] = Hv->temp_az_max.val *D2R; return; break; } case 2: //equal spatial separation drad = (radmax - radmin)/float(Nht); rrange[0] = radmin + pos_order*drad; rrange[1] = rrange[0] + drad; arange[0] = -PI; arange[1] = PI; return; break; default: rrange[0] = radmin; rrange[1] = radmax; arange[0] = -PI; arange[1] = PI; } } void SolarField::radialStaggerPositions(vector<sp_point> &HelPos) { /* Calculate the possible heliostat positions in the solar field, given certain minimum/maximum extent requirements, heliostat geometry, and tower height. This function requires that the following SolarField attributes be defined: -> radmin -> radmax -> q_des -> tht -> helio_templates -> land (if land filter is used) -> spacing_reset Note that DELSOL uses a variable called "FSLIP" to remove heliostats from the first row when spacing is reset. This is based on an empirical relationship that defines the average spacing of a radial "zone" and moves inward until heliostat must be removed. This convention is not adopted here. Instead, the spacing is determined either by optimization or a user-specified initial spacing factor, and spacing is reset to the initial ratio when the current row azimuth spacing divided by the compressed row spacing exceeds the value "_spacing_reset". Radial spacing can be calculated as follows: -> Using an empirical relationship from DELSOL -> To eliminate blocking but not shading -> Optimized? (not yet implemented) The heliostat templates will be used according to the following rules: -> For 'N' templates in a 1-D array, the field will be broken into N radial sections from radmin to radmax. Each template will be used in its corresponding radial section, with the first template corresponding to the first radial group. */ //any declarations int i,j; int N_max; //Upper estimate for the number of heliostats in the field, sizes the arrays //Calculate limits in meters //get the field limits from the land class double rad[2]; _land.getExtents(*_var_map, rad); double radmint = rad[0], radmaxt = rad[1]; //Calculate an upper estimate of the size of the heliostat positions array to avoid resizing all the time { //ensure local scope for these temporary variables double r_coll_temp; double r_coll_min = 9.e9; for(htemp_map::iterator it=_helio_templates.begin(); it != _helio_templates.end(); it++) { r_coll_temp = it->second->getCollisionRadius(); if(r_coll_temp < r_coll_min) r_coll_min = r_coll_temp; //minimum collision radius in any combination } int nr_max = int((radmaxt - radmint)/(r_coll_min*2.)); int naz_max = int((radmaxt + radmint)/2.*(_var_map->sf.accept_max.val - _var_map->sf.accept_min.val)*D2R/(r_coll_min*2.)); N_max = nr_max * naz_max; //Estimate the array size } HelPos.reserve(N_max); //choose which (initial) template to use to lay out the positions Heliostat *Htemp=0; var_heliostat *Htv; switch (_var_map->sf.template_rule.mapval()) { //case SolarField::TEMPLATE_RULE::SINGLE: case var_solarfield::TEMPLATE_RULE::USE_SINGLE_TEMPLATE: Htemp = _helio_templates.find( _var_map->sf.temp_which.mapval() )->second; break; //case SolarField::TEMPLATE_RULE::SPEC_RANGE: //case SolarField::TEMPLATE_RULE::EVEN_DIST: case var_solarfield::TEMPLATE_RULE::SPECIFIED_RANGE: case var_solarfield::TEMPLATE_RULE::EVEN_RADIAL_DISTRIBUTION: // Use the first enabled template in the list for(int i=0; i<(int)_helio_templates.size(); i++) { if( _helio_templates.at(i)->IsEnabled() ) { Htemp = _helio_templates.at(i); break; } } break; default: throw spexception("An invalid heliostat template rule was specified. Please contact support for debugging help."); } Htv = Htemp->getVarMap(); //how to calculate radial spacing of the rows? if(_var_map->sf.rad_spacing_method.mapval() == var_solarfield::RAD_SPACING_METHOD::DELSOL_EMPIRICAL_FIT) //use the empirical relationship from delsol { /* Documentation on these methods is from Kistler (1986), pages 39-41. DELSOL3 code lines 1223-1286. There are separate relationships depending on surround/cavity receiver, round/rectangular heliostats. For this method, only 1 heliostat template can be used. */ //Check to see if only 1 heliostat template is used. /*----------Calculate the row positions----------*/ int nr = 1; //row counter double r_c = radmint; //current row position bool is_slip = true; //initialize //Calculate the pointing angle for the first row double phi_0 = atan(_var_map->sf.tht.val/r_c); //Elevation angle from the heliostats in the first row to the receiver double tan_phi_0 = _var_map->sf.tht.val/r_c; double r_reset = r_c; //Hold on to the radius where the spacing has reset //Calculate azimuthal spacing variables double daz_init; //The initial physical spacing between heliostats azimuthally double az_ang, azmin, azmid, haz, dr_c; int Nhelio = 0; azmid = (_var_map->sf.accept_max.val + _var_map->sf.accept_min.val)/2.; //[rad] The midpoint of the acceptance window int hpr=-1; //heliostats per row are calculated after slip planes while(r_c < radmaxt){ /* Calculations in this loop use the current radial position value (r_c), the flag for whether the row is a slip plane (is_slip), and the elevation angle phi_0 that is consistent with r_c. These should be initialized and are updated at the end of the loop. */ //Choose the heliostat template based on the current row position, updating only after slip planes if(is_slip) { sp_point cpos; cpos.Set( 0., r_c, 0. ); Htemp = whichTemplate(_var_map->sf.template_rule.mapval(), cpos ); Htv = Htemp->getVarMap(); } bool is_round = Htv->is_round.mapval() == var_heliostat::IS_ROUND::ROUND; //Get the minimum separation between heliostats that ensures no collision double r_coll = Htemp->getCollisionRadius(); //Collision radius for current template double hw = Htv->width.val; //The radial separation formula is the same for both round and rectangular heliostats double rsep = 1.1442399/tan_phi_0-1.093519+3.0683558*phi_0-1.1255617*pow(phi_0,2); double asep; //Calculate azimuthal separation if(is_round){ //Round asep = 1.609666+0.29654848*phi_0+0.019137019/(phi_0-0.012341664); asep *= 1./(1.-rsep*hw/(_var_map->sf.tht.val*2. * r_c)); //D1275 is always used. rsep *= .5; //Correct for the half-size convention used dr_c = rsep*Htv->width.val; } else{ //Rectangular asep = (1.7490871+0.63964099*phi_0+0.028726279/(phi_0-0.049023315)); asep *= 1./(1.-rsep*hw/(_var_map->sf.tht.val*2. * r_c)); //D1275 is always used. rsep *= .5; //Correct for the half-size convention used dr_c = rsep*Htv->height.val; } //----Now add heliostats to each row---- //If the collision radius limit is exceeded, remove heliostats. //daz_init = Azimuthal straight-line distance daz_init = hw*asep; //Normal spacing int col_factor = r_coll*2. > hw*asep ? 2 : 1; //Should this row reset the spacing? if( is_slip ) { az_ang = 2.*atan2(daz_init, 2.*r_c); //The angular spacing of the heliostats in the row //How many heliostats are in this row? hpr = int(floor(fmin((_var_map->sf.accept_max.val - _var_map->sf.accept_min.val), 2.*PI)/az_ang)); //-----calculate the position of each heliostat in the row.----- //Go min to max around the arc. //Every other row, a heliostat should be at the bisection angle of the acceptance window. //In the alternate rows, two heliostats will be evenly centered about the bisecting angle. //Calculate the starting minimum azimuth angle azmin = azmid - az_ang*hpr/2.; } if( hpr < 0 ) throw spexception("An algorithmic error occurred during heliostat placement. Please contact support for debugging help."); j=0; while(j<hpr){ //For the heliostats in the row haz = azmin + az_ang*double(j) + az_ang/2.*double(nr%2); //heliostat azimuth angle HelPos.push_back(sp_point()); HelPos.at(Nhelio).x = r_c*sin(haz); HelPos.at(Nhelio).y = r_c*cos(haz); HelPos.at(Nhelio).z = 0.; Nhelio++; j += col_factor; //If we're skipping heliostats, col_factor will increment by 2 } //Increment to the next row, but make sure there's enough room to avoid collision r_c += max(dr_c, r_coll*2.); //Is the next row a slip plane? if(r_c/r_reset > _var_map->sf.spacing_reset.val){ is_slip = true; r_reset = r_c; } else{ is_slip = false; } nr++; //Row number, starts at 1 //now with the solved radius, prepare for the next radius phi_0 = atan(_var_map->sf.tht.val/r_c); tan_phi_0 = _var_map->sf.tht.val/r_c; } } else if( (_var_map->sf.rad_spacing_method.mapval() == var_solarfield::RAD_SPACING_METHOD::NO_BLOCKINGDENSE || _var_map->sf.rad_spacing_method.mapval() == var_solarfield::RAD_SPACING_METHOD::ELIMINATE_BLOCKING) && Htv->is_round.mapval() == var_heliostat::IS_ROUND::ROUND){ /* Space using radial stagger with the row position chosen for "close packing" from the perspective of the receiver. */ int nr=1; //row counter double r_c = radmint; //Initialize bool is_slip = true; //For round heliostats, all heliostats must be round (no multiple templates. Macro-level geometry //will use the first heliostat (excludes specific canting, aiming, focusing etc.). double phi_0 = atan(_var_map->sf.tht.val/r_c); //elevation angle of the heliostats in the first row //Calculate azimuthal spacing variables double daz_init; //The initial physical spacing between heliostats azimuthally double az_ang, azmin, azmid, haz, dr_c; int Nhelio = 0; azmid = (_var_map->sf.accept_max.val + _var_map->sf.accept_min.val)/2.; //[rad] The midpoint of the acceptance window //Keep track of the row positions vector<double> rowpos; rowpos.push_back(r_c); //keep track of whether each row was a slip plane vector<bool> slips; slips.push_back(true); while(r_c < radmaxt){ //Choose the heliostat template based on the current row position, updating only after slip planes if(is_slip) { sp_point cpos; cpos.Set( 0., r_c, 0. ); Htemp = whichTemplate(_var_map->sf.template_rule.mapval(), cpos ); Htv = Htemp->getVarMap(); } double Hd = Htv->width.val; //Heliostat diameter //double Hrad = Hd/2.; //----Add heliostats to this row---- //Should this row reset the spacing? int hpr=-1; //heliostats per row are calculated after slip planes if( is_slip ){ //daz_init = Azimuthal straight-line distance daz_init = Hd*max(1.,_var_map->sf.az_spacing.val); //Normal spacing az_ang = 2.*asin(daz_init*.5/r_c); //The angular spacing of the heliostats in the row //How many heliostats are in this row? hpr = int(floor(fmin((_var_map->sf.accept_max.val - _var_map->sf.accept_min.val), 2.*PI)/az_ang)); //-----calculate the position of each heliostat in the row.----- //Go min to max around the arc. //Every other row, a heliostat should be at the bisection angle of the acceptance window. //In the alternate rows, two heliostats will be evenly centered about the bisecting angle. //Calculate the starting minimum azimuth angle azmin = azmid - az_ang*hpr/2.; } if( hpr < 0 ) throw spexception("An algorithmic error occurred during heliostat placement. Please contact support for debugging help."); j=0; while(j<hpr){ //For the heliostats in the row haz = azmin + az_ang*double(j) + az_ang/2.*double(nr%2); //heliostat azimuth angle HelPos.push_back(sp_point()); HelPos.at(Nhelio).x = r_c*sin(haz); HelPos.at(Nhelio).y = r_c*cos(haz); HelPos.at(Nhelio).z = 0.; Nhelio++; j ++; //If we're skipping heliostats, col_factor will increment by 2 } //--- Calculate the position of the next row --- dr_c = sqrt( pow(Hd,2) - pow(r_c*sin(az_ang/2.),2) )/sin(phi_0); //Increment to the next row r_c += dr_c; //Calculate the spacing between the current row and the previous 2 rows that //would result in blocking is_slip = false; if(nr>2){ if(! slips.at(nr-2)){ //If the last row was a slip plane, don't do these calculations double drlim = Hd/sin(phi_0); if( (r_c - rowpos.at(nr-3)) < drlim || dr_c < Hd/2.){ is_slip = true; r_c += -dr_c + max(drlim, Hd); } } } nr++; //Row number, starts at 1 //now with the solved radius, prepare for the next radius phi_0 = atan(_var_map->sf.tht.val/r_c); slips.push_back(is_slip); rowpos.push_back(r_c); } } else if( ( _var_map->sf.rad_spacing_method.mapval() == var_solarfield::RAD_SPACING_METHOD::ELIMINATE_BLOCKING || _var_map->sf.rad_spacing_method.mapval() == var_solarfield::RAD_SPACING_METHOD::NO_BLOCKINGDENSE ) && Htv->is_round.mapval() != var_heliostat::IS_ROUND::ROUND){ //Space to eliminate blocking - rectangular heliostats //***calculate the row positions*** int nr=1; //row counter double r_0 = radmint; double r_c = r_0; //initialize vector<double> rowpos; vector<bool> slips; vector<bool> is_compact; rowpos.push_back(r_0); //add the first row slips.push_back(true); //Calculate the minimum row separation distance, depends on default azimuthal spacing //..The azimuthal separation factor - the ratio of the actual separation azimuthally to the collision radius double H2 = Htv->height.val/2.; //Heliostat half-height //calculate pointing angle for the first row double phi_0 = atan(_var_map->sf.tht.val/r_0); //elevation angle of the heliostats in the first row double r_reset = r_c; //Hold on to the radius where the spacing has reset sp_point hloc; while(r_c < radmaxt){ //get the new template hloc.Set(r_0,0.,0.); //Radial position (y-component doesn't matter with this layout in terms of the template to use) Htemp = whichTemplate(_var_map->sf.template_rule.mapval(), hloc ); Htv = Htemp->getVarMap(); H2 = Htv->height.val/2.; //Heliostat half-height double W2 = Htv->width.val/2.; //heliostat half-width double r_coll = Htemp->getCollisionRadius(); double fr = H2*2.*_var_map->sf.az_spacing.val/r_coll; //double dr_min = 2.*sqrt( pow(2.*r_coll, 2) - pow(r_coll * fr/2.,2) ); double dr_min = 2. * sqrt( 4 * r_coll * r_coll - pow(_var_map->sf.az_spacing.val*W2, 2) ); //from pointing angle, calculate other needed info { double z_0u = cos(phi_0)*H2; //height of the upper heliostat edge double r_0u = r_0 + sin(phi_0)*H2; //Radial position of the upper heliostat edge //Calculate the next row position based on similar triangles between tower and upper/lower corners of adjacent heliostats. r_c = r_0u * (_var_map->sf.tht.val + z_0u) / (_var_map->sf.tht.val - z_0u) + sin(phi_0)*H2; } //Is this row in the inner compact region? bool row_compact = r_c - r_0 < 2.* r_coll *_var_map->sf.trans_limit_fact.val; if( _var_map->sf.rad_spacing_method.mapval() != var_solarfield::RAD_SPACING_METHOD::NO_BLOCKINGDENSE) row_compact = false; //only allow compact layout if requested //Has the row compact flag just changed? bool row_compact_switch = false; //retroactively handle the first row if( is_compact.empty() ){ if( row_compact ) { //The next row is compact, therefore the first must also be is_compact.push_back( true ); } else{ is_compact.push_back( false ); } } else{ if( is_compact.back() && !row_compact ) row_compact_switch = true; } //Increment to the next row, but make sure there's enough room to avoid collision r_c = r_0 + max(r_c - r_0, dr_min); bool is_slip = (r_c+r_0)/2./r_reset > _var_map->sf.spacing_reset.val || row_compact_switch; //check whether the next row is outside the max bounds if(r_c > radmaxt) break; //manage the next two rows. Call the template check for each subsequent row to ensure //the correct template is used for each position. sp_point hpos; hpos.Set( (r_c + r_0)/2., 0., 0. ); Heliostat *Htemp_r1 = whichTemplate( _var_map->sf.template_rule.mapval(), hpos ); hpos.Set( r_c, 0., 0. ); Heliostat *Htemp_r2 = whichTemplate( _var_map->sf.template_rule.mapval(), hpos ); //first handle the case where the intermediate row uses a different template if( Htemp != Htemp_r1 ) { //the intermediate row causes a template switch. min spacing enforced nr++; H2 = Htemp_r1->getVarMap()->height.val/2.; //Heliostat half-height //update the calculations r_coll = Htemp_r1->getCollisionRadius(); fr = H2*2.*_var_map->sf.az_spacing.val/r_coll; dr_min = sqrt( pow(2.*r_coll, 2) - pow(r_coll * fr/2.,2) ); //update calculation //r_c = r_0 + max( (r_c - r_0)/2., dr_min ); r_c = r_0 + max( (r_c - r_0)/2., r_coll * 2. ); rowpos.push_back( r_c ); slips.push_back( true ); is_compact.push_back( false ); //not sure how else to handle this scenario r_reset = r_c; } //next handle the case where the "current" row uses a different template, but the intermediate row does not else if( Htemp != Htemp_r2 ) { //the current row causes a template switch. nr++; //next row double r_half = (r_c+r_0)/2.; rowpos.push_back(r_half); //In radial stagger, there's a shifted row halfway between each aligned row slips.push_back(false); //regular spacing on current row, but maintain at least the collision radius r_c = max( r_c, r_half + Htemp_r2->getCollisionRadius() ); rowpos.push_back(r_c); slips.push_back(true); is_compact.push_back( false ); //not sure how else to handle this scenario r_reset = r_c; } //Is this an inner compact row? else if( row_compact ) { nr++; r_c = r_0 + r_coll * 2.; rowpos.push_back( r_c ); slips.push_back(true); is_compact.push_back( true ); r_reset = r_c; } //Check to see if we have a slip plane at the interediate row else if( is_slip ) //The intermediate row incurs a slip plane { if(! row_compact_switch){ if( !_var_map->sf.is_sliprow_skipped.val ) { nr++; //make sure the next 2 rows are at least the collision radius away r_c = max(r_0 + 4.*r_coll, r_c); //Make the row as close as possible and remove shadowed/blocked heliostats. //Multiply by the _slip_offset factor specified by the user rowpos.push_back((r_c+r_0)/2.); slips.push_back(true); is_compact.push_back(false); } else { r_c = r_0 + (r_c - r_0)*(1.-_var_map->sf.slip_plane_blocking.val/2.); r_c = max(r_0 + 2.*r_coll, r_c); } } else { r_c = max(r_0 + 2.*r_coll, r_c ); } nr++; rowpos.push_back(r_c); slips.push_back(false || row_compact_switch || _var_map->sf.is_sliprow_skipped.val ); is_compact.push_back(false); r_reset = r_c; } //The intermediate row isn't a slip plane, so add the intermediate row and then check the current row else{ //add intermediate row nr++; rowpos.push_back((r_c+r_0)/2.); //In radial stagger, there's a shifted row halfway between each aligned row slips.push_back(false); is_compact.push_back(false); //determine whether current row is a slip plane if( r_c/r_reset > _var_map->sf.spacing_reset.val){ //Does the next inline row incurs a slip plane? nr++; if( ! _var_map->sf.is_sliprow_skipped.val ) { //Put this row as close as possible to the intermediate row. include _slip_offset factor r_c = max(rowpos.back() + 2.*r_coll, r_c ); } else { //from pointing angle, calculate other needed info phi_0 = atan(_var_map->sf.tht.val/rowpos.back()); double z_0u = cos(phi_0)*H2*(1.-_var_map->sf.slip_plane_blocking.val); //height of the upper heliostat edge double r_0u = rowpos.back() + sin(phi_0)*H2; //Radial position of the upper heliostat edge //Calculate the next row position based on similar triangles between tower and upper/lower corners of adjacent heliostats. r_c = r_0u * (_var_map->sf.tht.val + z_0u) / (_var_map->sf.tht.val - z_0u) + sin(phi_0)*H2; r_c = max(rowpos.back() + 2.*r_coll, r_c); } rowpos.push_back( r_c ); slips.push_back(true); r_reset = r_c; } else{ //current row is not a slip plane, just add as-is nr++; rowpos.push_back( r_c ); slips.push_back(false); } is_compact.push_back(false); } //now with the solved radius, prepare for the next radius phi_0 = atan(_var_map->sf.tht.val/r_c); r_0 = r_c; } //----Now add heliostats to each row---- double daz_init; //The initial physical spacing between heliostats azimuthally double az_ang, azmin, azmid, haz; int Nhelio = 0, hpr = -1; //initialize the heliostat template again { sp_point hpos; hpos.Set(0., rowpos.front(), 0. ); Htemp = whichTemplate( _var_map->sf.template_rule.mapval(), hpos ); Htv = Htemp->getVarMap(); } double hw = Htv->width.val; double r_coll = Htemp->getCollisionRadius(); r_reset = .001; //rowpos.at(0); //Hold on to the radius where the spacing has reset azmid = (_var_map->sf.accept_max.val + _var_map->sf.accept_min.val)/2.; //[rad] The midpoint of the acceptance window for(i=0; i<nr; i++){ //For each row double r_row = rowpos.at(i); //Figure out which template to use if( slips.at(i) ) { //update template-dependent values hloc.Set(r_row,0.,0.); Htemp = whichTemplate(_var_map->sf.template_rule.mapval(), hloc); Htv = Htemp->getVarMap(); hw = Htv->width.val; //The heliostat width r_coll = Htemp->getCollisionRadius(); } if( is_compact.at(i) ){ daz_init = r_coll * 2.; //Compact rows have minimum spacing } else{ daz_init = max(r_coll*2, hw*_var_map->sf.az_spacing.val); //Azimuthal straight-line distance } //Should this row reset the spacing? It will reset if beyond the spacing ratio limit or a new heliostat width is used if( slips.at(i) ){ az_ang = 2.*atan2(daz_init, 2.*r_row); //The angular spacing of the heliostats in the row //How many heliostats are in this row? hpr = int(floor(fmin((_var_map->sf.accept_max.val - _var_map->sf.accept_min.val), 2.*PI)/az_ang)); //-----calculate the position of each heliostat in the row.----- //Go min to max around the arc. //Every other row, a heliostat should be at the bisection angle of the acceptance window. //In the alternate rows, two heliostats will be evenly centered about the bisecting angle. //Calculate the starting minimum azimuth angle azmin = azmid - az_ang*hpr/2.; } for(j=0; j<hpr; j++){ //For the heliostats in the row haz = azmin + az_ang*double(j) + az_ang/2.*double(i%2); //heliostat azimuth angle HelPos.push_back(sp_point()); HelPos.at(Nhelio).x = r_row*sin(haz); HelPos.at(Nhelio).y = r_row*cos(haz); HelPos.at(Nhelio).z = 0.; Nhelio++; } } } return; } void SolarField::cornfieldPositions(vector<sp_point> &HelPos){ /* Lay out the possible heliostat positions (HelPos) for heliostats arranged in a cornfield arrangement. In this configuration, the heliostats are positioned in straight rows, with the positioning staggered between rows. Information for this layout is contained in the following variables: _row_spacing_x //Separation between adjacent heliostats in the X-direction, multiplies heliostat radius _row_spacing_y //Separation between adjacent heliostats in the Y-direction, multiplies heliostat radius _xy_field_shape //Enforced shape of the heliostat field _xy_rect_aspect //Aspect ratio of the rectangular field layout (height in Y / width in X) */ //get the field limits from the land class double rad[2]; _land.getExtents(*_var_map, rad); double radmint = rad[0], radmaxt = rad[1]; //Calculate an upper estimate of the size of the heliostat positions array to avoid resizing all the time double r_coll_temp = 0, r_coll_min = 9.e9; for(htemp_map::iterator it=_helio_templates.begin(); it != _helio_templates.end(); it++){ r_coll_temp = it->second->getCollisionRadius(); if(r_coll_temp < r_coll_min) r_coll_min = r_coll_temp; //minimum collision radius in any combination } //Estimate the total number of heliostats to reserve in the HelPos array int N_max, nxmax, nymax; double Lx=0., Ly=0.; double ry = 2.*r_coll_temp * _var_map->sf.row_spacing_y.val, rx = 2.*r_coll_temp * _var_map->sf.row_spacing_x.val; switch(_var_map->sf.xy_field_shape.mapval()) { //case 0: //Hexagon case var_solarfield::XY_FIELD_SHAPE::HEXAGON: /* The maximum hexagon diameter is governed by the maximum radial value. nx_bar = (radmax*sin(30)+radmax)/2*2 --> nx_bar = radmax * 1.5 * rx ny = 2*radmax*cos(PI/6)/ry */ N_max = (int)ceil(pow(radmaxt-radmint, 2)*3.*cos(PI/6.)/(rx*ry)); break; //case 1: //Rectangle //case 2: //Circular case var_solarfield::XY_FIELD_SHAPE::RECTANGLE: case var_solarfield::XY_FIELD_SHAPE::UNDEFINED: { /* alpha = _xy_rect_aspect theta = atan(alpha) Lx = 2*sin(theta)*radmax Ly = alpha*Lx nx = Lx/rx ny = Ly/ry */ double hyp = sqrt( 1. + _var_map->sf.xy_rect_aspect.val*_var_map->sf.xy_rect_aspect.val ); //Lx = 2.*sin(atan(1./_xy_rect_aspect))*radmaxt; Lx = 2.*radmaxt/hyp; Ly = _var_map->sf.xy_rect_aspect.val*Lx; nxmax = (int)ceil(Lx/rx); nymax = (int)ceil(Ly/ry); if(_var_map->sf.xy_field_shape.mapval() == var_solarfield::XY_FIELD_SHAPE::RECTANGLE){ //rectangle N_max = nxmax*nymax; } else{ //circular N_max = (int)ceil(PI * nxmax * nymax); } break; } default: _sim_error.addSimulationError("The specified field shape model does not exist",true); return; } //-- now we know the maximum number of heliostats possible in the field HelPos.reserve(N_max); /* ----------------- Calculate the positions ----------------*/ double y_loc, //Current row position in Y x_offset, //Stagger offset in X x_max, //maximum position in X //x_min, //minimum x position for the current row x_loc, //current x position y_max, hex_factor; //Constant factor used to calculate x_max in hex's int //ind_y, //Current row index in Y Nhelio; //Number of heliostats, total //Initialize values x_offset = 999.; //initialize to nonzero to force into 0 offset on first pass y_loc = 0.; hex_factor = 0.57735026919; //1./tan(PI/3.); Nhelio = 0; var_solarfield::XY_FIELD_SHAPE::EN shape = static_cast<var_solarfield::XY_FIELD_SHAPE::EN>(_var_map->sf.xy_field_shape.mapval()); assert (shape >= 0 && shape <= var_solarfield::XY_FIELD_SHAPE::UNDEFINED); switch (shape) { case var_solarfield::XY_FIELD_SHAPE::HEXAGON: //case 0: //hex y_max = cos(PI/6.)*radmaxt; break; case var_solarfield::XY_FIELD_SHAPE::RECTANGLE: //case 1: //rectangle y_max = Ly/2.; break; case var_solarfield::XY_FIELD_SHAPE::UNDEFINED: //case 2: //circular y_max = radmaxt; break; } //loop through Y while(y_loc <= y_max) { //Set the x offset if(x_offset > 0.){ x_offset = 0.; } else{ x_offset = rx/2.; } //Calculate the maximum x position var_solarfield::XY_FIELD_SHAPE::EN shape = static_cast<var_solarfield::XY_FIELD_SHAPE::EN>(_var_map->sf.xy_field_shape.mapval()); assert (shape >= 0 && shape <= var_solarfield::XY_FIELD_SHAPE::UNDEFINED); switch (shape) { case var_solarfield::XY_FIELD_SHAPE::HEXAGON: //case 0: //hex x_max = radmaxt - hex_factor*y_loc; break; case var_solarfield::XY_FIELD_SHAPE::RECTANGLE: //case 1: //rect x_max = Lx/2.; break; case var_solarfield::XY_FIELD_SHAPE::UNDEFINED: //case 2: //circular x_max = sqrt( pow(radmaxt, 2) - pow(y_loc, 2) ); break; } //loop through each X position x_loc = x_offset; while(x_loc <= x_max){ //check if the x location is within the exclusion area if( sqrt(pow(x_loc, 2) + pow(y_loc, 2)) >= radmint ){ //Add the heliostat position HelPos.push_back(sp_point()); HelPos.at(Nhelio++).Set(x_loc, y_loc, 0.); //Add the -y complement if(y_loc>0.){ HelPos.push_back(sp_point()); HelPos.at(Nhelio++).Set(x_loc, -y_loc, 0.); } //Add the x complement if(x_loc > 0.){ HelPos.push_back(sp_point()); HelPos.at(Nhelio++).Set(-x_loc, y_loc, 0.); if(y_loc>0.){ HelPos.push_back(sp_point()); HelPos.at(Nhelio++).Set(-x_loc, -y_loc, 0.); } } } //increment row X position x_loc += rx; } //increment row Y position y_loc += ry; } } void SolarField::RefactorHeliostatImages(Vect &Sun){ /* This method: 1. Recalculates the analytical image properties for each heliostat in the field. 2. Should only be called after the static Hermite terms have been initialized. 3. Is a truncated form of the Simulate() call, using only the image intercept method. 4. Does not set any efficiency properties of the simulated heliostats. 5. Requires that the tracking vectors be previously updated. Call this method when an existing field geometry is simulated at a different solar position or when aim points are updated. */ int nh = (int)_heliostats.size(); for(int i=0; i<nh; i++){ _flux->imagePlaneIntercept(*_var_map, *_heliostats.at(i), _heliostats.at(i)->getWhichReceiver(), &Sun); } } bool SolarField::SimulateTime(int /*hour*/, int day_of_month, int month, sim_params &P){ /* Simulate a particular date/time for the current solar field geometry. hour | Hour of the day [0,23) day_of_month | Day of the month [1,31] month | Month of the year [1,12] args[0] | DNI [W/m2] args[1] | Ambient temperature [C] args[2] | Atmospheric pressure [atm] args[3] | Wind velocity [m/s] */ //update DateTime structure with necessary info DateTime DT; DT.SetDate(2011, month, day_of_month); //also updates day of year //Calculate the sun position double az, zen; Ambient::calcSunPosition(*_var_map, DT, &az, &zen); //If the sun is not above the horizon plus a very small amount (to avoid infinite shadows), don't continue if( zen > 88 ) return false; //Simulate field performance //args[4] Should contain {dni [W/m2], tdb [C], wind [m/s], pres [mbar], weighting factor [-]}; Simulate(az, zen, P); return true; } void SolarField::Simulate(double azimuth, double zenith, sim_params &P) { /* azimuth [rad] zenith [rad] For a given heliostat field and tower/receiver geometry, simulate the performance of the field. Add the efficiency attributes to each heliostat. The method requires that: * The payment or weighting factors have been set * Solar field geometry has been defined The procedure is: 1. Calculate sun vector 2. Update receiver stuff 3. Update tracking vectors 4. Refactor heliostat images 5. Calculate final aim points 6. Calculate heliostat performance */ //calculate sun vector Vect Sun = Ambient::calcSunVectorFromAzZen(azimuth, zenith); for(int i=0; i<(int)_receivers.size(); i++) { //Update the estimated receiver thermal efficiency for each receiver _receivers.at(i)->CalculateThermalEfficiency(P.dni, _var_map->sf.dni_des.val, P.Vwind, _var_map->sf.q_des.val); //reset receiver calculated values //reset the flux grids on all receivers for(int j=0; j<(int)_receivers.at(i)->getFluxSurfaces()->size(); j++) { FluxSurface *fs = &_receivers.at(i)->getFluxSurfaces()->at(j); fs->ClearFluxGrid(); fs->setMaxObservedFlux(0.); } } setSimulatedPowerToReceiver(0.); //reset the simulated power to the receiver //tracking bool psave = P.is_layout; P.is_layout = true; //override for simple right now calcAllAimPoints(Sun, P); //true, true); //update with simple aim points first to get consistent tracking vectors updateAllTrackVectors(Sun); //Calculate aim points P.is_layout = psave; calcAllAimPoints(Sun, P); //.is_layout, P.is_layout); // , simple? , quiet? //Update the heliostat neighbors to include possible shadowers UpdateNeighborList(_helio_extents, P.is_layout ? 0. : zenith); //don't include shadowing effects in layout (zenith = 0.) //For each heliostat, assess the losses //for layout calculations, we can speed things up by only calculating the intercept factor for representative heliostats. (similar to DELSOL). int nh = (int)_heliostats.size(); if(P.is_layout && _var_map->sf.is_opt_zoning.val){ //The intercept factor is the most time consuming calculation. Simulate just a single heliostat in the //neighboring group and apply it to all the rest. for(int i=0; i<(int)_layout_groups.size(); i++){ Hvector *hg = &_layout_groups.at(i); int ngroup = (int)hg->size(); if(ngroup == 0) continue; Heliostat *helios = hg->front(); // just use the first one double eta_int = _flux->imagePlaneIntercept(*_var_map, *helios, helios->getWhichReceiver(), &Sun); if( eta_int > 1.) eta_int = 1.; helios->setEfficiencyIntercept( fmin(eta_int, 1.) ); for(int k=1; k<ngroup; k++){ hg->at(k)->setEfficiencyIntercept( eta_int ); hg->at(k)->CopyImageData( helios ); } } } //Simulate efficiency for all heliostats for(int i=0; i<nh; i++) SimulateHeliostatEfficiency(this, Sun, _heliostats.at(i), P); } void SolarField::SimulateHeliostatEfficiency(SolarField *SF, Vect &Sun, Heliostat *helios, sim_params &P) { /* Simulate the heliostats in the specified range */ //if a heliostat has been disabled, handle here and return if( ! helios->IsEnabled() ) { helios->setEfficiencyCosine( 0. ); helios->setEfficiencyAtmAtten( 0. ); helios->setEfficiencyIntercept( 0. ); helios->setEfficiencyShading( 0. ); helios->setEfficiencyBlocking( 0. ); helios->setPowerToReceiver( 0. ); helios->setPowerValue( 0. ); helios->calcTotalEfficiency(); return; } //Cosine loss helios->setEfficiencyCosine( Toolbox::dotprod(Sun, *helios->getTrackVector()) ); var_map *V = SF->getVarMap(); //Attenuation loss double slant = helios->getSlantRange(), att = Ambient::calcAttenuation(*V, slant ); helios->setEfficiencyAtmAtten( att ); Receiver *Rec = helios->getWhichReceiver(); //Intercept if(! (P.is_layout && V->sf.is_opt_zoning.val) ){ //For layout simulations, the simulation method that calls this method handles image intercept double eta_int = SF->getFluxObject()->imagePlaneIntercept(*V, *helios, Rec, &Sun); if(eta_int != eta_int) throw spexception("An error occurred when calculating heliostat intercept factor. Please contact support for help resolving this issue."); if(eta_int>1.) eta_int = 1.; helios->setEfficiencyIntercept(eta_int); } //Shadowing and blocking double shad_tot = 1., block_tot = 1.; double interaction_limit = V->sf.interaction_limit.val; Hvector *neibs = helios->getNeighborList(); int nn = (int)neibs->size(); for(int j=0; j<nn; j++){ if(helios == neibs->at(j) ) continue; //Don't calculate blocking or shading for the same heliostat if(!P.is_layout) shad_tot += -SF->calcShadowBlock(helios, neibs->at(j), 0, Sun, interaction_limit); //Don't calculate shadowing for layout simulations. Cascaded shadowing effects can skew the layout. block_tot += -SF->calcShadowBlock(helios, neibs->at(j), 1, Sun, interaction_limit); } if(shad_tot < 0.) shad_tot = 0.; if(shad_tot > 1.) shad_tot = 1.; helios->setEfficiencyShading(shad_tot); if(block_tot < 0.) block_tot = 0.; if(block_tot > 1.) block_tot = 1.; helios->setEfficiencyBlocking(block_tot); //Soiling, reflectivity, and receiver absorptance factors are included in the total calculation double eta_rec_abs = Rec->getVarMap()->absorptance.val; // * eta_rec_acc, double eta_total = helios->calcTotalEfficiency(); double power = eta_total * P.dni * helios->getArea() * eta_rec_abs; helios->setPowerToReceiver( power ); helios->setPowerValue( power * P.Simweight*P.TOUweight * Rec->getThermalEfficiency() ); return; } double SolarField::calcShadowBlock(Heliostat *H, Heliostat *HI, int mode, Vect &Sun, double interaction_limit) { /* This method takes two heliostats and calculates the interfering or blocking of heliostat "H" by neighbor "HI". interfering is calculated in mode = 0 Blocking is calculated in mode = 1 The method assumes that the neighboring heliostats have approximately the same orientation with respect to the sun (i.e. approximately the same tracking vector). This simplifies the calculation. The method returns a double value equal to the fraction lost to interference. */ #if 0 if(HI->IsRound()){ //Remove this for now // Round heliostats /* The formula for the area of intersection of 2 circles of equal radius is: A = 2 R^2 acos[ d/(2R) ] - 1/2 d sqrt(4 R^2 - d^2) where: R = radius of the circle d = distance separating the centroid of the circles The shadowing efficiency is equal to (1 - A_intersect/A_heliostat) */ sp_point *HIloc, *Hloc; //Check to see if the two heliostats are far enough apart that there is no possibility //of interfering. This criteria will depend on the solar angle Vect *H_inter; if(mode == 0){ //Get the sun vector as the interference direction H_inter = &Sun; } else{ //Get the tower/receiver vector as the interference direction H_inter = H->getTowerVector(); } double zen = acos(H_inter->k); //The zenith angle for interference //Get the interfering heliostat tracking angles Vect *HIt = HI->getTrackVector(), //Interfering heliostat track vector *Ht = H->getTrackVector(); //Base heliostat track vector //Is the heliostat in a position to shadow/block? double Hd = HI->getVarMap()->width.val; //Diameter //Get locations HIloc = HI->getLocation(); Hloc = H->getLocation(); //Create a vector pointing from the heliostat to the interfering neighbor Vect Hnn; Hnn.Set(HIloc->x - Hloc->x, HIloc->y - Hloc->y, HIloc->z - Hloc->z); //If the heliostat is not in front of the other with respect to the solar position, it also can't shadow if( Toolbox::dotprod(Hnn, *H_inter) < 0.) return 0.; //Find the collision point of the centroid of the shadow sp_point hit; if( Toolbox::plane_intersect(*Hloc, *Ht, *HIloc, *H_inter, hit) ) { //Calculate the distance separating the hit and the heliostat centroid Vect vsep; vsep.Set( Hloc->x - hit.x, Hloc->y - hit.y, Hloc->z - hit.z ); double r_sep = Toolbox::vectmag( vsep ); if(r_sep < Hd){ //Calculate the shadow overlap area double Ax = 2.*pow(Hd/2.,2)*acos(r_sep/Hd) - .5*r_sep*sqrt(pow(Hd,2) - pow(r_sep,2)); return Ax/(PI*.25*pow(Hd,2)); } } return 0.; } else #endif { // rectangular heliostats sp_point *HIloc, *Hloc; //Check to see if the two heliostats are far enough apart that there is no possibility //of interfering. This criteria will depend on the solar angle Vect *H_inter; if(mode == 0){ //Get the sun vector as the interference direction H_inter = &Sun; } else{ //Get the tower/receiver vector as the interference direction H_inter = H->getTowerVector(); } //double zen = acos(H_inter->k); //The zenith angle for interference //Get the interfering heliostat tracking angles Vect *HIt = HI->getTrackVector(), //Interfering heliostat track vector *Ht = H->getTrackVector(); //Base heliostat track vector double HIh = HI->getVarMap()->height.val; //Interfering heliostat tracking zenith double HIzen = acos(HIt->k); //zenith angle //double HIaz = atan2(HIt->i,HIt->j); //azimuth angle /* The maximum possible extent between heliostats where interference is a possibility.. Equals the distance in height between the top edge of the interfering heliostat and the bottom edge of the blocked/shadowed heliostat, plus any elevation difference between the heliostats, plus the horizontal distance from tilting the heliostats. */ HIloc = HI->getLocation(); Hloc = H->getLocation(); //double l_max = (HIloc->z - Hloc->z + HIh*sin(HIzen))/tan(PI/2.-zen) + HIh*cos(HIzen); double tanpi2zen = H_inter->k/sqrt(H_inter->i*H_inter->i + H_inter->j*H_inter->j); double l_max = (HIloc->z - Hloc->z + HIh*sin(HIzen))/tanpi2zen + HIh*HIt->k; l_max = fmin(l_max, interaction_limit*HIh); //limit to a reasonable number //Create a vector pointing from the heliostat to the interfering neighbor Vect Hnn; Hnn.Set(HIloc->x - Hloc->x, HIloc->y - Hloc->y, HIloc->z - Hloc->z); //How close are the heliostats? double hdist = sqrt(Hnn.i*Hnn.i + Hnn.j*Hnn.j + Hnn.k*Hnn.k); if(hdist > l_max) return 0.; //No possibility of interfering, return here. //Check for collision radius double Hh = H->getVarMap()->height.val, //Shaded heliostat height Hw = H->getVarMap()->width.val; //Shaded heliostat width //double Hr = sqrt(pow(Hh/2.,2) + pow(Hw/2.,2)); //If the heliostat is not in front of the other with respect to the solar position, it also can't shadow if( Toolbox::dotprod(Hnn, *H_inter) < 0.) return 0.; //-----------test vector<sp_point> *cobj = HI->getCornerCoords(), ints(2); //intersection points vector<bool> hits(2, false); //track whether either point hit int i; for(i=0; i<2; i++){ if( Toolbox::plane_intersect(*Hloc, *Ht, cobj->at(i), *H_inter, ints.at(i)) ){ //An intercept on the plane was detected. Is the intercept within the heliostat area? hits.at(i) = Toolbox::pointInPolygon(*H->getCornerCoords(), ints.at(i) ); } } //Do either of the corners shadow/block the heliostat? if(hits.at(0) || hits.at(1)){ //interfering detected. double dx_inter, dy_inter; /* To calculate the fraction of energy lost, we first transform the intersection point into heliostat coordinates so that it's easier to find how the shadow is cast on the heliostat. */ vector<sp_point> ints_trans(2); //Copy of the intersection points for heliostat coordinate transform for(i=0; i<2; i++){ //Express each point of HI in global coords relative to the centroid of H //i.e. (ints_trans.x - H->x, ... ) ints_trans.at(i).Set(ints.at(i).x - Hloc->x, ints.at(i).y - Hloc->y, ints.at(i).z - Hloc->z); //First rotate azimuthally back to the north position Toolbox::rotation(-H->getAzimuthTrack(), 2, ints_trans.at(i)); //Next rotate in zenith to get it into heliostat coords. The z component should be very small or zero. //Y components should be relatively close for rectangular heliostats Toolbox::rotation(-H->getZenithTrack(), 0, ints_trans.at(i)); } //Based on how the image appears, determine interfering. //Recall that after transformation, the positive y edge corresponds to the bottom of the heliostat. int which_is_off, which_is_on; if(hits.at(0) && hits.at(1)) { //Both corners are active in interfering (i.e. the shadow image is contained within the shadowed heliostat dy_inter = ( Hh - (ints_trans.at(0).y + ints_trans.at(1).y) ) / (2. * Hh); //Use the average z position of both points dx_inter = fabs(ints_trans.at(0).x - ints_trans.at(1).x ) / Hw; return dy_inter * dx_inter; } else if(hits.at(0)) { //Only the first corner appears in the shadow/blocking image which_is_off = 1; which_is_on = 0; } else { //Only the second corner appears in the shadow/blocking image which_is_off = 0; which_is_on = 1; } dy_inter = (Hh/2. - ints_trans.at(which_is_on).y) / Hh; //The z-interfering component if( ints_trans.at(which_is_off).x > Hw/2. ){ // The shadow image spills off the +x side of the heliostat dx_inter = .5 - ints_trans.at(which_is_on).x / Hw; } else { //The shadow image spills off the -x side of the heliostat dx_inter = ints_trans.at(which_is_on).x / Hw + .5; } return dy_inter * dx_inter; } else{ //No interfering return 0.; } } } double *SolarField::getPlotBounds(bool /*use_land*/){ /* Returns the field bound extents for plotting based on the field layout "use_land" indicates whether the extents should factor in all available land */ //if(use_land){} //else{ //Return the array (size = 4) of heliostat position boundaries [xmax,xmin,ymax,ymin] return _helio_extents; //} } void SolarField::updateAllTrackVectors(Vect &Sun){ //update all tracking vectors according to the current sun position if(_var_map->flux.aim_method.mapval() == var_fluxsim::AIM_METHOD::FREEZE_TRACKING) return; int npos = (int)_heliostats.size(); for(int i=0; i<npos; i++){ _heliostats.at(i)->updateTrackVector(Sun); } } void SolarField::calcHeliostatShadows(Vect &Sun){ //Calculate the heliostat shadows sp_point P; //sp_point on a plane representing the ground Vect Nv; //Vector normal to the ground surface Nv.Set(0., 0., 1.); int npos = (int)_heliostats.size(); //Calculate differently if the heliostats are round #if 0 if(_helio_templates.at(0)->getVarMap()->is_round.mapval() == var_heliostat::IS_ROUND::ROUND) { //This is all wrong Vect hvect_xy, hvect_z, svect_xy, svect_z; double fscale_x, fscale_y; double hdiam = _heliostats.at(0)->getVarMap()->width.val; for(int i=0; i<npos; i++){ P.Set(0.,0., -hdiam/2.*1.1); vector<sp_point> *sc = _heliostats.at(i)->getShadowCoords(); sc->resize(2); /* The shadow coordinates for round heliostats will be: 0 | x,y,z of shadow centroid 1 | <shadow width in x>,<shadow width in y>,0. */ Vect *hvect = _heliostats.at(i)->getTrackVector(); Toolbox::plane_intersect(P, Nv, *_heliostats.at(i)->getLocation(), Sun, sc->at(0) ); //Get relevant vectors hvect_xy.Set(hvect->i, hvect->j, 0.); Toolbox::unitvect(hvect_xy); svect_xy.Set(Sun.i, Sun.j, 0.); Toolbox::unitvect(svect_xy); hvect_z.Set( Toolbox::vectmag(hvect->i, hvect->j, 0.), 0., hvect->k); Toolbox::unitvect(hvect_z); svect_z.Set( Toolbox::vectmag(Sun.i, Sun.j, 0.), 0., Sun.k); Toolbox::unitvect(svect_z); //dot products determine shadow scaling fscale_x = Toolbox::dotprod(hvect_xy, svect_xy); fscale_y = Toolbox::dotprod(svect_z, hvect_z); //Calculate the shadow width and height sc->at(1).Set( fscale_x*hdiam, fscale_y*hdiam, 0 ); } } else #endif { //rectangular heliostats for(int i=0; i<npos; i++){ P.Set(0., 0., -_heliostats.at(i)->getVarMap()->height.val/2.*1.1); _heliostats.at(i)->getShadowCoords()->resize(4); for(int j=0; j<4; j++){ Toolbox::plane_intersect(P, Nv, _heliostats.at(i)->getCornerCoords()->at(j), Sun, _heliostats.at(i)->getShadowCoords()->at(j) ); } } } } void SolarField::calcAllAimPoints(Vect &Sun, sim_params &P) //bool force_simple, bool quiet) { /* Method can be: 0 | Simple aim points | All heliostats point at vertical centerline of their closest receiver point 1 | Sigma aim point | Heliostats spread depending on image size (sigmas =std dev of image in x and y) -> For this method, args[0] = limiting sigma factor. This determines the distance away from the edge in standard deviations of each image. args[1] = alternation flag indicating which receiver edge the offset should reference (+1 or -1) 2 | Probability | 3 | Image SIze | -> args[0] = limiting sigma factor args[1] = limiting sigma factor y args[2] = First image flag 4 | Keep Existing | 5 | Freeze | When calculating the aim points, the heliostat images should be previously updated. Call the flux image updator for methods other than simple aim points. */ int nh = (int)_heliostats.size(); int method = _var_map->flux.aim_method.mapval(); if(P.is_layout && method != var_fluxsim::AIM_METHOD::KEEP_EXISTING) method = var_fluxsim::AIM_METHOD::SIMPLE_AIM_POINTS; //set up args based on the method double args[] = {0., 0., 0., 0.}; switch (method) { //case FluxSimData::AIM_STRATEGY::EXISTING: //case FluxSimData::AIM_STRATEGY::SIMPLE: case var_fluxsim::AIM_METHOD::KEEP_EXISTING: case var_fluxsim::AIM_METHOD::SIMPLE_AIM_POINTS: break; //case FluxSimData::AIM_STRATEGY::SIGMA: case var_fluxsim::AIM_METHOD::SIGMA_AIMING: args[0] = _var_map->flux.sigma_limit_y.val; args[1] = 1.; break; //case FluxSimData::AIM_STRATEGY::PROBABILITY: case var_fluxsim::AIM_METHOD::PROBABILITY_SHIFT: if(_var_map->flux.flux_dist.mapval() == var_fluxsim::FLUX_DIST::NORMAL){ //Normal dist, get the standard dev of the sampling distribution args[2] = _var_map->flux.norm_dist_sigma.val; } args[0] = _var_map->flux.sigma_limit_y.val; args[1] = _var_map->flux.flux_dist.mapval(); //the distribution type break; //case FluxSimData::AIM_STRATEGY::IMAGE_SIZE: case var_fluxsim::AIM_METHOD::IMAGE_SIZE_PRIORITY: args[0] = _var_map->flux.sigma_limit_y.val; args[1] = _var_map->flux.sigma_limit_x.val; break; //case FluxSimData::AIM_STRATEGY::FREEZE: case var_fluxsim::AIM_METHOD::FREEZE_TRACKING: args[0] = Sun.i; args[1] = Sun.j; args[2] = Sun.k; break; default: break; } //for methods that require sorted heliostats, create the sorted data Hvector hsort; vector<double> ysize; int imsize_last_enabled=0; if(method == var_fluxsim::AIM_METHOD::IMAGE_SIZE_PRIORITY) { //update images //RefactorHeliostatImages(Sun); //Create a list of heliostats sorted by their Y image size int nh = (int)_heliostats.size(); for(int i=0; i<nh; i++) { //update heliostat efficiency and optical coefficients SimulateHeliostatEfficiency(this, Sun, _heliostats.at(i), P); hsort.push_back(_heliostats.at(i)); ysize.push_back(_heliostats.at(i)->getImageSize()[1]); } quicksort(ysize,hsort,0,nh-1); //Sorts in ascending order //find the first enabled heliostat. This will be the last one called. for(size_t i=0; i<hsort.size(); i++) { if( hsort.at(i)->IsEnabled() ) { imsize_last_enabled=nh - 1 - (int)i; break; } } } //-- if(! P.is_layout) { _sim_info.Reset(); _sim_info.setTotalSimulationCount(nh); } int update_every = method == var_fluxsim::AIM_METHOD::IMAGE_SIZE_PRIORITY ? max(nh/20,1) : nh+1; for(int i=0; i<nh; i++){ int usemethod = method; //hande image size priority separately from the main switch structure if( method == var_fluxsim::AIM_METHOD::IMAGE_SIZE_PRIORITY ) { try{ if( hsort.at(nh-i-1)->IsEnabled() ) //is it enabled? { args[2] = i == 0 ? 1. : 0.; _flux->imageSizeAimPoint(*hsort.at(nh-i-1), *this, args, i==imsize_last_enabled); //Send in descending order } else { _flux->zenithAimPoint(*hsort.at(nh-i-1), Sun); usemethod = -1; } } catch(...){ return; } } else { //handle all other methods' disabled status here if( ! _heliostats.at(i)->IsEnabled() ) { //this heliostat is disabled. The aimpoint should point the heliostat to zenith _flux->zenithAimPoint(*_heliostats.at(i), Sun); usemethod = -1; } } switch(usemethod) { case var_fluxsim::AIM_METHOD::SIMPLE_AIM_POINTS: //Determine the simple aim point - doesn't account for flux limitations _flux->simpleAimPoint(*_heliostats.at(i), *this); break; case var_fluxsim::AIM_METHOD::SIGMA_AIMING: args[1] = -args[1]; _flux->sigmaAimPoint(*_heliostats.at(i), *this, args); break; case var_fluxsim::AIM_METHOD::PROBABILITY_SHIFT: _flux->probabilityShiftAimPoint(*_heliostats.at(i), *this, args); break; case var_fluxsim::AIM_METHOD::KEEP_EXISTING: //Keep existing aim point, but we still need to update the image plane flux point (geometry may have changed) { _flux->keepExistingAimPoint(*_heliostats.at(i), *this, 0); break; } case var_fluxsim::AIM_METHOD::FREEZE_TRACKING: //update the aim point based on the movement of the sun and the resulting shift in the reflected image _flux->frozenAimPoint(*_heliostats.at(i), _var_map->sf.tht.val, args); break; case -1: default: //nothing break; } //Update the progress bar if(! P.is_layout ) { if(i%update_every==0) { if(! _sim_info.setCurrentSimulation(i+1) ) break; } } } if(! P.is_layout) { _sim_info.Reset(); _sim_info.setCurrentSimulation(0); } setAimpointStatus(true); //all aimpoints should be up to date } int SolarField::getActiveReceiverCount(){ int n=0; for(unsigned int i=0; i<_receivers.size(); i++){ n += _receivers.at(i)->isReceiverEnabled() ? 1 : 0; } return n; } bool SolarField::parseHeliostatXYZFile(const std::string &filedat, layout_shell &layout ){ /* Take the heliostat layout in text form and parse it into a shell for later use. The text lines should be separated by the "\n" newline character, and can be delimited by "," | " " | ";" | "\t" Structure: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 <template (int)> <enabled> <in layout> <location X> <location Y> <location Z> <x focal length> <y focal length> <cant i> <cant j> <cant k> <aim X> <aim Y> <aim Z> */ layout.clear(); //Split by lines vector<string> entries = split(filedat, ";"); //if there's only one entry, we used the wrong delimiter. Try "\n" int nlines = (int)entries.size(); if(nlines < 2){ entries.clear(); entries = split(filedat, "\n"); nlines = (int)entries.size(); } //Resize the heliostat vector layout.reserve(nlines); vector<string> data; int i, j; double loc[3], focal[2], cant[3], aim[3]; //Find the type of delimiter string delim = Toolbox::getDelimiter(entries.at(0)); data.clear(); //try to handle old version bool is_old_version = false; for(i=0; i<nlines; i++){ data = split(entries.at(i), delim); //check for empty lines if( data.size() < 2 ) continue; layout.push_back(layout_obj()); //If the number of entries is less than 14 (but must be at least 6), append NULL's int dsize = (int)data.size(); //if the data length is 12, we're loading from an old file if (i == 0) { if (dsize == 12) is_old_version = true; } if(dsize < 6){ char fmt[] = "Formatting error\nLine %d in the imported layout is incorrectly formatted. The error occurred while parsing the following text:\n\"%s\""; char msg[250]; sprintf(msg, fmt, i+1, entries.at(i).c_str()); throw(spexception(msg)); //error! } else if(dsize < 14){ for(unsigned int k=dsize; k<14; k++){ data.push_back("NULL"); } } int col = 0; // current column //which template should we use? to_integer(data.at(col++), &layout.at(i).helio_type); //assign enabled and layout status if (!is_old_version) { to_bool(data.at(col++), layout.at(i).is_enabled); to_bool(data.at(col++), layout.at(i).is_in_layout); } else { layout.at(i).is_enabled = true; layout.at(i).is_in_layout = true; } //Assign the location for(j=0; j<3; j++) { to_double(data.at(col++), &loc[j]); } layout.at(i).location.Set(loc[0], loc[1], loc[2]); //Assign the focal length if(data.at(col)!="NULL"){ for(j=0; j<2; j++) { to_double(data.at(col++), &focal[j]); } layout.at(i).focal_x = focal[0]; layout.at(i).focal_y = focal[1]; layout.at(i).is_user_focus = true; } else{ layout.at(i).is_user_focus = false; } //Assign the cant vector unless its null if(data.at(col)!="NULL") { for(j=0; j<3; j++) { to_double(data.at(col++), &cant[j]); } layout.at(i).cant.Set(cant[0], cant[1], cant[2]); layout.at(i).is_user_cant = true; } else{ layout.at(i).is_user_cant = false; } //Assign the aim point unless its null if(data.at(col)!="NULL") { for(j=0; j<3; j++) { to_double(data.at(col++), &aim[j]); } layout.at(i).aim.Set(aim[0], aim[1], aim[2]); layout.at(i).is_user_aim = true; } else{ layout.at(i).is_user_aim = false; } } return true; } int SolarField::calcNumRequiredSimulations(){ //Based on the solar field settings, how many simulations are impending? int nsim; int des_sim_detail = _var_map->sf.des_sim_detail.mapval(); if(des_sim_detail == var_solarfield::DES_SIM_DETAIL::DO_NOT_FILTER_HELIOSTATS){ nsim = 1; } else{ if(des_sim_detail == var_solarfield::DES_SIM_DETAIL::SUBSET_OF_DAYSHOURS){ //Subset of days, all sunlight hours in the selected days //Calculate which hours from the days are needed //TODO throw spexception("Subset hours: Method not currently supported"); } //else if(des_sim_detail == var_solarfield::DES_SIM_DETAIL::ANNUAL_SIMULATION){ //nsim = _var_map->amb.weather_file.val.size(); //} else{ nsim = _var_map->sf.sim_step_data.Val().size(); //If other type of simulation, use the data established in the design select method } } return nsim; } double SolarField::getReceiverTotalHeatLoss() { double qloss = 0.; for(int i=0; i<(int)_receivers.size(); i++) { qloss = _receivers.at(i)->getReceiverThermalLoss()*1000.; //kWt } return qloss; } double SolarField::getReceiverPipingHeatLoss() { double qloss = 0.; for(int i=0; i<(int)_receivers.size(); i++) { qloss = _receivers.at(i)->getReceiverPipingLoss()*1000.; //kWt } return qloss; } void SolarField::HermiteFluxSimulation(Hvector &helios, bool keep_existing_profile) { if( ! keep_existing_profile ) AnalyticalFluxSimulation(helios); CalcDimensionalFluxProfiles(helios); } void SolarField::AnalyticalFluxSimulation(Hvector &helios) { //Simulate each receiver flux profile (non-dimensional) int nrec = (int)_receivers.size(); for(int n=0; n<nrec; n++){ if(! _receivers.at(n)->isReceiverEnabled() ) continue; FluxSurfaces *surfaces = _receivers.at(n)->getFluxSurfaces(); for(unsigned int i=0; i<surfaces->size(); i++){ _flux->fluxDensity(&_sim_info, surfaces->at(i), helios, true, true, true); } } } void SolarField::CalcDimensionalFluxProfiles(Hvector &helios) { /* Take the existing non-dimensional flux profiles in the Receivers::getFluxSurfaces() and alter the values to indicate total dimensional power on the receiver surfaces */ //DNI double dni = _var_map->flux.flux_dni.val*0.001; // _var_map->sf.dni_des.val*0.001; //kW/m2 //Determine the total power delivered from the heliostats. This serves as a normalizing basis. double q_to_rec=0.; for(unsigned int i=0; i<helios.size(); i++){ q_to_rec += helios.at(i)->getEfficiencyTotal()*helios.at(i)->getArea()*dni; //[kW] } //Receiver surface area double Arec = calcReceiverTotalArea(); //[m2] //Convert to kW/m2 //double q_rec_spec = q_to_rec / Arec; //Simulate for each receiver int nrec = (int)_receivers.size(); for(int n=0; n<nrec; n++){ if(! _receivers.at(n)->isReceiverEnabled() ) continue; FluxSurfaces *surfaces = _receivers.at(n)->getFluxSurfaces(); for(unsigned int i=0; i<surfaces->size(); i++){ FluxSurface *fs = &surfaces->at(i); //Take the normalized flux values and multiply to get flux density [kW/m2] FluxGrid *grid = fs->getFluxMap(); double fmax=0.; double maxbin=0.; double ftot=0.; double ftot2 = 0.; int nfy = fs->getFluxNY(), nfx = fs->getFluxNX(); double nfynfx = (double)(nfy*nfx); double anode = Arec / nfynfx; for(int j=0; j<nfy; j++){ for(int k=0; k<nfx; k++){ double *pt = &grid->at(k).at(j).flux; ftot += *pt; if(*pt > maxbin) maxbin = *pt; *pt *= q_to_rec / anode; //*pt *= q_rec_spec*nfynfx; ftot2 += *pt; if(*pt > fmax) fmax = *pt; } } fs->setMaxObservedFlux(fmax); } } } void SolarField::copySimulationStepData(WeatherData &wdata){ //the weather data structure contains some pointers that need to be reset. Copy the //data and reset the pointers here int n = (int)_var_map->sf.sim_step_data.Val().size(); wdata.resizeAll(n); double day, hour, month, dni, tdb, pres, vwind, step_weight; for(int i=0; i<n; i++){ _var_map->sf.sim_step_data.Val().getStep( i, day, hour, month, dni, tdb, pres, vwind, step_weight); wdata.setStep(i, day, hour, month, dni, tdb, pres, vwind, step_weight ); } } bool SolarField::CalcDesignPtSunPosition(int sun_loc_des, double &az_des, double &zen_des) { /* Calculate the design-point sun position given a design point specified by the user. sun_loc_des: 0 Summer Solstice (June 21 N, Dec 21 S) 1 Equinox (March 20, = Sept 20) 2 Winter solstice (Dec 21 N, June 21 S) 3 Zenith (180, 90 elev) 4 User specified Sets: az_des [deg] zen_des [deg] Returns: Bool (success) */ int month, day; bool N_hemis = _var_map->amb.latitude.val > 0.; switch (sun_loc_des) { case var_solarfield::SUN_LOC_DES::ZENITH: az_des = 180.; zen_des = 0.; return true; case var_solarfield::SUN_LOC_DES::OTHER: az_des = _var_map->sf.sun_az_des_user.val; zen_des = 90. - _var_map->sf.sun_el_des_user.val; return true; // ^^^^ these methods are done and have returned without calling sun position case var_solarfield::SUN_LOC_DES::SUMMER_SOLSTICE: month = N_hemis ? 6 : 12; day = 21; break; case var_solarfield::SUN_LOC_DES::EQUINOX: month = 3; day = 20; break; case var_solarfield::SUN_LOC_DES::WINTER_SOLSTICE: month = N_hemis ? 12 : 6; day = 21; break; default: _sim_error.addSimulationError("This design-point sun position option is not available", true); return false;; } //call the sun position algorithm here //Convert the day of the month to a day of year DateTime DT; int doy = DT.GetDayOfYear(2011,month,day); Ambient::setDateTime(DT, 12., doy); //Calculate the sun position Ambient::calcSunPosition(*_var_map, DT, &az_des, &zen_des); //If the sun is not above the horizon plus a very small amount, fail return zen_des < 90.; } double SolarField::getAnnualPowerApproximation() { return _estimated_annual_power; } double SolarField::getDesignThermalPowerWithLoss(){ return _q_des_withloss; } double SolarField::getActualThermalPowerWithLoss(){ return _q_to_rec/1.e6; } // --- clouds --- void SolarField::clouds::Create(var_map &V, double extents[2]){ _all_locs.clear(); //just to be safe... //if it's not enabled, we can skip if(! V.flux.is_cloudy.val) return; //Calculate shadow location(s) here int cloud_shape = V.flux.cloud_shape.mapval(); if(V.flux.is_cloud_pattern.val && cloud_shape == var_fluxsim::CLOUD_SHAPE::FRONT) { switch (cloud_shape) { case var_fluxsim::CLOUD_SHAPE::ELLIPTICAL: case var_fluxsim::CLOUD_SHAPE::RECTANGULAR: { //create a point for the initial cloud location sp_point loc = {V.flux.cloud_loc_x.val, V.flux.cloud_loc_y.val, 0.}; //rotate into original coordinates Toolbox::rotation(-V.flux.cloud_skew.val, 2, loc); double rcloud_max = max(V.flux.cloud_depth.val, V.flux.cloud_width.val)/2.; double dx = V.flux.cloud_width.val * V.flux.cloud_sep_width.val; double dy = V.flux.cloud_depth.val * V.flux.cloud_sep_depth.val; double rfmax = extents[1], xp = rfmax - loc.x + rcloud_max + dx/2., xm = V.flux.is_cloud_symw.val ? rfmax + loc.x + rcloud_max : 0., yp = rfmax - loc.y + rcloud_max, ym = V.flux.is_cloud_symd.val ? rfmax + loc.y + rcloud_max : 0.; //add primary point //_all_locs.push_back({_cloud_loc_x, _cloud_loc_y, 0.}); int nry = (int)ceil( (yp + ym) / dy ); int nrx = (int)ceil( (xp + xm) / dx ); int ixs = -(int)ceil( xm / dx ); int iys = -(int)ceil( ym / dy ); for(int j = iys; j < nry+1; j++){ double xoffset = j%2==0 ? 0. : dx/2.; for(int i = ixs; i < nrx+1; i++){ sp_point cloc = {dx * i - xoffset, dy * j, 0.}; Toolbox::rotation(V.flux.cloud_skew.val*D2R, 2, cloc); cloc.Add(V.flux.cloud_loc_x.val, V.flux.cloud_loc_y.val, 0.); _all_locs.push_back(cloc); } } break; } case var_fluxsim::CLOUD_SHAPE::FRONT: throw spexception("Cannot create a patterned cloud front! Please disable the \"" + V.flux.is_cloud_pattern.short_desc + "\" checkbox."); break; default: break; } } else{ //Single cloud sp_point p; p.x = V.flux.cloud_loc_x.val; p.y = V.flux.cloud_loc_y.val; p.z = 0.; _all_locs.push_back(p); } } double SolarField::clouds::ShadowLoss(var_map &V, sp_point &hloc){ /* Calculate the loss due to cloudiness for this particular location in the field */ if(! V.flux.is_cloudy.val) return 1.; for(vector<sp_point>::iterator cpt = _all_locs.begin(); cpt != _all_locs.end(); cpt ++){ //express the heliostat location in the coordinate system of the shadow sp_point hloc_rot = {hloc.x - cpt->x, hloc.y - cpt->y, 0.}; Toolbox::rotation(-V.flux.cloud_skew.val*R2D, 2, hloc_rot); bool shadowed = false; switch (V.flux.cloud_shape.mapval()) { case var_fluxsim::CLOUD_SHAPE::ELLIPTICAL: { double rx = V.flux.cloud_width.val/2., ry = V.flux.cloud_depth.val/2.; if( hloc_rot.x*hloc_rot.x / (rx * rx) + hloc_rot.y*hloc_rot.y / (ry * ry) < 1. ) shadowed = true; break; } case var_fluxsim::CLOUD_SHAPE::RECTANGULAR: if( fabs(hloc_rot.x) < V.flux.cloud_width.val/2. && fabs(hloc_rot.y) < V.flux.cloud_depth.val/2.) shadowed = true; break; case var_fluxsim::CLOUD_SHAPE::FRONT: if( hloc_rot.y > 0. ) shadowed = true; break; default: break; } if(shadowed) return 1. - V.flux.cloud_opacity.val; } return 1.; }
34.671894
207
0.655861
sacorbet97
cb7b75f78252d6ef3d9aee01e29b0c2ab68d9c0c
40,533
cpp
C++
test/test_util_network_ssl.cpp
Subv/realm-core
377a85d2a385a31ec91be7e5fe8c09d22365df97
[ "Apache-2.0" ]
null
null
null
test/test_util_network_ssl.cpp
Subv/realm-core
377a85d2a385a31ec91be7e5fe8c09d22365df97
[ "Apache-2.0" ]
null
null
null
test/test_util_network_ssl.cpp
Subv/realm-core
377a85d2a385a31ec91be7e5fe8c09d22365df97
[ "Apache-2.0" ]
null
null
null
#include <thread> #include <realm/util/network_ssl.hpp> #include "test.hpp" #include "util/semaphore.hpp" using namespace realm::util; using namespace realm::test_util; // Test independence and thread-safety // ----------------------------------- // // All tests must be thread safe and independent of each other. This // is required because it allows for both shuffling of the execution // order and for parallelized testing. // // In particular, avoid using std::rand() since it is not guaranteed // to be thread safe. Instead use the API offered in // `test/util/random.hpp`. // // All files created in tests must use the TEST_PATH macro (or one of // its friends) to obtain a suitable file system path. See // `test/util/test_path.hpp`. // // // Debugging and the ONLY() macro // ------------------------------ // // A simple way of disabling all tests except one called `Foo`, is to // replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the // test suite. Note that you can also use filtering by setting the // environment varible `UNITTEST_FILTER`. See `README.md` for more on // this. // // Another way to debug a particular test, is to copy that test into // `experiments/testcase.cpp` and then run `sh build.sh // check-testcase` (or one of its friends) from the command line. namespace { network::Endpoint bind_acceptor(network::Acceptor& acceptor) { network::Endpoint ep; // Wildcard acceptor.open(ep.protocol()); acceptor.bind(ep); ep = acceptor.local_endpoint(); // Get actual bound endpoint acceptor.listen(); return ep; } void connect_sockets(network::Socket& socket_1, network::Socket& socket_2) { network::Service& service_1 = socket_1.get_service(); network::Service& service_2 = socket_2.get_service(); network::Acceptor acceptor(service_1); network::Endpoint ep = bind_acceptor(acceptor); bool accept_occurred = false, connect_occurred = false; auto accept_handler = [&](std::error_code ec) { REALM_ASSERT(!ec); accept_occurred = true; }; auto connect_handler = [&](std::error_code ec) { REALM_ASSERT(!ec); connect_occurred = true; }; acceptor.async_accept(socket_1, std::move(accept_handler)); socket_2.async_connect(ep, std::move(connect_handler)); if (&service_1 == &service_2) { service_1.run(); } else { std::thread thread{[&] { service_1.run(); }}; service_2.run(); thread.join(); } REALM_ASSERT(accept_occurred); REALM_ASSERT(connect_occurred); } void configure_server_ssl_context_for_test(network::ssl::Context& ssl_context) { ssl_context.use_certificate_chain_file(get_test_resource_path() + "test_util_network_ssl_ca.pem"); ssl_context.use_private_key_file(get_test_resource_path() + "test_util_network_ssl_key.pem"); } void connect_ssl_streams(network::ssl::Stream& server_stream, network::ssl::Stream& client_stream) { network::Socket& server_socket = server_stream.lowest_layer(); network::Socket& client_socket = client_stream.lowest_layer(); connect_sockets(server_socket, client_socket); network::Service& server_service = server_socket.get_service(); network::Service& client_service = client_socket.get_service(); bool server_handshake_occurred = false, client_handshake_occurred = false; auto server_handshake_handler = [&](std::error_code ec) { REALM_ASSERT(!ec); server_handshake_occurred = true; }; auto client_handshake_handler = [&](std::error_code ec) { REALM_ASSERT(!ec); client_handshake_occurred = true; }; server_stream.async_handshake(std::move(server_handshake_handler)); client_stream.async_handshake(std::move(client_handshake_handler)); if (&server_service == &client_service) { server_service.run(); } else { std::thread thread{[&] { server_service.run(); }}; client_service.run(); thread.join(); } REALM_ASSERT(server_handshake_occurred); REALM_ASSERT(client_handshake_occurred); } class PingPongDelayFixture { public: PingPongDelayFixture(network::Service& service) : PingPongDelayFixture{service, service} { } PingPongDelayFixture(network::Service& server_service, network::Service& client_service) : m_server_socket{server_service} , m_client_socket{client_service} { connect_sockets(m_server_socket, m_client_socket); } // Must be called by thread associated with `server_service` void start_server() { initiate_server_read(); } // Must be called by thread associated with `server_service` void stop_server() { m_server_socket.cancel(); } // Must be called by thread associated with `client_service` void delay_client(realm::util::UniqueFunction<void()> handler, int n = 512) { m_handler = std::move(handler); m_num = n; initiate_client_write(); } private: network::Socket m_server_socket, m_client_socket; char m_server_char = 0, m_client_char = 0; int m_num; realm::util::UniqueFunction<void()> m_handler; void initiate_server_read() { auto handler = [this](std::error_code ec, size_t) { if (ec != error::operation_aborted) handle_server_read(ec); }; m_server_socket.async_read(&m_server_char, 1, std::move(handler)); } void handle_server_read(std::error_code ec) { if (ec) throw std::system_error(ec); initiate_server_write(); } void initiate_server_write() { auto handler = [this](std::error_code ec, size_t) { if (ec != error::operation_aborted) handle_server_write(ec); }; m_server_socket.async_write(&m_server_char, 1, std::move(handler)); } void handle_server_write(std::error_code ec) { if (ec) throw std::system_error(ec); initiate_server_read(); } void initiate_client_write() { if (m_num <= 0) { realm::util::UniqueFunction<void()> handler = std::move(m_handler); m_handler = nullptr; handler(); return; } --m_num; auto handler = [this](std::error_code ec, size_t) { if (ec != error::operation_aborted) handle_client_write(ec); }; m_client_socket.async_write(&m_client_char, 1, std::move(handler)); } void handle_client_write(std::error_code ec) { if (ec) throw std::system_error(ec); initiate_client_read(); } void initiate_client_read() { auto handler = [this](std::error_code ec, size_t) { if (ec != error::operation_aborted) handle_client_read(ec); }; m_client_socket.async_read(&m_client_char, 1, std::move(handler)); } void handle_client_read(std::error_code ec) { if (ec) throw std::system_error(ec); initiate_client_write(); } }; } // unnamed namespace TEST(Util_Network_SSL_Handshake) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_sockets(socket_1, socket_2); auto connector = [&] { std::error_code ec; ssl_stream_2.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; auto acceptor = [&] { std::error_code ec; ssl_stream_1.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; std::thread thread_1(std::move(connector)); std::thread thread_2(std::move(acceptor)); thread_1.join(); thread_2.join(); } TEST(Util_Network_SSL_AsyncHandshake) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_sockets(socket_1, socket_2); bool connect_completed = false; auto connect_handler = [&](std::error_code ec) { CHECK_EQUAL(std::error_code(), ec); connect_completed = true; }; bool accept_completed = false; auto accept_handler = [&](std::error_code ec) { CHECK_EQUAL(std::error_code(), ec); accept_completed = true; }; ssl_stream_1.async_handshake(std::move(accept_handler)); ssl_stream_2.async_handshake(std::move(connect_handler)); service.run(); CHECK(connect_completed); CHECK(accept_completed); } TEST(Util_Network_SSL_ReadWriteShutdown) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); const char* message = "hello"; char buffer[256]; auto writer = [&] { std::size_t n = ssl_stream_1.write(message, std::strlen(message)); CHECK_EQUAL(std::strlen(message), n); ssl_stream_1.shutdown(); }; auto reader = [&] { std::error_code ec; std::size_t n = ssl_stream_2.read(buffer, sizeof buffer, ec); if (CHECK_EQUAL(MiscExtErrors::end_of_input, ec)) { if (CHECK_EQUAL(std::strlen(message), n)) CHECK(std::equal(buffer, buffer + n, message)); } }; std::thread thread_1(std::move(writer)); std::thread thread_2(std::move(reader)); thread_1.join(); thread_2.join(); } TEST(Util_Network_SSL_AsyncReadWriteShutdown) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); const char* message = "hello"; char buffer[256]; bool shutdown_completed = false; auto shutdown_handler = [&](std::error_code ec) { CHECK_EQUAL(std::error_code(), ec); shutdown_completed = true; }; auto write_handler = [&](std::error_code ec, std::size_t n) { CHECK_EQUAL(std::error_code(), ec); CHECK_EQUAL(std::strlen(message), n); ssl_stream_1.async_shutdown(std::move(shutdown_handler)); }; bool read_completed = false; auto read_handler = [&](std::error_code ec, std::size_t n) { CHECK_EQUAL(MiscExtErrors::end_of_input, ec); if (CHECK_EQUAL(std::strlen(message), n)) CHECK(std::equal(buffer, buffer + n, message)); read_completed = true; }; ssl_stream_1.async_write(message, std::strlen(message), std::move(write_handler)); ssl_stream_2.async_read(buffer, sizeof buffer, std::move(read_handler)); service.run(); CHECK(shutdown_completed); CHECK(read_completed); } TEST(Util_Network_SSL_PrematureEndOfInputOnHandshakeRead) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_sockets(socket_1, socket_2); socket_1.shutdown(network::Socket::shutdown_send); // Use a separate thread to consume data written by Stream::handshake(), // such that we can be sure not to block. auto consumer = [&] { constexpr std::size_t size = 4096; std::unique_ptr<char[]> buffer(new char[size]); std::error_code ec; do { socket_1.read_some(buffer.get(), size, ec); } while (!ec); REALM_ASSERT(ec == MiscExtErrors::end_of_input); }; std::thread thread(std::move(consumer)); #if REALM_HAVE_OPENSSL CHECK_SYSTEM_ERROR(ssl_stream_2.handshake(), MiscExtErrors::premature_end_of_input); #elif REALM_HAVE_SECURE_TRANSPORT // We replace the CHECK_SYSTEM_ERROR check for "premature end of input" // with a check for any error code, Mac OS occasionally reports another // system error. We can revisit the details of the error code later. The // detailed check is disabled for now to reduce the number of failed unit // test runs. CHECK_THROW(ssl_stream_2.handshake(), std::system_error); #endif socket_2.close(); thread.join(); } #ifndef _WIN32 // FIXME: winsock doesn't have EPIPE, what's the equivalent? TEST(Util_Network_SSL_BrokenPipeOnHandshakeWrite) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_sockets(socket_1, socket_2); socket_1.close(); // Fill the kernel level write buffer, to provoke error::broken_pipe. constexpr std::size_t size = 4096; std::unique_ptr<char[]> buffer(new char[size]); std::fill(buffer.get(), buffer.get() + size, 0); std::error_code ec; do { socket_2.write_some(buffer.get(), size, ec); } while (!ec); #if REALM_PLATFORM_APPLE // Which error we get from writing to a closed socket seems to depend on // some asynchronous kernel state. If it notices that the socket is closed // before sending any data we get EPIPE, and if it's after trying to send // data it's ECONNRESET. EHOSTDOWN is not documented as an error code from // send() and may be worth investigating once the macOS 12 XNU source is // released. REALM_ASSERT(ec == error::broken_pipe || ec == error::connection_reset || ec.value() == EHOSTDOWN); #else REALM_ASSERT(ec == error::broken_pipe); #endif CHECK_SYSTEM_ERROR(ssl_stream_2.handshake(), error::broken_pipe); } #endif TEST(Util_Network_SSL_EndOfInputOnRead) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); ssl_stream_2.shutdown(); socket_2.shutdown(network::Socket::shutdown_send); char ch; CHECK_SYSTEM_ERROR(ssl_stream_1.read_some(&ch, 1), MiscExtErrors::end_of_input); } TEST(Util_Network_SSL_PrematureEndOfInputOnRead) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); socket_2.shutdown(network::Socket::shutdown_send); char ch; CHECK_SYSTEM_ERROR(ssl_stream_1.read_some(&ch, 1), MiscExtErrors::premature_end_of_input); } #ifndef _WIN32 // FIXME: winsock doesn't have EPIPE, what's the equivalent? TEST(Util_Network_SSL_BrokenPipeOnWrite) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); socket_1.close(); // Fill the kernel level write buffer, to provoke error::broken_pipe. constexpr std::size_t size = 4096; std::unique_ptr<char[]> buffer(new char[size]); std::fill(buffer.get(), buffer.get() + size, 0); std::error_code ec; do { socket_2.write_some(buffer.get(), size, ec); } while (!ec); #if REALM_PLATFORM_APPLE REALM_ASSERT(ec == error::broken_pipe || ec == error::connection_reset || ec.value() == EHOSTDOWN); #else REALM_ASSERT(ec == error::broken_pipe); #endif char ch = 0; CHECK_SYSTEM_ERROR(ssl_stream_2.write(&ch, 1), error::broken_pipe); } TEST(Util_Network_SSL_BrokenPipeOnShutdown) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); socket_1.close(); // Fill the kernel level write buffer, to provoke error::broken_pipe. constexpr std::size_t size = 4096; std::unique_ptr<char[]> buffer(new char[size]); std::fill(buffer.get(), buffer.get() + size, 0); std::error_code ec; do { socket_2.write_some(buffer.get(), size, ec); } while (!ec); #if REALM_PLATFORM_APPLE REALM_ASSERT(ec == error::broken_pipe || ec == error::connection_reset || ec.value() == EHOSTDOWN); #else REALM_ASSERT(ec == error::broken_pipe); #endif CHECK_SYSTEM_ERROR(ssl_stream_2.shutdown(), error::broken_pipe); } #endif TEST(Util_Network_SSL_ShutdownBeforeCloseNotifyReceived) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); // Shut down peer 1's writing side before it has received a shutdown alert // from peer 2. ssl_stream_1.shutdown(); } TEST(Util_Network_SSL_ShutdownAfterCloseNotifyReceived) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); // Make sure peer 2 gets an SSL shutdown alert. ssl_stream_1.shutdown(); socket_1.shutdown(network::Socket::shutdown_send); // Make sure peer 2 received the shutdown alert from peer 1 before peer 2 // writes. char ch; CHECK_SYSTEM_ERROR(ssl_stream_2.read_some(&ch, 1), MiscExtErrors::end_of_input); // Check that peer 2 can stil permform a shutdown operation. ssl_stream_2.shutdown(); } TEST(Util_Network_SSL_WriteAfterCloseNotifyReceived) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); // Shut down peer 1's writing side, such that peer 2 gets an SSL shutdown // alert. ssl_stream_1.shutdown(); socket_1.shutdown(network::Socket::shutdown_send); // Make sure peer 2 received the shutdown alert from peer 1 before peer 2 // writes. char ch; CHECK_SYSTEM_ERROR(ssl_stream_2.read_some(&ch, 1), MiscExtErrors::end_of_input); // Make peer 2 Write a message, which must fail....???? const char* message = "hello"; CHECK_SYSTEM_ERROR(ssl_stream_2.write(message, std::strlen(message)), error::broken_pipe); } TEST(Util_Network_SSL_BasicSendAndReceive) { network::Service service; network::Socket socket_1{service}, socket_2{service}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); // Make peer 2 Write a message. const char* message = "hello"; ssl_stream_2.write(message, std::strlen(message)); ssl_stream_2.shutdown(); socket_2.shutdown(network::Socket::shutdown_send); // Check that peer 1 received the message correctly. char buffer[256]; std::error_code ec; std::size_t n = ssl_stream_1.read(buffer, sizeof buffer, ec); CHECK_EQUAL(MiscExtErrors::end_of_input, ec); if (CHECK_EQUAL(std::strlen(message), n)) CHECK(std::equal(buffer, buffer + n, message)); } TEST(Util_Network_SSL_StressTest) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; configure_server_ssl_context_for_test(ssl_context_1); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); connect_ssl_streams(ssl_stream_1, ssl_stream_2); constexpr size_t original_size = 0x100000; // 1MiB std::unique_ptr<char[]> original_1, original_2; original_1.reset(new char[original_size]); original_2.reset(new char[original_size]); { std::mt19937_64 prng{std::random_device()()}; using lim = std::numeric_limits<char>; std::uniform_int_distribution<short> dist{short(lim::min()), short(lim::max())}; log("Initializing..."); for (size_t i = 0; i < original_size; ++i) original_1[i] = char(dist(prng)); for (size_t i = 0; i < original_size; ++i) original_2[i] = char(dist(prng)); log("Initialized"); } struct Stats { std::uint_fast64_t num_cancellations = 0; std::uint_fast64_t num_reads = 0, num_canceled_reads = 0; std::uint_fast64_t num_writes = 0, num_canceled_writes = 0; }; #ifdef _WIN32 // With 512, it would take 9 minutes in 32-bit Debug mode on Windows constexpr int num_cycles = 32; #else constexpr int num_cycles = 512; #endif auto thread = [&](int id, network::ssl::Stream& ssl_stream, const char* read_original, const char* write_original, Stats& stats) { std::unique_ptr<char[]> read_buffer{new char[original_size]}; std::mt19937_64 prng{std::random_device()()}; // Using range 1B -> 32KiB because that undershoots and overshoots in // equal amounts with respect to the SSL frame size of 16KiB. std::uniform_int_distribution<size_t> read_write_size_dist(1, 32 * 1024); std::uniform_int_distribution<int> delayed_read_write_dist(0, 49); network::Service& service = ssl_stream.lowest_layer().get_service(); network::DeadlineTimer cancellation_timer{service}; network::DeadlineTimer read_timer{service}; network::DeadlineTimer write_timer{service}; bool read_done = false, write_done = false; realm::util::UniqueFunction<void()> shedule_cancellation = [&] { auto handler = [&](std::error_code ec) { REALM_ASSERT(!ec || ec == error::operation_aborted); if (ec == error::operation_aborted) return; if (read_done && write_done) return; ssl_stream.lowest_layer().cancel(); ++stats.num_cancellations; shedule_cancellation(); }; cancellation_timer.async_wait(std::chrono::microseconds(10), std::move(handler)); }; // shedule_cancellation(); char* read_begin = read_buffer.get(); char* read_end = read_buffer.get() + original_size; int num_read_cycles = 0; realm::util::UniqueFunction<void()> read = [&] { if (read_begin == read_end) { log("<R%1>", id); CHECK(std::equal(read_original, read_original + original_size, read_buffer.get())); ++num_read_cycles; if (num_read_cycles == num_cycles) { log("End of read %1", id); read_done = true; if (write_done) cancellation_timer.cancel(); return; } read_begin = read_buffer.get(); read_end = read_buffer.get() + original_size; } auto handler = [&](std::error_code ec, size_t n) { REALM_ASSERT(!ec || ec == error::operation_aborted); ++stats.num_reads; if (ec == error::operation_aborted) { ++stats.num_canceled_reads; } else { read_begin += n; } if (delayed_read_write_dist(prng) == 0) { auto handler_2 = [&](std::error_code ec) { REALM_ASSERT(!ec); read(); }; read_timer.async_wait(std::chrono::microseconds(100), std::move(handler_2)); } else { read(); } }; char* buffer = read_begin; size_t size = read_write_size_dist(prng); size_t max_size = read_end - read_begin; if (size > max_size) size = max_size; ssl_stream.async_read_some(buffer, size, std::move(handler)); }; read(); const char* write_begin = write_original; const char* write_end = write_original + original_size; int num_write_cycles = 0; realm::util::UniqueFunction<void()> write = [&] { if (write_begin == write_end) { log("<W%1>", id); ++num_write_cycles; if (num_write_cycles == num_cycles) { log("End of write %1", id); write_done = true; if (read_done) cancellation_timer.cancel(); return; } write_begin = write_original; write_end = write_original + original_size; } auto handler = [&](std::error_code ec, size_t n) { REALM_ASSERT(!ec || ec == error::operation_aborted); ++stats.num_writes; if (ec == error::operation_aborted) { ++stats.num_canceled_writes; } else { write_begin += n; } if (delayed_read_write_dist(prng) == 0) { auto handler_2 = [&](std::error_code ec) { REALM_ASSERT(!ec); write(); }; write_timer.async_wait(std::chrono::microseconds(100), std::move(handler_2)); } else { write(); } }; const char* data = write_begin; size_t size = read_write_size_dist(prng); size_t max_size = write_end - write_begin; if (size > max_size) size = max_size; ssl_stream.async_write_some(data, size, std::move(handler)); }; write(); service.run(); }; Stats stats_1, stats_2; std::thread thread_1{[&] { thread(1, ssl_stream_1, original_1.get(), original_2.get(), stats_1); }}; std::thread thread_2{[&] { thread(2, ssl_stream_2, original_2.get(), original_1.get(), stats_2); }}; thread_1.join(); thread_2.join(); ssl_stream_1.shutdown(); ssl_stream_2.shutdown(); char ch; CHECK_SYSTEM_ERROR(ssl_stream_1.read_some(&ch, 1), MiscExtErrors::end_of_input); CHECK_SYSTEM_ERROR(ssl_stream_2.read_some(&ch, 1), MiscExtErrors::end_of_input); log("Cancellations: %1, %2", stats_1.num_cancellations, stats_2.num_cancellations); log("Reads: %1 (%2 canceled), %3 (%4 canceled)", stats_1.num_reads, stats_1.num_canceled_reads, stats_2.num_reads, stats_2.num_canceled_reads); log("Writes: %1 (%2 canceled), %3 (%4 canceled)", stats_1.num_writes, stats_1.num_canceled_writes, stats_2.num_writes, stats_2.num_canceled_writes); } // The host name is contained in both the // Common Name and the Subject Alternartive Name // section of the server certificate. TEST(Util_Network_SSL_Certificate_CN_SAN) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; std::string ca_dir = get_test_resource_path() + "../certificate-authority"; ssl_context_1.use_certificate_chain_file(ca_dir + "/certs/dns-chain.crt.pem"); ssl_context_1.use_private_key_file(ca_dir + "/certs/dns-checked-server.key.pem"); ssl_context_2.use_verify_file(ca_dir + "/root-ca/crt.pem"); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); ssl_stream_2.set_verify_mode(realm::util::network::ssl::VerifyMode::peer); // We expect success because the certificate is signed for www.example.com // in both Common Name and SAN. ssl_stream_2.set_host_name("www.example.com"); connect_sockets(socket_1, socket_2); auto connector = [&] { std::error_code ec; ssl_stream_2.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; auto acceptor = [&] { std::error_code ec; ssl_stream_1.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; std::thread thread_1(std::move(connector)); std::thread thread_2(std::move(acceptor)); thread_1.join(); thread_2.join(); } // The host name is only contained in the // Subject Alternative Name section of the certificate. TEST(Util_Network_SSL_Certificate_SAN) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; std::string ca_dir = get_test_resource_path() + "../certificate-authority"; ssl_context_1.use_certificate_chain_file(ca_dir + "/certs/dns-chain.crt.pem"); ssl_context_1.use_private_key_file(ca_dir + "/certs/dns-checked-server.key.pem"); ssl_context_2.use_verify_file(ca_dir + "/root-ca/crt.pem"); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); ssl_stream_2.set_verify_mode(realm::util::network::ssl::VerifyMode::peer); ssl_stream_2.set_host_name("support.example.com"); connect_sockets(socket_1, socket_2); auto connector = [&] { std::error_code ec; ssl_stream_2.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; auto acceptor = [&] { std::error_code ec; ssl_stream_1.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; std::thread thread_1(std::move(connector)); std::thread thread_2(std::move(acceptor)); thread_1.join(); thread_2.join(); } // FIXME: Verification of peer against Common Name is no longer supported in // Catalina (macOS). #if REALM_HAVE_OPENSSL || !REALM_HAVE_SECURE_TRANSPORT // The host name www.example.com is contained in Common Name but not in SAN. TEST(Util_Network_SSL_Certificate_CN) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; std::string ca_dir = get_test_resource_path() + "../certificate-authority"; ssl_context_1.use_certificate_chain_file(ca_dir + "/certs/ip-chain.crt.pem"); ssl_context_1.use_private_key_file(ca_dir + "/certs/ip-server.key.pem"); ssl_context_2.use_verify_file(ca_dir + "/root-ca/crt.pem"); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); ssl_stream_2.set_verify_mode(realm::util::network::ssl::VerifyMode::peer); ssl_stream_2.set_host_name("www.example.com"); connect_sockets(socket_1, socket_2); auto connector = [&] { std::error_code ec; ssl_stream_2.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; auto acceptor = [&] { std::error_code ec; ssl_stream_1.handshake(ec); CHECK_EQUAL(std::error_code(), ec); }; std::thread thread_1(std::move(connector)); std::thread thread_2(std::move(acceptor)); thread_1.join(); thread_2.join(); } #endif // REALM_HAVE_OPENSSL || !REALM_HAVE_SECURE_TRANSPORT // The ip address is contained in the IP SAN section // of the certificate. For OpenSSL, we expect failure because we only // check for DNS. For Secure Transport we get success because the // ip section is checked. This discrepancy could be resolved in the // future if deemed important. TEST(Util_Network_SSL_Certificate_IP) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; std::string ca_dir = get_test_resource_path() + "../certificate-authority"; ssl_context_1.use_certificate_chain_file(ca_dir + "/certs/ip-chain.crt.pem"); ssl_context_1.use_private_key_file(ca_dir + "/certs/ip-server.key.pem"); ssl_context_2.use_verify_file(ca_dir + "/root-ca/crt.pem"); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); ssl_stream_2.set_verify_mode(realm::util::network::ssl::VerifyMode::peer); ssl_stream_2.set_host_name("127.0.0.1"); connect_sockets(socket_1, socket_2); auto connector = [&] { std::error_code ec; ssl_stream_2.handshake(ec); #if REALM_HAVE_OPENSSL CHECK_NOT_EQUAL(std::error_code(), ec); #elif REALM_HAVE_SECURE_TRANSPORT CHECK_EQUAL(std::error_code(), ec); #endif }; auto acceptor = [&] { std::error_code ec; ssl_stream_1.handshake(ec); #if REALM_HAVE_OPENSSL CHECK_NOT_EQUAL(std::error_code(), ec); #elif REALM_HAVE_SECURE_TRANSPORT CHECK_EQUAL(std::error_code(), ec); #endif }; std::thread thread_1(std::move(connector)); std::thread thread_2(std::move(acceptor)); thread_1.join(); thread_2.join(); } // The certificate contains incorrect host names. // We expect the handshake to fail. TEST(Util_Network_SSL_Certificate_Failure) { network::Service service_1, service_2; network::Socket socket_1{service_1}, socket_2{service_2}; network::ssl::Context ssl_context_1; network::ssl::Context ssl_context_2; std::string ca_dir = get_test_resource_path() + "../certificate-authority"; ssl_context_1.use_certificate_chain_file(ca_dir + "/certs/dns-chain.crt.pem"); ssl_context_1.use_private_key_file(ca_dir + "/certs/dns-checked-server.key.pem"); ssl_context_2.use_verify_file(ca_dir + "/root-ca/crt.pem"); network::ssl::Stream ssl_stream_1{socket_1, ssl_context_1, network::ssl::Stream::server}; network::ssl::Stream ssl_stream_2{socket_2, ssl_context_2, network::ssl::Stream::client}; ssl_stream_1.set_logger(&test_context.logger); ssl_stream_2.set_logger(&test_context.logger); ssl_stream_2.set_verify_mode(realm::util::network::ssl::VerifyMode::peer); // We expect failure because the certificate is signed for www.example.com ssl_stream_2.set_host_name("www.another-example.com"); connect_sockets(socket_1, socket_2); auto connector = [&] { std::error_code ec; ssl_stream_2.handshake(ec); // Refine this CHECK_NOT_EQUAL(std::error_code(), ec); }; auto acceptor = [&] { std::error_code ec; ssl_stream_1.handshake(ec); // Refine this CHECK_NOT_EQUAL(std::error_code(), ec); }; std::thread thread_1(std::move(connector)); std::thread thread_2(std::move(acceptor)); thread_1.join(); thread_2.join(); }
36.814714
118
0.67202
Subv
cb80b31eabe2f186879f72c627146ef22579f727
1,803
cpp
C++
src/medPacs/medAbstractPacsMoveScu.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src/medPacs/medAbstractPacsMoveScu.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src/medPacs/medAbstractPacsMoveScu.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "medAbstractPacsMoveScu.h" #include "medAbstractPacsNode.h" #include <dtkCore/dtkGlobal.h> int medAbstractPacsMoveScu::sendMoveRequest( const char* peerTitle, const char* peerIP, unsigned int peerPort, const char* ourTitle, const char* ourIP, unsigned int ourPort ) { DTK_UNUSED(peerTitle); DTK_UNUSED(peerIP); DTK_UNUSED(peerPort); DTK_UNUSED(ourTitle); DTK_UNUSED(ourIP); DTK_UNUSED(ourPort); DTK_DEFAULT_IMPLEMENTATION; return 0; } medAbstractPacsMoveScu::medAbstractPacsMoveScu( void ) { } medAbstractPacsMoveScu::~medAbstractPacsMoveScu( void ) { } void medAbstractPacsMoveScu::useBuildInStoreSCP( bool flag ) { DTK_UNUSED(flag); DTK_DEFAULT_IMPLEMENTATION; } bool medAbstractPacsMoveScu::setStorageDirectory( const char* directory ) { DTK_UNUSED(directory); DTK_DEFAULT_IMPLEMENTATION; return false; } bool medAbstractPacsMoveScu::addRequestToQueue( int group, int elem, const char* query, medAbstractPacsNode& moveSource, medAbstractPacsNode& moveTarget) { DTK_UNUSED(group); DTK_UNUSED(elem); DTK_UNUSED(query); DTK_UNUSED(moveSource); DTK_UNUSED(moveTarget); DTK_DEFAULT_IMPLEMENTATION; return false; } int medAbstractPacsMoveScu::performQueuedMoveRequests() { DTK_DEFAULT_IMPLEMENTATION; return 0; } void medAbstractPacsMoveScu::sendCancelRequest() { DTK_DEFAULT_IMPLEMENTATION; }
21.987805
174
0.695507
ocommowi
cb80e817794d89f60a9a68f2a6fb6135e2762dc1
5,612
cpp
C++
src/Material.cpp
JoshNoel/Raytracer
2ff3aaecb5d9048a9b6a5f0a1a05560449dacd0e
[ "MIT" ]
null
null
null
src/Material.cpp
JoshNoel/Raytracer
2ff3aaecb5d9048a9b6a5f0a1a05560449dacd0e
[ "MIT" ]
null
null
null
src/Material.cpp
JoshNoel/Raytracer
2ff3aaecb5d9048a9b6a5f0a1a05560449dacd0e
[ "MIT" ]
null
null
null
#include "Material.h" #include "Ray.h" #include "Triangle.h" #include "MathHelper.h" #include <array> #include <fstream> #include "helper/array.h" Material::Material(glm::vec3 col, float dc, glm::vec3 specCol, float sc, float shine, float ref, float ior) : color(col), diffuseCoef(dc), indexOfRefrac(ior), specCoef(sc), specularColor(specCol), shininess(shine), reflectivity(ref), texture() { } Material::~Material() { } bool Material::loadMTL(const std::string& path, const std::string& materialName) { int extStart = path.find_last_of('.'); if(path.substr(extStart) != ".mtl") return false; std::string line; std::ifstream ifs; ifs.open(path); if(!ifs.is_open()) return false; type = Material::DIFFUSE | Material::BPHONG_SPECULAR; //clear file stream until it reaches the correct material name // indicates start of material data while(getline(ifs, line)) { if(line.find("newmtl") != std::string::npos && line.find(materialName) != std::string::npos) break; } while(getline(ifs, line)) { //import texture if(line.find("map_Kd") != std::string::npos) { int spacePos = line.find_first_of(' '); std::string texturePath = line.substr(spacePos + 1); if(texture.loadImage(texturePath)) hasTexture = true; } //import shininess else if(line.find("Ns") != std::string::npos) { int spacePos = line.find_first_of(' '); shininess = std::stof(line.substr(spacePos + 1)); } //import IOR else if(line.find("Ni") != std::string::npos) { int spacePos = line.find_first_of(' '); indexOfRefrac = std::stof(line.substr(spacePos + 1)); } //import diffuse color else if(line.find("Kd") != std::string::npos) { //convert from normalized colors to [0, 255] scale int spacePos = line.find_first_of(' '); float r = std::stof(line.substr(spacePos + 1)) * 255.0f; spacePos = line.find(' ', spacePos + 1); float g = std::stof(line.substr(spacePos + 1)) * 255.0f; spacePos = line.find(' ', spacePos + 1); float b = std::stof(line.substr(spacePos + 1)) * 255.0f; color = glm::vec3(r, g, b); } //import specular color else if(line.find("Ks") != std::string::npos) { int spacePos = line.find_first_of(' '); float r = std::stof(line.substr(spacePos + 1)) * 255.0f; spacePos = line.find(' ', spacePos + 1); float g = std::stof(line.substr(spacePos + 1)) * 255.0f; spacePos = line.find(' ', spacePos + 1); float b = std::stof(line.substr(spacePos + 1)) * 255.0f; specularColor = glm::vec3(r, g, b); } //exit when next material is found else if(line.find("newmtl") != std::string::npos) break; } if(ifs.bad()) return false; ifs.close(); return true; } CUDA_HOST CUDA_DEVICE glm::vec3 Material::sample(const Ray& ray, float t) const { if(!hasTexture) return color; //sample texture //first compute coefficients for weighted average of uvCoords at 3 triangle points for the intersection point //I = intersection glm::vec3 I = ray.pos + ray.dir * t; helper::array<glm::vec2, 3, true> triCoords; if(!ray.hitTri->getUV(triCoords)) return color; /* p3 /\ / \ / \ / \ / \ / \ / \ / \ / \ /__________________\ p1 p2 */ //if lines are drawn from each vertex to the intersection point, // the ratio of the uvCoordinate of each point contributed to the intersection point // is equal to the ratio of the area of the opposite inner triangle to the area of the whole triangle glm::vec3 p1 = ray.hitTri->getWorldCoords()[0]; glm::vec3 p2 = ray.hitTri->getWorldCoords()[1]; glm::vec3 p3 = ray.hitTri->getWorldCoords()[2]; //areas are doubled, but the ratio of the sub-triangle areas to the whole triangle is all that matters glm::vec3 totalAreaVec = glm::cross(p2 - p1, p3 - p1); float totalArea = glm::length(totalAreaVec); glm::vec3 ItoP1 = p1 - I; glm::vec3 ItoP2 = p2 - I; glm::vec3 ItoP3 = p3 - I; float p1Area = glm::length(glm::cross(ItoP2, ItoP3)); float p2Area = glm::length(glm::cross(ItoP3, ItoP1)); float p3Area = glm::length(glm::cross(ItoP1, ItoP2)); float p1Weight = p1Area / totalArea; float p2Weight = p2Area / totalArea; float p3Weight = p3Area / totalArea; glm::vec2 uv1 = triCoords[0]; glm::vec2 uv2 = triCoords[1]; glm::vec2 uv3 = triCoords[2]; glm::vec2 intersectionCoord = uv1 * p1Weight + uv2 * p2Weight + uv3 * p3Weight; return texture.getPixel(intersectionCoord); } CUDA_HOST CUDA_DEVICE float Material::calcReflectivity(float angle, float n1) const { //calculates the reflectivity of the material using fresnel's law float angleOfRefraction = std::asin((n1*std::sin(angle)) / this->indexOfRefrac); //s polarized reflectance float i1cos = n1*std::cos(angle); float r2cos = this->indexOfRefrac * std::cos(angleOfRefraction); float Rs = std::pow(std::fabs((i1cos - r2cos) / (i1cos + r2cos)), 2.0f); //p polarized reflectance float i2cos = n1*std::cos(angleOfRefraction); float r1cos = this->indexOfRefrac * std::cos(angle); float Rp = std::pow(std::fabs((i2cos - r1cos) / (i2cos + r1cos)), 2.0f); return (Rs + Rp) / 2.0f; } void Material::setTexture(const Texture& tex) { this->texture = tex; hasTexture = true; } //Initialize constant indicies of refraction const float Material::IOR::AIR = 1.0f; const float Material::IOR::WATER = 4.0f/3.0f; const float Material::IOR::ICE = 1.31f; const float Material::IOR::GLASS = 1.66f; //Initialize constant colors const glm::vec3 Material::COLORS::WHITE = glm::vec3(255, 255, 255);
27.509804
110
0.651639
JoshNoel
cb82b95e796f59f5085527c2cedd5e626493675a
530
cc
C++
yt/cpp-template/src/lib/cpplib.cc
e-dnx/courses
d21742a51447496f541dc8ec32b0df79d709dbff
[ "MIT" ]
null
null
null
yt/cpp-template/src/lib/cpplib.cc
e-dnx/courses
d21742a51447496f541dc8ec32b0df79d709dbff
[ "MIT" ]
null
null
null
yt/cpp-template/src/lib/cpplib.cc
e-dnx/courses
d21742a51447496f541dc8ec32b0df79d709dbff
[ "MIT" ]
null
null
null
#include "cpplib.h" #include "limits" std::string CPPLib::PrintHelloWorld() { return "**** Hello World ****"; } // Calculates the Nth Fibonacci number int CPPLib::fib(int N) { if (N == 0) { return 0; } if (N == 1) { return 1; } return fib(N - 1) + fib(N - 2); } int CPPLib::FindMax(const std::vector<int> &inputs) { if (inputs.size() == 0) { return -1; } int result = std::numeric_limits<int>::min(); for (auto n : inputs) { if (n > result) { result = n; } } return result; }
16.5625
73
0.549057
e-dnx
cb86d020926f4bdd1a6b0390b31c46990939a1fa
3,986
cpp
C++
libs/asio/test/buffer.cpp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
11
2015-07-12T13:04:52.000Z
2021-05-30T23:23:46.000Z
libs/asio/test/buffer.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
null
null
null
libs/asio/test/buffer.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
3
2015-12-23T01:51:57.000Z
2019-08-25T04:58:32.000Z
// // buffer.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff 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) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include <boost/asio/buffer.hpp> #include <boost/array.hpp> #include "unit_test.hpp" //------------------------------------------------------------------------------ // buffer_compile test // ~~~~~~~~~~~~~~~~~~~ // The following test checks that all overloads of the buffer function compile // and link correctly. Runtime failures are ignored. namespace buffer_compile { using namespace boost::asio; void test() { try { char raw_data[1024]; const char const_raw_data[1024] = ""; void* void_ptr_data = raw_data; const void* const_void_ptr_data = const_raw_data; boost::array<char, 1024> array_data; const boost::array<char, 1024>& const_array_data_1 = array_data; boost::array<const char, 1024> const_array_data_2 = { { 0 } }; std::vector<char> vector_data(1024); const std::vector<char>& const_vector_data = vector_data; const std::string string_data(1024, ' '); // mutable_buffer constructors. mutable_buffer mb1; mutable_buffer mb2(void_ptr_data, 1024); mutable_buffer mb3(mb1); // mutable_buffer functions. void* ptr1 = buffer_cast<void*>(mb1); (void)ptr1; std::size_t size1 = buffer_size(mb1); (void)size1; // mutable_buffer operators. mb1 = mb2 + 128; mb1 = 128 + mb2; // mutable_buffers_1 constructors. mutable_buffers_1 mbc1(mb1); mutable_buffers_1 mbc2(mbc1); // mutable_buffers_1 functions. mutable_buffers_1::const_iterator iter1 = mbc1.begin(); (void)iter1; mutable_buffers_1::const_iterator iter2 = mbc1.end(); (void)iter2; // const_buffer constructors. const_buffer cb1; const_buffer cb2(const_void_ptr_data, 1024); const_buffer cb3(cb1); const_buffer cb4(mb1); // const_buffer functions. const void* ptr2 = buffer_cast<const void*>(cb1); (void)ptr2; std::size_t size2 = buffer_size(cb1); (void)size2; // const_buffer operators. cb1 = cb2 + 128; cb1 = 128 + cb2; // const_buffers_1 constructors. const_buffers_1 cbc1(cb1); const_buffers_1 cbc2(cbc1); // const_buffers_1 functions. const_buffers_1::const_iterator iter3 = cbc1.begin(); (void)iter3; const_buffers_1::const_iterator iter4 = cbc1.end(); (void)iter4; // buffer function overloads. mb1 = buffer(mb2); mb1 = buffer(mb2, 128); cb1 = buffer(cb2); cb1 = buffer(cb2, 128); mb1 = buffer(void_ptr_data, 1024); cb1 = buffer(const_void_ptr_data, 1024); mb1 = buffer(raw_data); mb1 = buffer(raw_data, 1024); cb1 = buffer(const_raw_data); cb1 = buffer(const_raw_data, 1024); mb1 = buffer(array_data); mb1 = buffer(array_data, 1024); cb1 = buffer(const_array_data_1); cb1 = buffer(const_array_data_1, 1024); cb1 = buffer(const_array_data_2); cb1 = buffer(const_array_data_2, 1024); mb1 = buffer(vector_data); mb1 = buffer(vector_data, 1024); cb1 = buffer(const_vector_data); cb1 = buffer(const_vector_data, 1024); cb1 = buffer(string_data); cb1 = buffer(string_data, 1024); } catch (std::exception&) { } } } // namespace buffer_compile //------------------------------------------------------------------------------ test_suite* init_unit_test_suite(int, char*[]) { test_suite* test = BOOST_TEST_SUITE("buffer"); test->add(BOOST_TEST_CASE(&buffer_compile::test)); return test; }
26.751678
81
0.623432
zyiacas
cb87696c4881154da3875a239a73a08433467bd7
2,012
cpp
C++
core/src/view/light/PointLight.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
core/src/view/light/PointLight.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
core/src/view/light/PointLight.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * PointLight.cpp * Copyright (C) 2009-2017 by MegaMol Team * Alle Rechte vorbehalten. */ #include "mmcore/view/light/PointLight.h" #include "mmcore/param/ColorParam.h" #include "mmcore/param/FloatParam.h" #include "mmcore/param/Vector3fParam.h" #include "stdafx.h" using namespace megamol::core::view::light; void megamol::core::view::light::PointLight::addLight(LightCollection& light_collection) { light_collection.add<PointLightType>(std::static_pointer_cast<PointLightType>(lightsource)); } /* * megamol::core::view::light::PointLight::PointLight */ PointLight::PointLight(void) : AbstractLight(), position("Position", ""), radius("Radius", "") { // point light lightsource = std::make_shared<PointLightType>(); this->position << new core::param::Vector3fParam(vislib::math::Vector<float, 3>(0.0f, 0.0f, 0.0f)); this->radius << new core::param::FloatParam(0.0f); this->MakeSlotAvailable(&this->position); this->MakeSlotAvailable(&this->radius); } /* * megamol::core::view::light::PointLight::~PointLight */ PointLight::~PointLight(void) { this->Release(); } /* * megamol::core::view::light::PointLight::readParams */ void PointLight::readParams() { auto light = std::static_pointer_cast<PointLightType>(lightsource); light->colour = this->lightColor.Param<core::param::ColorParam>()->Value(); light->intensity = this->lightIntensity.Param<core::param::FloatParam>()->Value(); auto pl_pos = this->position.Param<core::param::Vector3fParam>()->Value().PeekComponents(); std::copy(pl_pos, pl_pos + 3, light->position.begin()); light->radius = this->radius.Param<core::param::FloatParam>()->Value(); } /* * megamol::core::view::light::PointLight::InterfaceIsDirty */ bool PointLight::InterfaceIsDirty() { if (this->AbstractIsDirty() || this->position.IsDirty() || this->radius.IsDirty()) { this->position.ResetDirty(); this->radius.ResetDirty(); return true; } else { return false; } }
30.484848
103
0.683897
masrice
cb8964efc3e0de162559226feb6de3d668afb4ad
6,851
hpp
C++
tuttex/adjacency_list.hpp
DavePearce/TuttePoly
0a97f50d0c7bede42c39e19e7f5145b06aaad45d
[ "BSD-3-Clause" ]
null
null
null
tuttex/adjacency_list.hpp
DavePearce/TuttePoly
0a97f50d0c7bede42c39e19e7f5145b06aaad45d
[ "BSD-3-Clause" ]
1
2021-01-27T23:04:31.000Z
2021-01-27T23:04:31.000Z
tuttex/adjacency_list.hpp
DavePearce/TuttePoly
0a97f50d0c7bede42c39e19e7f5145b06aaad45d
[ "BSD-3-Clause" ]
null
null
null
// (C) Copyright David James Pearce and Gary Haggard, 2007. // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // // Email: david.pearce@mcs.vuw.ac.nz #ifndef ADJACENCY_LIST_HPP #define ADJACENCY_LIST_HPP #include <vector> #include <map> #include <list> #include <algorithm> #include <stdexcept> // This graph type is simply the most basic implementation // you could think of. // Note, T here must implement the multiple sorted // associative container interface defined in the STL template<class T = std::map<unsigned int, unsigned int> > class adjacency_list { public: typedef std::list<unsigned int>::const_iterator vertex_iterator; typedef typename T::iterator int_edge_iterator; typedef typename T::const_iterator edge_iterator; private: int numedges; // useful cache std::list<unsigned int> vertices; unsigned int _domain_size; std::vector<T> edges; int nummultiedges; public: adjacency_list(int n = 0) : edges(n), numedges(0), nummultiedges(0), _domain_size(n) { for(int i=0;i!=n;++i) { vertices.push_back(i); } } unsigned int domain_size() const { return _domain_size; } unsigned int num_vertices() const { return vertices.size(); } unsigned int num_edges() const { return numedges; } unsigned int num_underlying_edges() const { return numedges - nummultiedges; } unsigned int num_edges(unsigned int vertex) const { // this could also be cached. unsigned int count=0; for(edge_iterator i(edges[vertex].begin());i!=edges[vertex].end();++i) { count += i->second; } return count; } unsigned int num_underlying_edges(unsigned int vertex) const { return edges[vertex].size(); } unsigned int num_edges(unsigned int from, unsigned int to) const { T const &fset = edges[from]; typename T::const_iterator fend = fset.end(); // optimisation typename T::const_iterator i = fset.find(to); if(i != fend) { return i->second; } else { return 0; } } unsigned int num_multiedges() const { return nummultiedges; } bool is_multi_graph() const { return nummultiedges > 0; } // there is no add vertex! void clear(unsigned int v) { // Now, clear all edges involving v T &vset = edges[v]; // optimisation int_edge_iterator vend(vset.end()); // optimisation int_edge_iterator i(vset.begin()); for(;i!=vend;++i) { unsigned int k = i->second; nummultiedges -= (k - 1); numedges -= k; if(i->first != v) { edges[i->first].erase(v); } } edges[v] = T(); // save memory } void clearall() { for(vertex_iterator i(begin_verts());i!=end_verts();++i) { clear(*i); } } // remove vertex from graph void remove(unsigned int v) { vertices.remove(v); clear(v); } bool add_edge(unsigned int from, unsigned int to, unsigned int c) { numedges += c; // the following is a hack to check // whether the edge we're inserting // is already in the graph or not T &tos = edges[to]; // optimisation int_edge_iterator i = tos.find(from); if(i != tos.end()) { // edge already present so another multi-edge! nummultiedges += c; i->second += c; // don't want to increment same edge twice! if(from != to) { i = edges[from].find(to); i->second += c; } return true; } else { // completely new edge! nummultiedges += (c - 1); tos.insert(std::make_pair(from,c)); // self-loops only get one mention in the edge set if(from != to) { edges[from].insert(std::make_pair(to,c)); } return false; } } bool add_edge(unsigned int from, unsigned int to) { return add_edge(from,to,1); } bool remove_edge(unsigned int from, unsigned int to, unsigned int c) { T &fset = edges[from]; // optimisation typename T::iterator fend = fset.end(); // optimisation typename T::iterator i = fset.find(to); if(i != fend) { if(i->second > c) { // this is a multi-edge, so decrement count. nummultiedges -= c; numedges -= c; i->second -= c; if(from != to) { i = edges[to].find(from); i->second -= c; } } else { // clear our ALL edges numedges -= i->second; nummultiedges -= (i->second - 1); fset.erase(to); if(from != to) { edges[to].erase(from); } } return true; } return false; } unsigned int remove_all_edges(unsigned int from, unsigned int to) { // remove all edges "from--to" unsigned int r=0; T &fset = edges[from]; // optimisation typename T::iterator fend = fset.end(); // optimisation typename T::iterator i = fset.find(to); if(i != fend) { r = i->second; numedges -= r; nummultiedges -= (r - 1); fset.erase(to); if(from != to) { edges[to].erase(from); } } return r; } bool remove_edge(unsigned int from, unsigned int to) { return remove_edge(from,to,1); } void remove(adjacency_list<T> const &g) { for(vertex_iterator i(g.begin_verts());i!=g.end_verts();++i) { for(edge_iterator j(g.begin_edges(*i));j!=g.end_edges(*i);++j) { if(*i >= j->first) { remove_edge(*i,j->first,j->second); } } } } // Ok, this implementation is seriously inefficient! // could use an indirection trick here as one solution? // // POST: vertex 'from' remains, whilst vertex 'to' is removed void contract_edge(unsigned int from, unsigned int to) { if(from == to) { throw std::runtime_error("cannot contract a loop!"); } for(edge_iterator i(begin_edges(to));i!=end_edges(to);++i) { if(i->first == to) { // is self loop add_edge(from,from,i->second); } else { add_edge(from,i->first,i->second); } } remove(to); } // Ok, this implementation is seriously inefficient! // could use an indirection trick here as one solution? // // POST: vertex 'from' remains, whilst vertex 'to' is removed void simple_contract_edge(unsigned int from, unsigned int to) { if(from == to) { throw std::runtime_error("cannot contract a loop!"); } for(edge_iterator i(begin_edges(to));i!=end_edges(to);++i) { if(from != i->first && num_edges(from,i->first) == 0) { add_edge(from,i->first,1); } } remove(to); } vertex_iterator begin_verts() const { return vertices.begin(); } vertex_iterator end_verts() const { return vertices.end(); } edge_iterator begin_edges(int f) const { return edges[f].begin(); } edge_iterator end_edges(int f) const { return edges[f].end(); } }; #endif
29.153191
89
0.62531
DavePearce
cb8965a817a3343072699b5849d6c0b181368995
2,034
cpp
C++
aws-cpp-sdk-servicediscovery/source/model/RegisterInstanceRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-servicediscovery/source/model/RegisterInstanceRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-servicediscovery/source/model/RegisterInstanceRequest.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/servicediscovery/model/RegisterInstanceRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ServiceDiscovery::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; RegisterInstanceRequest::RegisterInstanceRequest() : m_serviceIdHasBeenSet(false), m_instanceIdHasBeenSet(false), m_creatorRequestId(Aws::Utils::UUID::RandomUUID()), m_creatorRequestIdHasBeenSet(true), m_attributesHasBeenSet(false) { } Aws::String RegisterInstanceRequest::SerializePayload() const { JsonValue payload; if(m_serviceIdHasBeenSet) { payload.WithString("ServiceId", m_serviceId); } if(m_instanceIdHasBeenSet) { payload.WithString("InstanceId", m_instanceId); } if(m_creatorRequestIdHasBeenSet) { payload.WithString("CreatorRequestId", m_creatorRequestId); } if(m_attributesHasBeenSet) { JsonValue attributesJsonMap; for(auto& attributesItem : m_attributes) { attributesJsonMap.WithString(attributesItem.first, attributesItem.second); } payload.WithObject("Attributes", std::move(attributesJsonMap)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection RegisterInstanceRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Route53AutoNaming_v20170314.RegisterInstance")); return headers; }
25.111111
109
0.757129
curiousjgeorge
cb8b45308458bc5023eb27b83893519bd5627e5b
1,198
cc
C++
plog/smodels-2.34/examples/example3.cc
bu-air-lab/POMDP-Dialog-Manager-Language-Learning
36731060d970003944532395275c85453265aba8
[ "MIT" ]
2
2018-10-01T07:04:24.000Z
2019-04-01T14:45:14.000Z
plog/smodels-2.34/examples/example3.cc
bu-air-lab/POMDP-Dialog-Manager-Language-Learning
36731060d970003944532395275c85453265aba8
[ "MIT" ]
null
null
null
plog/smodels-2.34/examples/example3.cc
bu-air-lab/POMDP-Dialog-Manager-Language-Learning
36731060d970003944532395275c85453265aba8
[ "MIT" ]
2
2018-10-01T06:14:53.000Z
2018-10-16T21:39:42.000Z
// Compute the stable models of the program // a :- not b. // b :- not a. // Then add the rule // a :- b. // and compute the stable models of the resulting program. #include <iostream> #include "smodels.h" #include "api.h" #include "atomrule.h" int main () { Smodels smodels; Api api (&smodels.program); Atom *a = api.new_atom (); Atom *b = api.new_atom (); api.set_name (a, "a"); api.set_name (b, "b"); // a :- not b. api.begin_rule (BASICRULE); api.add_head (a); api.add_body (b, false); api.end_rule (); // b :- not a. api.begin_rule (BASICRULE); api.add_head (b); api.add_body (a, false); api.end_rule (); // Copy the program Smodels smodels2; Api api2 (&smodels2.program); api2.copy (&api); api2.done (); // a :- b. api.begin_rule (BASICRULE); api.add_head (a); api.add_body (b, true); api.end_rule (); api.done (); // Find the models of the smaller program smodels2.program.print (); smodels2.init (); while (smodels2.model ()) smodels2.printAnswer (); // Find the models of the larger program smodels.program.print (); smodels.init (); while (smodels.model ()) smodels.printAnswer (); return 0; }
21.017544
58
0.617696
bu-air-lab
cb8bd1ec4ca35823105caf34293db97eb68b499f
6,811
hpp
C++
game/gamecontroller.hpp
edwinkepler/chessman
f9ffb902ce91c15726b8716665707d178ac734e1
[ "MIT" ]
null
null
null
game/gamecontroller.hpp
edwinkepler/chessman
f9ffb902ce91c15726b8716665707d178ac734e1
[ "MIT" ]
14
2017-08-28T15:37:20.000Z
2017-09-20T09:15:43.000Z
game/gamecontroller.hpp
edwinkepler/chessman
f9ffb902ce91c15726b8716665707d178ac734e1
[ "MIT" ]
null
null
null
/** * @copyright 2017 Edwin Kepler * @license MIT */ #ifndef GAMECONTROLLER_HPP #define GAMECONTROLLER_HPP #include <utility> #include <vector> #include <chrono> #include <memory> #include <exception> #include "pieces/pawn.hpp" #include "pieces/rook.hpp" #include "pieces/knight.hpp" #include "pieces/bishop.hpp" #include "pieces/queen.hpp" #include "pieces/king.hpp" #include "player.hpp" #include "history.hpp" #include "board.hpp" #include "debug/log.hpp" /** * @brief This namespace contains main interface for game of chess. */ namespace Game { /** * @brief Main inteerface for game of chess. * @details This class is a main interface, way of controlling game. It is * keeping track of movement, state of current match and plays. */ class GameController { public: /** * @brief Constructor * @details Prepare all pieces by placing them on board. */ GameController(); /** * @brief Decnstructor * @details Delete all pieces, board, players and any other objects * created during playing the game. */ ~GameController(); /** * @brief Returns pointer to Chessman::Board. * @return Pointer to Chessman::Board. */ shared_ptr<Chessboard::Board> chessboard(); /** * @brief Returns pointer to Chessplayer::Player of a given side. * @param Enum Chessplayer::SIDE. * @return Pointer to Chessplayer::Player. * @throw invalid_argument if argument is not one of Chessplayer::SIDE. */ shared_ptr<Chessplayer::Player> player(int); /** * @brief Returns Chessplayer::SIDE of a player that turn is currently in * play. * @return Chessplayer::SIDE. */ int current_player(); /** * @brief Return history of moves. * @return Vector of strings containing history of moves. */ vector<string> moves_history(); /** * @brief Will move piece. * @details Move will be identified and if anything but invalid move will * happen. Pieces are moved on Chessboard::Board and board will * check if arguments are valid (exception will be thrown if * not). * @param Pair of coordinates (x, y) as a integers of moved piece. * @param Pair of destination (x, y) as a integers of a destination. * @return Chessman::MOVE type of the move. */ int move(const pair<int, int>&, const pair<int, int>&); /** * @brief Will move piece. * @details Move will be identified and if anything but invalid move will * happen. Pieces are moved on Chessboard::Board and board will * check if arguments are valid (exception will be thrown if * not). * @param Pair of coordinates (x, y) as a char and int of moved piece. * @param Pair of destination (x, y) as a char and int of a destination. * @return Chessman::MOVE type of the move. */ int move(const pair<char, int>&, const pair<char, int>&); /** * @brief Checkmate check. * @return Game::MODIFICATION */ const int checkmate(); /** TODO */ int promotion(); private: const void add_moves_to_pieces(shared_ptr<Chessboard::Board>, const shared_ptr<Chessman::Piece>); /** * @brief Player currently playing his turn. */ int i_curr_player = 0; History hist; shared_ptr<Chessboard::Board> board {new Chessboard::Board()}; shared_ptr<Chessplayer::Player> play_white {new Chessplayer::Player("Player1", 0)}; shared_ptr<Chessplayer::Player> play_black {new Chessplayer::Player("Player2", 1)}; shared_ptr<Chessman::Pawn> pawn_w_1 {new Chessman::Pawn(0, make_pair(1, 2))}; shared_ptr<Chessman::Pawn> pawn_w_2 {new Chessman::Pawn(0, make_pair(2, 2))}; shared_ptr<Chessman::Pawn> pawn_w_3 {new Chessman::Pawn(0, make_pair(3, 2))}; shared_ptr<Chessman::Pawn> pawn_w_4 {new Chessman::Pawn(0, make_pair(4, 2))}; shared_ptr<Chessman::Pawn> pawn_w_5 {new Chessman::Pawn(0, make_pair(5, 2))}; shared_ptr<Chessman::Pawn> pawn_w_6 {new Chessman::Pawn(0, make_pair(6, 2))}; shared_ptr<Chessman::Pawn> pawn_w_7 {new Chessman::Pawn(0, make_pair(7, 2))}; shared_ptr<Chessman::Pawn> pawn_w_8 {new Chessman::Pawn(0, make_pair(8, 2))}; shared_ptr<Chessman::Rook> rook_w_1 {new Chessman::Rook(0, make_pair(1, 1))}; shared_ptr<Chessman::Rook> rook_w_2 {new Chessman::Rook(0, make_pair(8, 1))}; shared_ptr<Chessman::Knight> knight_w_1 {new Chessman::Knight(0, make_pair(2, 1))}; shared_ptr<Chessman::Knight> knight_w_2 {new Chessman::Knight(0, make_pair(7, 1))}; shared_ptr<Chessman::Bishop> bishop_w_1 {new Chessman::Bishop(0, make_pair(3, 1))}; shared_ptr<Chessman::Bishop> bishop_w_2 {new Chessman::Bishop(0, make_pair(6, 1))}; shared_ptr<Chessman::Queen> queen_w {new Chessman::Queen(0, make_pair(4, 1))}; shared_ptr<Chessman::King> king_w {new Chessman::King(0, make_pair(5, 1))}; shared_ptr<Chessman::Pawn> pawn_b_1 {new Chessman::Pawn(1, make_pair(1, 7))}; shared_ptr<Chessman::Pawn> pawn_b_2 {new Chessman::Pawn(1, make_pair(2, 7))}; shared_ptr<Chessman::Pawn> pawn_b_3 {new Chessman::Pawn(1, make_pair(3, 7))}; shared_ptr<Chessman::Pawn> pawn_b_4 {new Chessman::Pawn(1, make_pair(4, 7))}; shared_ptr<Chessman::Pawn> pawn_b_5 {new Chessman::Pawn(1, make_pair(5, 7))}; shared_ptr<Chessman::Pawn> pawn_b_6 {new Chessman::Pawn(1, make_pair(6, 7))}; shared_ptr<Chessman::Pawn> pawn_b_7 {new Chessman::Pawn(1, make_pair(7, 7))}; shared_ptr<Chessman::Pawn> pawn_b_8 {new Chessman::Pawn(1, make_pair(8, 7))}; shared_ptr<Chessman::Rook> rook_b_1 {new Chessman::Rook(1, make_pair(1, 8))}; shared_ptr<Chessman::Rook> rook_b_2 {new Chessman::Rook(1, make_pair(8, 8))}; shared_ptr<Chessman::Knight> knight_b_1 {new Chessman::Knight(1, make_pair(2, 8))}; shared_ptr<Chessman::Knight> knight_b_2 {new Chessman::Knight(1, make_pair(7, 8))}; shared_ptr<Chessman::Bishop> bishop_b_1 {new Chessman::Bishop(1, make_pair(3, 8))}; shared_ptr<Chessman::Bishop> bishop_b_2 {new Chessman::Bishop(1, make_pair(6, 8))}; shared_ptr<Chessman::Queen> queen_b {new Chessman::Queen(1, make_pair(4, 8))}; shared_ptr<Chessman::King> king_b {new Chessman::King(1, make_pair(5, 8))}; Debug::Log log; }; } #endif // GAMECONTROLLER_HPP
42.836478
105
0.621495
edwinkepler
cb8cb68d022aa88ea0c8d034260350a5fc42ecc5
1,235
cc
C++
src/tint/writer/wgsl/generator_bench.cc
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
9
2021-11-05T11:08:14.000Z
2022-03-18T05:14:34.000Z
src/tint/writer/wgsl/generator_bench.cc
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
2
2021-12-01T05:08:59.000Z
2022-02-18T08:14:30.000Z
src/tint/writer/wgsl/generator_bench.cc
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
1
2022-02-11T17:39:44.000Z
2022-02-11T17:39:44.000Z
// Copyright 2022 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include "src/tint/bench/benchmark.h" namespace tint::writer::wgsl { namespace { void GenerateWGSL(benchmark::State& state, std::string input_name) { auto res = bench::LoadProgram(input_name); if (auto err = std::get_if<bench::Error>(&res)) { state.SkipWithError(err->msg.c_str()); return; } auto& program = std::get<bench::ProgramAndFile>(res).program; for (auto _ : state) { auto res = Generate(&program, {}); if (!res.error.empty()) { state.SkipWithError(res.error.c_str()); } } } TINT_BENCHMARK_WGSL_PROGRAMS(GenerateWGSL); } // namespace } // namespace tint::writer::wgsl
30.121951
75
0.703644
hexops
cb8d7390dd77b15cc5ad0ee09628f74470787436
10,073
cpp
C++
src/ScreenOptionsManageEditSteps.cpp
fpmuniz/stepmania
984dc8668f1fedacf553f279a828acdebffc5625
[ "MIT" ]
1,514
2015-01-02T17:00:28.000Z
2022-03-30T14:11:21.000Z
src/ScreenOptionsManageEditSteps.cpp
fpmuniz/stepmania
984dc8668f1fedacf553f279a828acdebffc5625
[ "MIT" ]
1,462
2015-01-01T10:53:29.000Z
2022-03-27T04:35:53.000Z
src/ScreenOptionsManageEditSteps.cpp
fpmuniz/stepmania
984dc8668f1fedacf553f279a828acdebffc5625
[ "MIT" ]
552
2015-01-02T05:34:41.000Z
2022-03-26T05:19:19.000Z
#include "global.h" #include "ScreenOptionsManageEditSteps.h" #include "ScreenManager.h" #include "RageLog.h" #include "GameState.h" #include "SongManager.h" #include "ScreenTextEntry.h" #include "ScreenPrompt.h" #include "GameManager.h" #include "Steps.h" #include "ScreenMiniMenu.h" #include "RageUtil.h" #include "RageFileManager.h" #include "LocalizedString.h" #include "OptionRowHandler.h" #include "SongUtil.h" #include "Song.h" #include "ProfileManager.h" #include "Profile.h" #include "SpecialFiles.h" #include "NotesWriterSM.h" AutoScreenMessage( SM_BackFromRename ); AutoScreenMessage( SM_BackFromDelete ); AutoScreenMessage( SM_BackFromContextMenu ); enum StepsEditAction { StepsEditAction_Edit, StepsEditAction_Rename, StepsEditAction_Delete, NUM_StepsEditAction }; static const char *StepsEditActionNames[] = { "Edit", "Rename", "Delete", }; XToString( StepsEditAction ); /** @brief Loop through each StepsEditAction. */ #define FOREACH_StepsEditAction( i ) FOREACH_ENUM( StepsEditAction, i ) static MenuDef g_TempMenu( "ScreenMiniMenuContext" ); REGISTER_SCREEN_CLASS( ScreenOptionsManageEditSteps ); void ScreenOptionsManageEditSteps::Init() { ScreenOptions::Init(); CREATE_NEW_SCREEN.Load( m_sName, "CreateNewScreen" ); } void ScreenOptionsManageEditSteps::BeginScreen() { // Reload so that we're consistent with the disk in case the user has been dinking around with their edits. SONGMAN->FreeAllLoadedFromProfile( ProfileSlot_Machine ); SONGMAN->LoadStepEditsFromProfileDir( PROFILEMAN->GetProfileDir(ProfileSlot_Machine), ProfileSlot_Machine ); SONGMAN->LoadCourseEditsFromProfileDir( PROFILEMAN->GetProfileDir(ProfileSlot_Machine), ProfileSlot_Machine ); GAMESTATE->m_pCurSong.Set(nullptr); GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); vector<OptionRowHandler*> vHands; int iIndex = 0; { vHands.push_back( OptionRowHandlerUtil::MakeNull() ); OptionRowDefinition &def = vHands.back()->m_Def; def.m_layoutType = LAYOUT_SHOW_ONE_IN_ROW; def.m_bOneChoiceForAllPlayers = true; def.m_sName = "Create New Edit Steps"; def.m_sExplanationName = "Create New Edit Steps"; def.m_vsChoices.clear(); def.m_vsChoices.push_back( "" ); iIndex++; } SONGMAN->GetStepsLoadedFromProfile( m_vpSteps, ProfileSlot_Machine ); for (Steps const *s : m_vpSteps) { vHands.push_back( OptionRowHandlerUtil::MakeNull() ); OptionRowDefinition &def = vHands.back()->m_Def; Song *pSong = s->m_pSong; def.m_sName = pSong->GetTranslitFullTitle() + " - " + s->GetDescription(); def.m_bAllowThemeTitle = false; // not themable def.m_sExplanationName = "Select Edit Steps"; def.m_vsChoices.clear(); StepsType st = s->m_StepsType; RString sType = GAMEMAN->GetStepsTypeInfo(st).GetLocalizedString(); def.m_vsChoices.push_back( sType ); def.m_bAllowThemeItems = false; // already themed iIndex++; } ScreenOptions::InitMenu( vHands ); ScreenOptions::BeginScreen(); // select the last chosen course if( GAMESTATE->m_pCurSteps[PLAYER_1] ) { vector<Steps*>::const_iterator iter = find( m_vpSteps.begin(), m_vpSteps.end(), GAMESTATE->m_pCurSteps[PLAYER_1] ); if( iter != m_vpSteps.end() ) { iIndex = iter - m_vpSteps.begin(); this->MoveRowAbsolute( PLAYER_1, 1 + iIndex ); } } AfterChangeRow( PLAYER_1 ); } static LocalizedString THESE_STEPS_WILL_BE_LOST ("ScreenOptionsManageEditSteps", "These steps will be lost permanently."); static LocalizedString CONTINUE_WITH_DELETE ("ScreenOptionsManageEditSteps", "Continue with delete?"); static LocalizedString ENTER_NAME_FOR_STEPS ("ScreenOptionsManageEditSteps", "Enter a name for these steps."); void ScreenOptionsManageEditSteps::HandleScreenMessage( const ScreenMessage SM ) { if( SM == SM_GoToNextScreen ) { int iCurRow = m_iCurrentRow[GAMESTATE->GetMasterPlayerNumber()]; if( iCurRow == 0 ) // "create new" { SCREENMAN->SetNewScreen( CREATE_NEW_SCREEN ); return; // don't call base } else if( m_pRows[iCurRow]->GetRowType() == OptionRow::RowType_Exit ) { this->HandleScreenMessage( SM_GoToPrevScreen ); return; // don't call base } else // a Steps { Steps *pSteps = GAMESTATE->m_pCurSteps[PLAYER_1]; ASSERT( pSteps != nullptr ); const Style *pStyle = GAMEMAN->GetEditorStyleForStepsType( pSteps->m_StepsType ); GAMESTATE->SetCurrentStyle( pStyle, PLAYER_INVALID ); // do base behavior } } else if( SM == SM_BackFromRename ) { if( !ScreenTextEntry::s_bCancelledLast ) { ASSERT( ScreenTextEntry::s_sLastAnswer != "" ); // validate should have assured this Steps *pSteps = GAMESTATE->m_pCurSteps[PLAYER_1]; Song *pSong = pSteps->m_pSong; RString sOldDescription = pSteps->GetDescription(); pSteps->SetDescription( ScreenTextEntry::s_sLastAnswer ); RString sError; if( !NotesWriterSM::WriteEditFileToMachine(pSong,pSteps,sError) ) { ScreenPrompt::Prompt( SM_None, sError ); return; } SCREENMAN->SetNewScreen( this->m_sName ); // reload } } else if( SM == SM_BackFromDelete ) { if( ScreenPrompt::s_LastAnswer == ANSWER_YES ) { LOG->Trace( "Delete successful; deleting Steps from memory" ); Steps *pSteps = GetStepsWithFocus(); FILEMAN->Remove( pSteps->GetFilename() ); SONGMAN->DeleteSteps( pSteps ); GAMESTATE->m_pCurSteps[PLAYER_1].Set(nullptr); SCREENMAN->SetNewScreen( this->m_sName ); // reload } } else if( SM == SM_BackFromContextMenu ) { if( !ScreenMiniMenu::s_bCancelled ) { switch( ScreenMiniMenu::s_iLastRowCode ) { case StepsEditAction_Edit: { Steps *pSteps = GetStepsWithFocus(); Song *pSong = pSteps->m_pSong; GAMESTATE->m_pCurSong.Set( pSong ); GAMESTATE->m_pCurSteps[PLAYER_1].Set( pSteps ); ScreenOptions::BeginFadingOut(); } break; case StepsEditAction_Rename: { ScreenTextEntry::TextEntry( SM_BackFromRename, ENTER_NAME_FOR_STEPS, GAMESTATE->m_pCurSteps[PLAYER_1]->GetDescription(), MAX_STEPS_DESCRIPTION_LENGTH, SongUtil::ValidateCurrentEditStepsDescription ); } break; case StepsEditAction_Delete: { ScreenPrompt::Prompt( SM_BackFromDelete, THESE_STEPS_WILL_BE_LOST.GetValue()+"\n\n"+CONTINUE_WITH_DELETE.GetValue(), PROMPT_YES_NO, ANSWER_NO ); } break; } } } else if( SM == SM_LoseFocus ) { this->PlayCommand( "ScreenLoseFocus" ); } else if( SM == SM_GainFocus ) { this->PlayCommand( "ScreenGainFocus" ); } ScreenOptions::HandleScreenMessage( SM ); } void ScreenOptionsManageEditSteps::AfterChangeRow( PlayerNumber pn ) { Steps *pSteps = GetStepsWithFocus(); Song *pSong = pSteps ? pSteps->m_pSong : nullptr; GAMESTATE->m_pCurSong.Set( pSong ); GAMESTATE->m_pCurSteps[PLAYER_1].Set( pSteps ); ScreenOptions::AfterChangeRow( pn ); } static LocalizedString YOU_HAVE_MAX_STEP_EDITS( "ScreenOptionsManageEditSteps", "You have %d step edits, the maximum number allowed." ); static LocalizedString YOU_MUST_DELETE( "ScreenOptionsManageEditSteps", "You must delete an existing steps edit before creating a new steps edit." ); void ScreenOptionsManageEditSteps::ProcessMenuStart( const InputEventPlus & ) { if( IsTransitioning() ) return; int iCurRow = m_iCurrentRow[GAMESTATE->GetMasterPlayerNumber()]; if( iCurRow == 0 ) // "create new" { vector<Steps*> v; SONGMAN->GetStepsLoadedFromProfile( v, ProfileSlot_Machine ); if( v.size() >= size_t(MAX_EDIT_STEPS_PER_PROFILE) ) { RString s = ssprintf( YOU_HAVE_MAX_STEP_EDITS.GetValue()+"\n\n"+YOU_MUST_DELETE.GetValue(), MAX_EDIT_STEPS_PER_PROFILE ); ScreenPrompt::Prompt( SM_None, s ); return; } SCREENMAN->PlayStartSound(); this->BeginFadingOut(); } else if( m_pRows[iCurRow]->GetRowType() == OptionRow::RowType_Exit ) { SCREENMAN->PlayStartSound(); this->BeginFadingOut(); } else // a Steps { g_TempMenu.rows.clear(); FOREACH_StepsEditAction( i ) { MenuRowDef mrd( i, StepsEditActionToString(i), true, EditMode_Home, true, true, 0, "" ); g_TempMenu.rows.push_back( mrd ); } int iWidth, iX, iY; this->GetWidthXY( PLAYER_1, iCurRow, 0, iWidth, iX, iY ); ScreenMiniMenu::MiniMenu( &g_TempMenu, SM_BackFromContextMenu, SM_BackFromContextMenu, (float)iX, (float)iY ); } } void ScreenOptionsManageEditSteps::ImportOptions( int iRow, const vector<PlayerNumber> &vpns ) { } void ScreenOptionsManageEditSteps::ExportOptions( int iRow, const vector<PlayerNumber> &vpns ) { } Steps *ScreenOptionsManageEditSteps::GetStepsWithFocus() const { int iCurRow = m_iCurrentRow[GAMESTATE->GetMasterPlayerNumber()]; if( iCurRow == 0 ) return nullptr; else if( m_pRows[iCurRow]->GetRowType() == OptionRow::RowType_Exit ) return nullptr; // a Steps int iStepsIndex = iCurRow - 1; return m_vpSteps[iStepsIndex]; } /* * (c) 2002-2005 Chris Danford * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
30.524242
149
0.733843
fpmuniz
cb8ddf542520e955b9dcb91110ad076090cdaf98
2,687
cpp
C++
lib/samp-plugin-sdk/amxplugin2.cpp
TommyB123/pawn-chrono
9e3a9237bff75c3191f5b1123c74abca07e11935
[ "MIT" ]
14
2018-06-03T03:05:21.000Z
2021-09-16T17:08:34.000Z
lib/samp-plugin-sdk/amxplugin2.cpp
TommyB123/pawn-chrono
9e3a9237bff75c3191f5b1123c74abca07e11935
[ "MIT" ]
6
2018-06-15T21:27:48.000Z
2021-08-18T11:51:02.000Z
lib/samp-plugin-sdk/amxplugin2.cpp
TommyB123/pawn-chrono
9e3a9237bff75c3191f5b1123c74abca07e11935
[ "MIT" ]
6
2018-08-13T01:33:32.000Z
2022-03-13T16:38:40.000Z
//---------------------------------------------------------- // // SA-MP Multiplayer Modification For GTA:SA // Copyright 2014 SA-MP Team, Dan, maddinat0r // //---------------------------------------------------------- #include <cstring> #include <cstdlib> //---------------------------------------------------------- #include <assert.h> //---------------------------------------------------------- #include "amx/amx2.h" //---------------------------------------------------------- int AMXAPI amx_PushAddress(AMX *amx, cell *address) { AMX_HEADER *hdr; unsigned char *data; cell xaddr; /* reverse relocate the address */ assert(amx != NULL); hdr = (AMX_HEADER *) amx->base; assert(hdr != NULL); assert(hdr->magic == AMX_MAGIC); data = (amx->data != NULL) ? amx->data : amx->base + (int) hdr->dat; xaddr = (cell) ((unsigned char*) address-data); if ((ucell) xaddr >= (ucell) amx->stp) { return AMX_ERR_MEMACCESS; } return amx_Push(amx,xaddr); } void AMXAPI amx_Redirect(AMX *amx, char *from, ucell to, AMX_NATIVE *store) { AMX_HEADER *hdr = (AMX_HEADER*) amx->base; AMX_FUNCSTUB *func; for (int idx = 0, num = NUMENTRIES(hdr, natives, libraries); idx != num; ++idx) { func = GETENTRY(hdr, natives, idx); if (!strcmp(from, GETENTRYNAME(hdr, func))) { if (store) { *store = (AMX_NATIVE) func->address; } func->address = to; return; } } } int AMXAPI amx_GetCString(AMX *amx, cell param, char *&dest) { cell *ptr; amx_GetAddr(amx, param, &ptr); int len; amx_StrLen(ptr, &len); dest = (char*) malloc((len + 1) * sizeof(char)); if (dest != NULL) { amx_GetString(dest, ptr, 0, UNLIMITED); dest[len] = 0; return len; } return 0; } int AMXAPI amx_SetCString(AMX *amx, cell param, const char *str, int len) { cell *dest; int error; if ((error = amx_GetAddr(amx, param, &dest)) != AMX_ERR_NONE) return error; return amx_SetString(dest, str, 0, 0, len); } #if defined __cplusplus std::string AMXAPI amx_GetCppString(AMX *amx, cell param) { cell *addr = nullptr; amx_GetAddr(amx, param, &addr); int len = 0; amx_StrLen(addr, &len); std::string string(len, ' '); amx_GetString(&string[0], addr, 0, len + 1); return string; } int AMXAPI amx_SetCppString(AMX *amx, cell param, const std::string &str, size_t maxlen) { cell *dest = nullptr; int error; if ((error = amx_GetAddr(amx, param, &dest)) != AMX_ERR_NONE) return error; return amx_SetString(dest, str.c_str(), 0, 0, maxlen); } #endif // __cplusplus //---------------------------------------------------------- // EOF
23.365217
89
0.534053
TommyB123
cb902a321ce496c9ee21bd3293c86d1e0afcb78b
2,257
cpp
C++
src/face2js.cpp
dreamdrive/ros_brave_face
935470be602d48a8a6e4706d223b4d5fcdeab5f7
[ "MIT" ]
1
2020-10-28T01:28:31.000Z
2020-10-28T01:28:31.000Z
src/face2js.cpp
dreamdrive/ros_brave_face
935470be602d48a8a6e4706d223b4d5fcdeab5f7
[ "MIT" ]
null
null
null
src/face2js.cpp
dreamdrive/ros_brave_face
935470be602d48a8a6e4706d223b4d5fcdeab5f7
[ "MIT" ]
null
null
null
// 20200925 // ファイバリオン用頭部、顔追従プログラムノード (口はジョイスティックで動く) // Face2jointstates #include "ros/ros.h" #include "ros/time.h" #include "opencv_apps/FaceArrayStamped.h" #include "sensor_msgs/JointState.h" #include <sensor_msgs/Joy.h> #define SV_CNT 3 double face_x = 0; double face_y = 0; double mouse = 0; sensor_msgs::JointState js_robot; void face_callback(const opencv_apps::FaceArrayStamped::ConstPtr& facearraystamped) { face_x = 0; // 未検出のときは0 face_y = 0; // 未検出のときは0 if ( facearraystamped->faces.size() > 0 ){ face_x = facearraystamped->faces[0].face.x; face_y = facearraystamped->faces[0].face.y; } } void joy_callback(const sensor_msgs::Joy& joy_msg) { mouse = joy_msg.axes[1]; } int main(int argc, char **argv) { int i; ros::init(argc, argv, "face2js"); // ノードの初期化 ros::NodeHandle nh; // ノードハンドラ // サブスクライバの作成 ros::Subscriber sub_face = nh.subscribe("/face_detection/faces", 10, face_callback); ros::Subscriber sub_joy = nh.subscribe("joy", 10, joy_callback); // joint_stateのパブリッシャ ros::Publisher pub_js= nh.advertise<sensor_msgs::JointState>("/robot/joint_states",10); // JointStateの初期化 js_robot.header.frame_id = "base_link"; js_robot.name.resize(SV_CNT); js_robot.name[0] = "face_pitch"; js_robot.name[1] = "face_yaw"; js_robot.name[2] = "mouth"; js_robot.position.resize(SV_CNT); for(i=0;i<SV_CNT;i++){ // 値初期化 js_robot.position[i] = 0.0; } ros::Rate loop_rate(30); // 制御周期30Hz while(ros::ok()) { if ((face_x == 0)&&(face_y == 0)){ // 顔を未検出のとき (たまたま(0,0)のときは、(^^;A)) ROS_INFO("Not found face"); } else{ // 顔を検出したとき ROS_INFO("found face !! | Face = (%f , %f)",face_x,face_y); //JointStateの生成 js_robot.header.stamp = ros::Time::now(); js_robot.position[0] = M_PI * ((face_y - 240) / 240 ) /6 ; // ピッチ -30度〜30度 js_robot.position[1] = -M_PI * ((face_x - 320) / 320 ) /3 ; // ヨー -60度〜60度 } js_robot.position[2] = M_PI * mouse / 18 ; // 口の動き -10度〜10度 // joint stateの配信 pub_js.publish(js_robot); ros::spinOnce(); // コールバック関数を呼ぶ loop_rate.sleep(); } return 0; }
25.647727
89
0.607887
dreamdrive
cb92f211e92c8916f51a81482e7b764e4afff9f7
9,494
cpp
C++
mpi/tsp/tsp.cpp
fraguela/dparallel_recursion
30050242b7d01766fee5a3107c7a79db5c512d9e
[ "Apache-2.0" ]
3
2022-01-01T07:48:58.000Z
2022-01-25T14:01:35.000Z
mpi/tsp/tsp.cpp
fraguela/dparallel_recursion
30050242b7d01766fee5a3107c7a79db5c512d9e
[ "Apache-2.0" ]
null
null
null
mpi/tsp/tsp.cpp
fraguela/dparallel_recursion
30050242b7d01766fee5a3107c7a79db5c512d9e
[ "Apache-2.0" ]
null
null
null
/* dparallel_recursion: distributed parallel_recursion skeleton Copyright (C) 2015-2016 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna 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. */ /// /// \file tsp.cpp /// \author Carlos H. Gonzalez <cgonzalezv@udc.es> /// \author Basilio B. Fraguela <basilio.fraguela@udc.es> /// /* For copyright information, see olden_v1.0/COPYRIGHT */ #include "tsp.h" #include <mpi.h> #include <cstdlib> #include <cmath> extern void print_list(Tree t); //extern void print_tree(Tree t); /* communications */ void send(int dest_rank, int tag, Tree t) { assert(t->next != NULL); //only graphs alreay processed by tsp should be sent int i = 0; const tree *p = t; do { i++; p = p->next; } while( p != t); double *buf = (double *)malloc(sizeof(double) * 2 * i); assert(buf != NULL); double *bufptr = buf; p = t; do { *bufptr++ = p->x; *bufptr++ = p->y; p = p->next; } while( p != t); MPI_Send(buf, 2 * i, MPI_DOUBLE, dest_rank, tag, MPI_COMM_WORLD); free(buf); } void recv(int from_rank, int tag, Tree& data, MPI_Status& st) { int len; MPI_Probe(from_rank, tag, MPI_COMM_WORLD, &st); from_rank = st.MPI_SOURCE; tag = st.MPI_TAG; MPI_Get_count(&st, MPI_DOUBLE, &len); //printf("Recv %d doubles from %d with tag=%d\n", len, st.MPI_SOURCE, st.MPI_TAG); double *buf = (double *)malloc(sizeof(double) * len); MPI_Recv(buf, len, MPI_DOUBLE, from_rank, tag, MPI_COMM_WORLD, &st); len /= 2; data = new tree[len]; for(int i=0; i < len; ++i) { tree& p = data[i]; p.x = buf[2 * i]; p.y = buf[2 * i + 1]; p.next = data + ((i == (len - 1)) ? 0 : (i + 1)); p.prev = data + ((i ? i : len) - 1); p.left = NULL; p.right = NULL; } free(buf); } /* end communications */ /* Find Euclidean distance from a to b */ double distance(Tree a, Tree b) { double ax, ay, bx, by; ax = a->x; ay = a->y; bx = b->x; by = b->y; return (sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by))); } /* sling tree nodes into a list -- requires root to be tail of list */ /* only fills in next field, not prev */ Tree makelist(Tree t) { Tree left, right; Tree tleft, tright; Tree retval = t; if (!t) return NULL; left = makelist(t->left); /* head of left list */ right = makelist(t->right); /* head of right list */ if (right) { retval = right; tright = t->right; tright->next = t; } if (left) { retval = left; tleft = t->left; tleft->next = (right) ? right : t; } t->next = NULL; return retval; } /* reverse orientation of list */ void reverse(Tree t) { Tree prev, back, next, tmp; if (!t) return; prev = t->prev; prev->next = NULL; t->prev = NULL; back = t; tmp = t; for (t = t->next; t; back = t, t = next) { next = t->next; t->next = back; back->prev = t; } tmp->next = prev; prev->prev = tmp; /*printf("REVERSE result\n");*/ /*print_list(tmp);*/ /*printf("End REVERSE\n");*/ } /* Use closest-point heuristic from Cormen Leiserson and Rivest */ Tree conquer(Tree t) { Tree cycle, tmp, min, prev, next, donext; double mindist, test; double mintonext, mintoprev, ttonext, ttoprev; if (!t) return NULL; t = makelist(t); cycle = t; t = t->next; cycle->next = cycle; cycle->prev = cycle; for (; t; t = donext) { /* loop over remaining points */ donext = t->next; /* value won't be around later */ min = cycle; mindist = distance(t, cycle); for (tmp = cycle->next; tmp != cycle; tmp = tmp->next) { test = distance(tmp, t); if (test < mindist) { mindist = test; min = tmp; } /* if */ } /* for tmp... */ next = min->next; prev = min->prev; mintonext = distance(min, next); mintoprev = distance(min, prev); ttonext = distance(t, next); ttoprev = distance(t, prev); if ((ttoprev - mintoprev) < (ttonext - mintonext)) { /* insert between min and prev */ prev->next = t; t->next = min; t->prev = prev; min->prev = t; } else { next->prev = t; t->next = next; min->next = t; t->prev = min; } } /* for t... */ return cycle; } /* Merge two cycles as per Karp */ Tree merge(Tree a, Tree b, Tree t) { //t->left = t->right = a->left = a->right = b->left = b->right = NULL; Tree min, next, prev, tmp; double mindist, test, mintonext, mintoprev, ttonext, ttoprev; Tree n1, p1, n2, p2; double tton1, ttop1, tton2, ttop2; double n1ton2, n1top2, p1ton2, p1top2; int choice; //printf("Merging [%p]\n", t); /* Compute location for first cycle */ min = a; mindist = distance(t, a); tmp = a; for (a = a->next; a != tmp; a = a->next) { test = distance(a, t); if (test < mindist) { mindist = test; min = a; } /* if */ } /* for a... */ next = min->next; prev = min->prev; mintonext = distance(min, next); mintoprev = distance(min, prev); ttonext = distance(t, next); ttoprev = distance(t, prev); if ((ttoprev - mintoprev) < (ttonext - mintonext)) { /* would insert between min and prev */ p1 = prev; n1 = min; tton1 = mindist; ttop1 = ttoprev; } else { /* would insert between min and next */ p1 = min; n1 = next; ttop1 = mindist; tton1 = ttonext; } /* Compute location for second cycle */ min = b; mindist = distance(t, b); tmp = b; for (b = b->next; b != tmp; b = b->next) { test = distance(b, t); if (test < mindist) { mindist = test; min = b; } /* if */ } /* for tmp... */ next = min->next; prev = min->prev; mintonext = distance(min, next); mintoprev = distance(min, prev); ttonext = distance(t, next); ttoprev = distance(t, prev); if ((ttoprev - mintoprev) < (ttonext - mintonext)) { /* would insert between min and prev */ p2 = prev; n2 = min; tton2 = mindist; ttop2 = ttoprev; } else { /* would insert between min and next */ p2 = min; n2 = next; ttop2 = mindist; tton2 = ttonext; } /* Now we have 4 choices to complete: 1:t,p1 t,p2 n1,n2 2:t,p1 t,n2 n1,p2 3:t,n1 t,p2 p1,n2 4:t,n1 t,n2 p1,p2 */ n1ton2 = distance(n1, n2); n1top2 = distance(n1, p2); p1ton2 = distance(p1, n2); p1top2 = distance(p1, p2); mindist = ttop1 + ttop2 + n1ton2; choice = 1; test = ttop1 + tton2 + n1top2; if (test < mindist) { choice = 2; mindist = test; } test = tton1 + ttop2 + p1ton2; if (test < mindist) { choice = 3; mindist = test; } test = tton1 + tton2 + p1top2; if (test < mindist) choice = 4; /*chatting("p1,n1,t,p2,n2 0x%x,0x%x,0x%x,0x%x,0x%x\n",p1,n1,t,p2,n2);*/ switch (choice) { case 1: /* 1:p1,t t,p2 n2,n1 -- reverse 2!*/ /*reverse(b);*/ reverse(n2); p1->next = t; t->prev = p1; t->next = p2; p2->prev = t; n2->next = n1; n1->prev = n2; break; case 2: /* 2:p1,t t,n2 p2,n1 -- OK*/ p1->next = t; t->prev = p1; t->next = n2; n2->prev = t; p2->next = n1; n1->prev = p2; break; case 3: /* 3:p2,t t,n1 p1,n2 -- OK*/ p2->next = t; t->prev = p2; t->next = n1; n1->prev = t; p1->next = n2; n2->prev = p1; break; case 4: /* 4:n1,t t,n2 p2,p1 -- reverse 1!*/ /*reverse(a);*/ reverse(n1); n1->next = t; t->prev = n1; t->next = n2; n2->prev = t; p2->next = p1; p1->prev = p2; break; } return t; } /* Compute TSP for the tree t -- use conquer for problems <= sz */ Tree tsp(Tree t, int sz) { Tree leftval, rightval; if (t->sz <= sz) return conquer(t); leftval = tsp(t->left, sz); rightval = tsp(t->right, sz); return merge(leftval, rightval, t); } //partition_row_count could have also been reused with an extern declaration int tsp_partition_row_count = 0; Tree tsp_top(Tree t, int sz) { Tree leftval, rightval; //assumes no conquer at this level if ((t->sz / 2) == bottom_n ) { //printf("Pick bottom [%p]\n", t); leftval = partition_row[tsp_partition_row_count++]; rightval = partition_row[tsp_partition_row_count++]; } else { //printf("Pick children [%p]\n", t); leftval = tsp_top(t->left, sz); rightval = tsp_top(t->right, sz); } return merge(leftval, rightval, t); } Tree tsp(int rank, int nprocs, Tree t, int sz) { if (nprocs == 1) { return tsp(t, sz); } //assert(sz <= bottom_n); //conquer can only have happened at bottom_n or below for (int i = 0; i < myleaves; i++) { partition_row[myfirst_leaf + i] = tsp(partition_row[myfirst_leaf + i], sz); } //printf("r=%d myl=%d f=%d:\n", rank, myleaves, myfirst_leaf); if (rank) { for (int i = 0; i < myleaves; i++) { //print_list(partition_row[myfirst_leaf + i]); printf("Bye %d\n", rank); send(0, myfirst_leaf + i, partition_row[myfirst_leaf + i]); } return NULL; } else { Tree tmp; MPI_Status st; for (int i = 0; i < (nleaves - myleaves); i++) { recv(MPI_ANY_SOURCE, MPI_ANY_TAG, tmp, st); //print_list(tmp); //printf("setting %d\n", st.MPI_TAG); partition_row[st.MPI_TAG] = tmp; } //for (int i = 0; i < nleaves;i++) print_list(partition_row[i]); return 0; return tsp_top(t, sz); } }
22.604762
88
0.591426
fraguela
cb97a164bd3fe69862b66bc9a87a3fc41b1229a9
497
cpp
C++
Code full house/buoi8 - nguyen dinh trung duc-mang/bai11 cu dan lineland.cpp
ducyb2001/CbyTrungDuc
0e93394dce600876a098b90ae969575bac3788e1
[ "Apache-2.0" ]
null
null
null
Code full house/buoi8 - nguyen dinh trung duc-mang/bai11 cu dan lineland.cpp
ducyb2001/CbyTrungDuc
0e93394dce600876a098b90ae969575bac3788e1
[ "Apache-2.0" ]
null
null
null
Code full house/buoi8 - nguyen dinh trung duc-mang/bai11 cu dan lineland.cpp
ducyb2001/CbyTrungDuc
0e93394dce600876a098b90ae969575bac3788e1
[ "Apache-2.0" ]
null
null
null
/* bai 11 thanh pho Line Land */ #include<stdio.h> int min(int a, int b){ if(a<b) return a; return b; } int max(int a, int b){ if(a>b) return a; return b; } int main(){ int i,n; scanf("%d", &n); int a[n]; for(i=0; i<n;i++){ scanf("%d",&a[i]); }s for(i=0;i<n;i++){ if(i==0){ printf("%d %d\n", a[1]-a[0], a[n-1]-a[0]); } else if(i==n-1){ printf("%d %d\n", a[n-1]-a[n-2], a[n-1]-a[0]); } else printf("%d %d\n", min(a[i]-a[i-1], a[i+1]-a[i]), max(a[i]-a[0],a[n-1]-a[i])); } }
15.53125
83
0.474849
ducyb2001
cb989d5b0baf880de6daac4866f72e2ef4721c96
610
cpp
C++
UVa/686.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
UVa/686.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
UVa/686.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define MAXN 32768 using namespace std; int prime[100000]={2,3,5,7},primeNUM=4; int NUM[1000001]={0}; int main(){ for(int i=11;i<=MAXN;i++){ int judge=1; for(int j=0;judge&&prime[j]<=sqrt(i);j++){ if(i%prime[j]==0) judge=0; } if(judge){ prime[primeNUM++]=i; } } for(int i=0;i<primeNUM;i++){ NUM[prime[i]]++; } int N; cin>>N; while(N){ int i,judge=0; for(i=0;prime[i]<=N/2;i++){ if(NUM[N-prime[i]]){ judge++; } } if(judge){ printf("%d\n",judge); } else{ printf("Goldbach's conjecture is wrong.\n"); } cin>>N; } return 0; }
15.641026
47
0.544262
tico88612
cb99d03a67c1f22595ca5b7d90a55d0d34e8d596
3,092
cpp
C++
sim/FFT/fft_gen/bench/cpp/twoc.cpp
SebastianBraun01/vu_meter
131e632c388f39c37c539e9c5d5492b3f4cb2db6
[ "Apache-2.0" ]
null
null
null
sim/FFT/fft_gen/bench/cpp/twoc.cpp
SebastianBraun01/vu_meter
131e632c388f39c37c539e9c5d5492b3f4cb2db6
[ "Apache-2.0" ]
null
null
null
sim/FFT/fft_gen/bench/cpp/twoc.cpp
SebastianBraun01/vu_meter
131e632c388f39c37c539e9c5d5492b3f4cb2db6
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Filename: twoc.cpp // {{{ // Project: A General Purpose Pipelined FFT Implementation // // Purpose: Some various two's complement related C++ helper routines. // Specifically, these help extract signed numbers from // packed bitfields, while guaranteeing that the upper bits are properly // sign extended (or not) as desired. // // Creator: Dan Gisselquist, Ph.D. // Gisselquist Technology, LLC // //////////////////////////////////////////////////////////////////////////////// // }}} // Copyright (C) 2015-2021, Gisselquist Technology, LLC // {{{ // This program is free software (firmware): you can redistribute it and/or // modify it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, or (at // your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program. (It's in the $(ROOT)/doc directory. Run make with no // target there if the PDF file isn't present.) If not, see // <http://www.gnu.org/licenses/> for a copy. // }}} // License: GPL, v3, as defined and found on www.gnu.org, // {{{ // http://www.gnu.org/licenses/gpl.html // //////////////////////////////////////////////////////////////////////////////// // }}} #include <stdio.h> #include <assert.h> #include "twoc.h" long sbits(const long val, const int bits) { long r; r = val & ((1l<<bits)-1); if (r & (1l << (bits-1))) r |= (-1l << bits); return r; } unsigned long ubits(const long val, const int bits) { unsigned long r = val & ((1l<<bits)-1); return r; } unsigned long rndbits(const long val, const int bits_in, const int bits_out) { long s = sbits(val, bits_in); // Signed input value long t = s; // Truncated input value long r; // Result // printf("RNDBITS(%08lx, %d, %d)\n", val, bits_in, bits_out); // printf("S = %lx\n", s); // printf("T = %lx\n", t); // assert(bits_in > bits_out); if (bits_in == bits_out) r = s; else if (bits_in-1 == bits_out) { t = sbits(val>>1, bits_out); // printf("TEST! S = %ld, T = %ld\n", s, t); if (3 == (s&3)) t = t+1; r = t; } else { // A. 0XXXX.0xxxxx -> 0XXXX // B. 0XXX0.100000 -> 0XXX0; // C. 0XXX1.100000 -> 0XXX1+1; // D. 0XXXX.1zzzzz -> 0XXXX+1; // E. 1XXXX.0xxxxx -> 1XXXX // F. 1XXX0.100000 -> ??? XXX0; // G. 1XXX1.100000 -> ??? XXX1+1; // H. 1XXXX.1zzzzz -> 1XXXX+1; t = sbits(val>>(bits_in-bits_out), bits_out); // Truncated value if (0 == ((s >> (bits_in-bits_out-1))&1)) { // printf("A\n"); r = t; } else if (0 != (s & ((1<<(bits_in-bits_out-1))-1))) { // printf("D\n"); r = t+1; } else if (t&1) { // printf("C\n"); r = t+1; } else { // 3 ..?11 // printf("B\n"); r = t; } } return r; }
30.313725
80
0.570181
SebastianBraun01
ed806a15cb8396018711330adfc0ba80a74f8312
3,083
hpp
C++
include/UnityEngine/Experimental/Rendering/ScriptableRuntimeReflectionSystemSettings.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/Experimental/Rendering/ScriptableRuntimeReflectionSystemSettings.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/Experimental/Rendering/ScriptableRuntimeReflectionSystemSettings.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::Experimental::Rendering namespace UnityEngine::Experimental::Rendering { // Forward declaring type: ScriptableRuntimeReflectionSystemWrapper class ScriptableRuntimeReflectionSystemWrapper; // Forward declaring type: IScriptableRuntimeReflectionSystem class IScriptableRuntimeReflectionSystem; } // Completed forward declares // Type namespace: UnityEngine.Experimental.Rendering namespace UnityEngine::Experimental::Rendering { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.Experimental.Rendering.ScriptableRuntimeReflectionSystemSettings // [NativeHeaderAttribute] Offset: D9289C // [RequiredByNativeCodeAttribute] Offset: D9289C class ScriptableRuntimeReflectionSystemSettings : public ::Il2CppObject { public: // Creating value type constructor for type: ScriptableRuntimeReflectionSystemSettings ScriptableRuntimeReflectionSystemSettings() noexcept {} // Get static field: static private UnityEngine.Experimental.Rendering.ScriptableRuntimeReflectionSystemWrapper s_Instance static UnityEngine::Experimental::Rendering::ScriptableRuntimeReflectionSystemWrapper* _get_s_Instance(); // Set static field: static private UnityEngine.Experimental.Rendering.ScriptableRuntimeReflectionSystemWrapper s_Instance static void _set_s_Instance(UnityEngine::Experimental::Rendering::ScriptableRuntimeReflectionSystemWrapper* value); // static private System.Void set_Internal_ScriptableRuntimeReflectionSystemSettings_system(UnityEngine.Experimental.Rendering.IScriptableRuntimeReflectionSystem value) // Offset: 0x1B7CF2C static void set_Internal_ScriptableRuntimeReflectionSystemSettings_system(UnityEngine::Experimental::Rendering::IScriptableRuntimeReflectionSystem* value); // static private UnityEngine.Experimental.Rendering.ScriptableRuntimeReflectionSystemWrapper get_Internal_ScriptableRuntimeReflectionSystemSettings_instance() // Offset: 0x1B7D0A0 static UnityEngine::Experimental::Rendering::ScriptableRuntimeReflectionSystemWrapper* get_Internal_ScriptableRuntimeReflectionSystemSettings_instance(); // static private System.Void ScriptingDirtyReflectionSystemInstance() // Offset: 0x1B7D108 static void ScriptingDirtyReflectionSystemInstance(); // static private System.Void .cctor() // Offset: 0x1B7D13C static void _cctor(); }; // UnityEngine.Experimental.Rendering.ScriptableRuntimeReflectionSystemSettings #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Experimental::Rendering::ScriptableRuntimeReflectionSystemSettings*, "UnityEngine.Experimental.Rendering", "ScriptableRuntimeReflectionSystemSettings");
62.918367
189
0.798573
darknight1050
ed80d1cdae7a0ff0f958cc04a6bf80a89bbb6e48
3,962
cpp
C++
tests/lll/lll_test.cpp
pdx-cs-tutors/pdp
48622b1a4bdbf724795a1a6faed4ba1df16319a8
[ "MIT" ]
10
2017-04-25T05:01:19.000Z
2021-03-27T22:40:21.000Z
tests/lll/lll_test.cpp
pdx-cs-tutors/pdp
48622b1a4bdbf724795a1a6faed4ba1df16319a8
[ "MIT" ]
null
null
null
tests/lll/lll_test.cpp
pdx-cs-tutors/pdp
48622b1a4bdbf724795a1a6faed4ba1df16319a8
[ "MIT" ]
1
2019-02-02T23:39:46.000Z
2019-02-02T23:39:46.000Z
#include <sstream> #include "../include/lll_test.h" // Helper function to create a string representing an LLL given its head node // e.g. "[1 -> 2 -> 3]" std::string stringify(lll::node* head) { std::stringstream ss; ss << "["; while (head) { ss << head->data; if (head->next) ss << " -> "; head = head->next; } ss << "]"; return ss.str(); } // Helper function to deallocate LLL memory during tests void destroy_lll(lll::node* head) { while (head) { lll::node* temp = head->next; delete head; head = temp; } } /////////////// // LLL FAILURES /////////////// LLLFailure::LLLFailure(const char* description, std::string call, std::vector<int>& initial, std::initializer_list<int> expected, lll::node* actual) : BaseFailure(description, call, stringify(initial), stringify(expected), stringify(actual)) { } LLLFailure::LLLFailure(const LLLFailure& fail) : BaseFailure(fail) { } LLLReturnFailure::LLLReturnFailure(const char* description, std::string call, std::vector<int>& initial, int expected, int actual) : BaseFailure(description, call, stringify(initial), stringify(expected), stringify(actual)){ } LLLReturnFailure::LLLReturnFailure(const LLLReturnFailure& fail) : BaseFailure(fail) { } ////////////////// // CLL TEST SUITES ////////////////// void LLLTestSuite::addFailure(const LLLFailure& fail) { failures.push_back(new LLLFailure(fail)); } void LLLTestSuite::setUp() { head = nullptr; retval = nullptr; initial = {}; } void LLLTestSuite::tearDown() { if (head) destroy_lll(head); head = nullptr;// Verify that the nodes in the LLL match the given values // e.g. expectList(head, {1, 2, 3}); // Add failures if there are discrepancies if (retval) delete retval; retval = nullptr; } LLLTestSuite::~LLLTestSuite() { } // Verify that the nodes in the LLL under test match the given values // e.g. expectList({1, 2, 3}); // Add failures if there are discrepancies void LLLTestSuite::expectList(std::initializer_list<int> values) { lll::node* curr = head; int count = 0; for (auto value : values) { if (!curr) { addFailure(LLLFailure( "Missing item(s)", call, initial, values, head )); return; } else if (curr->data != value) { addFailure(LLLFailure( "Incorrect value(s)", call, initial, values, head )); return; } ++count; curr = curr->next; } if (curr) { addFailure(LLLFailure( "Too many items", call, initial, values, head )); } } // Verify that an LLL function has returned the expected value // e.g. expectReturn(1); // Add failure if retval does not match void LLLTestSuite::expectReturn(int value) { if (retval == nullptr || *retval != value) { addFailure(LLLReturnFailure( "Incorrect return value", call, initial, value, *retval )); } } // Fill the LLL under test with the given values // e.g. initialize({1, 2, 3}); void LLLTestSuite::initialize(std::initializer_list<int> values) { head = nullptr; for (auto it = values.end(); it != values.begin();) { lll::node* temp = head; head = new lll::node(); head->data = *--it; head->next = temp; } initial = values; } void LLLTestSuite::addFailure(const LLLReturnFailure& fail) { failures.push_back(new LLLReturnFailure(fail)); }
26.238411
98
0.538617
pdx-cs-tutors
ed80e8fa693c8897d1d3c80fa21d33aa18405fe1
28,847
cpp
C++
turtlebotDemo/sick_line_guidance_demo/src/navigation_mapper.cpp
SICKAG/sick_line_guidance
8df75641adb7d3273701de7c52941ec9b53b97d6
[ "Apache-2.0" ]
5
2019-04-15T11:19:19.000Z
2022-02-16T09:58:05.000Z
turtlebotDemo/sick_line_guidance_demo/src/navigation_mapper.cpp
dejongyeong/sick_line_guidance
48cbbdea13d7e881db35334c04df5949667b9c28
[ "Apache-2.0" ]
3
2020-07-07T11:59:02.000Z
2021-04-21T05:43:19.000Z
turtlebotDemo/sick_line_guidance_demo/src/navigation_mapper.cpp
dejongyeong/sick_line_guidance
48cbbdea13d7e881db35334c04df5949667b9c28
[ "Apache-2.0" ]
5
2019-02-18T18:32:48.000Z
2022-02-10T15:04:35.000Z
/* * NavigationMapper transforms the robots xy-positions from world/meter into map/pixel position, * detect lines and barcodes in the map plus their distance to the robot, * and transforms them invers into world coordinates. * * Copyright (C) 2019 Ing.-Buero Dr. Michael Lehning, Hildesheim * Copyright (C) 2019 SICK AG, Waldkirch * * 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. * * 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 SICK AG nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission * * Neither the name of Ing.-Buero Dr. Michael Lehning nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Authors: * Michael Lehning <michael.lehning@lehning.de> * * Copyright 2019 SICK AG * Copyright 2019 Ing.-Buero Dr. Michael Lehning * */ #include <boost/thread.hpp> #include <cmath> #include <iomanip> #include <iostream> #include <string> #include <vector> #include <math.h> #include <ros/ros.h> #include <tf/transform_datatypes.h> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <opencv2/videoio.hpp> #include "sick_line_guidance/sick_line_guidance_msg_util.h" #include "sick_line_guidance_demo/image_util.h" #include "sick_line_guidance_demo/navigation_mapper.h" #include "sick_line_guidance_demo/navigation_util.h" #include "sick_line_guidance_demo/time_format.h" /* * class NavigationMapper transforms the robots xy-positions from world/meter into map/pixel position, * detect lines and barcodes in the map plus their distance to the robot, * and transforms them invers into world coordinates. */ /* * Constructor * @param[in] map_imagefile navigation map, image file containing the map, f.e. "demo_map_02.png" * @param[in] intrinsic_xmlfile xmlfile with intrinsic parameter to transform position from navigation map (pixel) to real world (meter) and vice versa, f.e. "cam_intrinsic.xml" with cx=cy=660, fx=fy=1 * @param[in] barcode_xmlfile xmlfile with a list of barcodes with label and position, f.e. "demo_barcodes.xml" * @param[in] ros_topic_output_ols_messages ROS topic for simulated OLS_Measurement messages, "/ols" (activated) in simulation and "" (deactivated) in demo application * @param[in] sensor_config line sensor configuration setting (sensor parameter and mounting settings) * @param[in] visualize==2: visualization+video enabled, map and navigation plots are displayed in a window, visualize==1: video created but not displayed, visualize==0: visualization and video disabled. */ sick_line_guidance_demo::NavigationMapper::NavigationMapper(ros::NodeHandle* nh, const std::string & map_imagefile, const std::string & intrinsic_xmlfile, const std::string & barcode_xmlfile, const std::string & ros_topic_output_ols_messages, const LineSensorConfig & sensor_config, int visualize) : m_navigation_state(INITIAL), m_visualize(visualize), m_window_name(""), m_ols_measurement_simulator(nh, ros_topic_output_ols_messages), m_sensor_config(sensor_config), m_message_rate(20), m_message_thread_run(false), m_message_thread(0) { sick_line_guidance::OLS_Measurement zero_ols_msg; sick_line_guidance::MsgUtil::zero(zero_ols_msg); m_ols_measurement_sensor.set(zero_ols_msg); m_ols_measurement_world.set(zero_ols_msg); m_error_simulation_burst_no_line_duration = 0.0; m_error_simulation_burst_no_line_frequency = 0.0; m_error_simulation_no_line_start = ros::Time::now(); m_error_simulation_no_line_end = m_error_simulation_no_line_start; if(nh) { ros::param::getCached("/error_simulation/burst_no_line_duration", m_error_simulation_burst_no_line_duration); // error simulation: duration of "no line detected" bursts in seconds, default: 0.0 (disabled) ros::param::getCached("/error_simulation/burst_no_line_frequency", m_error_simulation_burst_no_line_frequency); // error simulation: frequency of "no line detected" bursts in 1/seconds, default: 0.0 (disabled) ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "Configuration error simulation: " << " m_error_simulation_burst_no_line_duration=" << m_error_simulation_burst_no_line_duration << " m_error_simulation_burst_no_line_frequency=" << m_error_simulation_burst_no_line_frequency); } m_message_rate = ros::Rate(20); if(!map_imagefile.empty()) { m_map_img = cv::imread(map_imagefile, cv::IMREAD_COLOR); if(m_map_img.empty()) { ROS_ERROR_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "## ERROR sick_line_guidance_demo::NavigationMapper::NavigationMapper(): file \"" << map_imagefile << "\" not readable (" << __FILE__ << ":" << __LINE__ << ")."); m_visualize = false; } } if(!intrinsic_xmlfile.empty()) { cv::FileStorage cv_intrinsics_file(intrinsic_xmlfile, cv::FileStorage::READ); cv_intrinsics_file["Camera_Matrix"] >> m_intrinsics; cv_intrinsics_file.release(); if(m_intrinsics.empty()) { ROS_ERROR_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "## ERROR sick_line_guidance_demo::NavigationMapper::NavigationMapper(): intrisic matrix file \"" << intrinsic_xmlfile << "\" not readable or parameter not found (" << __FILE__ << ":" << __LINE__ << ")."); } else { ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper: intrinsics {cx=" << m_intrinsics.at<double>(0,2) << ",cy=" << m_intrinsics.at<double>(1,2) << ",fx=" << m_intrinsics.at<double>(0,0) << ",fy=" << m_intrinsics.at<double>(1,1) << "} read from configuration file \"" << intrinsic_xmlfile << "\"."); m_intrinsics_inv = m_intrinsics.inv(); } } if(!barcode_xmlfile.empty()) { m_barcodes = BarcodeUtil::readBarcodeXmlfile(barcode_xmlfile); if(m_barcodes.empty()) { ROS_ERROR_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "## ERROR sick_line_guidance_demo::NavigationMapper::NavigationMapper(): barcodes configuration file \"" << barcode_xmlfile << "\" not readable or parameter not found (" << __FILE__ << ":" << __LINE__ << ")."); } else { ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper: " << m_barcodes.size() << " barcodes read from configuration file \"" << barcode_xmlfile << "\"."); for(std::vector<Barcode>::iterator iter_barcode = m_barcodes.begin(); iter_barcode != m_barcodes.end(); iter_barcode++) { iter_barcode->innerRectMap() = transformRectWorldToMap(iter_barcode->innerRectWorld()); iter_barcode->outerRectMap() = transformRectWorldToMap(iter_barcode->outerRectWorld()); ROS_DEBUG_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "barcode: label=\"" << iter_barcode->label() << "\", innerRect=" << iter_barcode->innerRectWorld()<< "\", outerRect=" << iter_barcode->outerRectWorld() << ", flipped=" << iter_barcode->flipped()); } } } if(m_visualize > 0) { m_window_img = m_map_img.clone(); m_video_write = cv::VideoWriter("sick_line_guidance_demo.avi",CV_FOURCC('F','M','P','4'), 30, cv::Size(m_window_img.cols, m_window_img.rows)); if(m_visualize > 1) { m_window_name = "NavigationMap"; cv::namedWindow(m_window_name, cv::WINDOW_AUTOSIZE); cv::imshow(m_window_name, m_window_img); } } } /* * Destructor */ sick_line_guidance_demo::NavigationMapper::~NavigationMapper() { if(m_visualize > 0) { m_video_write.release(); if(m_visualize > 1) { cv::destroyAllWindows(); } } } /* * transforms a xy-position in world coordinates [meter] to a xy-position in image map coordinates [pixel] * @param[in] world_pos xy-position in world coordinates [meter] * @param[out] map_pos xy-position in image map coordinates [pixel] */ void sick_line_guidance_demo::NavigationMapper::transformPositionWorldToMap(const cv::Point2d & world_pos, cv::Point2d & map_pos) { double world_vec[3] = { world_pos.x, world_pos.y, 1.0 }; cv::Mat world_mat = cv::Mat(3, 1, CV_64F, world_vec); cv::Mat map_mat = m_intrinsics * world_mat; map_pos.x = map_mat.at<double>(0,0); map_pos.y = map_mat.at<double>(1,0); } /* * transforms a xy-position in world coordinates [meter] to a xy-position in image map coordinates [pixel] * @param[in] world_pos xy-position in world coordinates [meter] * @return xy-position in image map coordinates [pixel] */ cv::Point sick_line_guidance_demo::NavigationMapper::transformPositionWorldToMap(const cv::Point2d & world_pos) { cv::Point2d map_pos2d; transformPositionWorldToMap(world_pos, map_pos2d); return cv::Point(std::lround(map_pos2d.x), std::lround(map_pos2d.y)); } /* * transforms a xy-position in image map coordinates [pixel] to a xy-position in world coordinates [meter] * @param[in] map_pos xy-position in image map coordinates [pixel] * @return xy-position in world coordinates [meter] */ cv::Point2d sick_line_guidance_demo::NavigationMapper::transformPositionMapToWorld(const cv::Point2d & map_pos) { double map_vec[3] = { map_pos.x, map_pos.y, 1.0 }; cv::Mat map_mat = cv::Mat(3, 1, CV_64F, map_vec); cv::Mat world_mat = m_intrinsics_inv * map_mat; return cv::Point2d(world_mat.at<double>(0,0), world_mat.at<double>(1,0)); } /* * transforms a rectangle in world coordinates [meter] into a rectangle in image map coordinates [pixel] * @param[in] world_rect rectangle in world coordinates [meter] * @return rectangle in image map coordinates [pixel] */ cv::Rect sick_line_guidance_demo::NavigationMapper::transformRectWorldToMap(const cv::Rect2d & world_rect) { cv::Point map_pos1 = transformPositionWorldToMap(cv::Point2d(world_rect.x, world_rect.y)); cv::Point map_pos2 = transformPositionWorldToMap(cv::Point2d(world_rect.x + world_rect.width, world_rect.y)); cv::Point map_pos3 = transformPositionWorldToMap(cv::Point2d(world_rect.x + world_rect.width, world_rect.y + world_rect.height)); cv::Point map_pos4 = transformPositionWorldToMap(cv::Point2d(world_rect.x, world_rect.y + world_rect.height)); int x1 = std::min(std::min(map_pos1.x, map_pos2.x), std::min(map_pos3.x, map_pos4.x)); int y1 = std::min(std::min(map_pos1.y, map_pos2.y), std::min(map_pos3.y, map_pos4.y)); int x2 = std::max(std::max(map_pos1.x, map_pos2.x), std::max(map_pos3.x, map_pos4.x)); int y2 = std::max(std::max(map_pos1.y, map_pos2.y), std::max(map_pos3.y, map_pos4.y)); return cv::Rect(x1, y1, x2 - x1 + 1, y2 - y1 + 1); } /* * transforms an ols state from world coordinates [meter] to sensor units [meter], i.e. scales line distance (lcp) and line width * from physical distances in the world to units of a sensor measurement; reverts function unscaleMeasurementToWorld(): * line distances (lcp) are scaled by line_sensor_scaling_dist: default: 180.0/133.0, Scaling between physical distance to the line center and measured line center point * (measurement: lcp = 180 mm, physical: lcp = 133 mm), depending on mounted sensor height * line width are scaled by line_sensor_scaling_width: default: 29.0/20.0, Scaling between physical line width (20 mm) and measured line width (29 mm) depending on mounted sensor height * (sensor mounted 100 mm over ground: scaling = 1, sensor mounted 65 mm over ground: scaling = 100/65 = 1.5) * @param[in] ols_state ols state in world coordinates [meter] * @return ols measurement in sensor units [meter] */ sick_line_guidance::OLS_Measurement sick_line_guidance_demo::NavigationMapper::scaleWorldToMeasurement(const sick_line_guidance::OLS_Measurement & ols_state) { sick_line_guidance::OLS_Measurement ols_msg = ols_state; int status_flags[3] = { 0x1, 0x2, 0x4 }; for(int line_idx = 0; line_idx < 3; line_idx++) { if((ols_msg.status & (status_flags[line_idx])) != 0) { ols_msg.position[line_idx] *= static_cast<float>(m_sensor_config.line_sensor_scaling_dist); ols_msg.width[line_idx] *= static_cast<float>(m_sensor_config.line_sensor_scaling_width); } } return ols_msg; } /* * transforms an ols measurement from sensor units [meter] to world coordinates [meter], i.e. scales line distance (lcp) and line width * from sensor units to physical distances; reverts function scaleWorldToMeasurement(). * line distances (lcp) are scaled by 1 / line_sensor_scaling_dist * line width are scaled by 1 / line_sensor_scaling_width * @param[in] ols measurement in sensor units [meter] * @return ols_state ols state in world coordinates [meter] */ sick_line_guidance::OLS_Measurement sick_line_guidance_demo::NavigationMapper::unscaleMeasurementToWorld(const sick_line_guidance::OLS_Measurement & ols_message) { sick_line_guidance::OLS_Measurement ols_state = ols_message; int status_flags[3] = { 0x1, 0x2, 0x4 }; for(int line_idx = 0; line_idx < 3; line_idx++) { if((ols_state.status & (status_flags[line_idx])) != 0) { ols_state.position[line_idx] /= static_cast<float>(m_sensor_config.line_sensor_scaling_dist); ols_state.width[line_idx] /= static_cast<float>(m_sensor_config.line_sensor_scaling_width); } } return ols_state; } /* * starts the message loop to handle ols and odometry messages received. * Message handling runs in background thread started by this function. */ void sick_line_guidance_demo::NavigationMapper::start(void) { stop(); m_message_thread_run = true; m_message_thread = new boost::thread(&sick_line_guidance_demo::NavigationMapper::messageLoop, this); } /* * stops the message loop. */ void sick_line_guidance_demo::NavigationMapper::stop(void) { if(m_message_thread) { m_message_thread_run = false; m_message_thread->join(); delete(m_message_thread); m_message_thread = 0; } } /* * message callback for OLS measurement messages. This function is called automatically by the ros::Subscriber after subscription of topic "/ols". * It displays the OLS measurement (line info and barcodes), if visualization is enabled. * @param[in] msg OLS measurement message (input) */ void sick_line_guidance_demo::NavigationMapper::messageCallbackOlsMeasurement(const boost::shared_ptr<sick_line_guidance::OLS_Measurement const>& msg) { if(msg) { m_ols_measurement_sensor.set(*msg); // OLS measurement message received from topic "/ols" (measurment in sensor units) m_ols_measurement_world.set(unscaleMeasurementToWorld(*msg)); // OLS measurement message received from topic "/ols" (measurment scaled world coordinates) } else { ROS_ERROR_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "## ERROR sick_line_guidance_demo::NavigationMapper::messageCallbackOlsMeasurement(): invalid message (" << __FILE__ << ":" << __LINE__ << ")"); } } /* * message callback for odometry messages. This function is called automatically by the ros::Subscriber after subscription of topic "/odom". * @param[in] msg odometry message (input) */ void sick_line_guidance_demo::NavigationMapper::messageCallbackOdometry(const nav_msgs::Odometry::ConstPtr& msg) { if(msg) { m_odom_msg.set(*msg); } else { ROS_ERROR_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "## ERROR sick_line_guidance_demo::NavigationMapper::messageCallbackOdometry(): invalid message (" << __FILE__ << ":" << __LINE__ << ")"); } } /* * Runs the message loop to handle odometry and ols messages. * It transforms the robots xy-positions from world/meter into map/pixel position, detect lines and barcodes in the map plus their distance to the robot, * and transform them invers into world coordinates. * @param[in] msg odometry message (input) */ void sick_line_guidance_demo::NavigationMapper::messageLoop(void) { while(ros::ok()) { nav_msgs::Odometry odom_msg = m_odom_msg.get(); // Convert ModelStates message to robot position in world coordinates [meter] and and image position [pixel] ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper::messageLoop: ols_msg_sensor=( " << sick_line_guidance::MsgUtil::toInfo(m_ols_measurement_sensor.get()) << " )"); ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper::messageLoop: ols_msg_world=( " << sick_line_guidance::MsgUtil::toInfo(m_ols_measurement_world.get()) << " )"); ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper::messageLoop: odom_msg=( " << NavigationUtil::toInfo(odom_msg) << " )"); double robot_world_posx = 0, robot_world_posy= 0, robot_yaw_angle = 0; NavigationUtil::toWorldPosition(odom_msg, robot_world_posx, robot_world_posy, robot_yaw_angle); cv::Point2d robot_world_pos(robot_world_posx, robot_world_posy); cv::Point robot_map_pos = transformPositionWorldToMap(robot_world_pos); sick_line_guidance::OLS_Measurement ols_state = unscaleMeasurementToWorld(m_ols_measurement_simulator.GetState()); // start quickfix to find a line initially (simulation only): force an initial turn to the left to hit the line for the first time, needs further handling - tbd ... if(m_navigation_state == INITIAL && (robot_world_pos.x*robot_world_pos.x+robot_world_pos.y*robot_world_pos.y) > (0.26*0.26)) // force initial turn to the left to hit the line for the first time { OLS_Measurement_Simulator::setLine(ols_state, 0.001f, 0.02); // force a slight left turn } if(m_navigation_state == INITIAL && ImageUtil::isLinePixel(m_map_img,robot_map_pos)) m_navigation_state = FOLLOW_LINE; // line close to sensor, start to follow this line // end quicktest // Detect possible line center points in map/image coordinates [pixel] std::vector<LineDetectionResult> map_line_points = ImageUtil::detectLineCenterPoints(m_map_img, robot_map_pos, robot_yaw_angle); // transform line center points to world coordinate and compute distance in meter std::vector<LineDetectionResult> world_line_points; for(std::vector<LineDetectionResult>::iterator iter_line_points = map_line_points.begin(); iter_line_points != map_line_points.end(); iter_line_points++) { LineDetectionResult world_line_pos(*iter_line_points); world_line_pos.centerPos() = transformPositionMapToWorld(iter_line_points->centerPos()); world_line_pos.startPos() = transformPositionMapToWorld(iter_line_points->startPos()); world_line_pos.endPos() = transformPositionMapToWorld(iter_line_points->endPos()); world_line_pos.lineWidth() = NavigationUtil::euclideanDistance(world_line_pos.startPos(), world_line_pos.endPos()); world_line_pos.centerDistance() = NavigationUtil::euclideanDistanceOrientated(robot_world_pos, world_line_pos.centerPos(), robot_yaw_angle, m_sensor_config.line_sensor_mounted_right_to_left); world_line_points.push_back(world_line_pos); } // Sort by ascending distance between robot and line center point (note: centerDistance() is orientated, use std::abs(centerDistance()) for comparison) std::sort(world_line_points.begin(), world_line_points.end(), [](const LineDetectionResult & a, const LineDetectionResult & b){ return (std::abs(a.centerDistance()) < std::abs(b.centerDistance())); }); // Get a list of line center points within the detection zone of the sensor Barcode barcode; std::vector<LineDetectionResult> sensor_line_points = NavigationUtil::selectLinePointsWithinDetectionZone(world_line_points, robot_world_pos, m_sensor_config.line_sensor_detection_width, 3); if(m_navigation_state > INITIAL) { // Set ols measurement from line center points within the detection zone of the sensor for(std::vector<LineDetectionResult>::iterator iter_line_points = sensor_line_points.begin(); iter_line_points != sensor_line_points.end(); iter_line_points++) { ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "OLS-Simulation: robot_world_pos=(" << std::setprecision(3) << std::fixed << robot_world_pos.x << "," << robot_world_pos.y << "), lcp_pos=(" << iter_line_points->centerPos().x << "," << iter_line_points->centerPos().y << "), lcp_dist=" << iter_line_points->centerDistance() << "), linewidth=" << iter_line_points->lineWidth()); } // Detect barcodes for(std::vector<Barcode>::iterator iter_barcodes = m_barcodes.begin(); barcode.label().empty() && iter_barcodes != m_barcodes.end(); iter_barcodes++) { if(iter_barcodes->innerRectWorld().contains(robot_world_pos)) { barcode = *iter_barcodes; ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper: Barcode \"" << barcode.label() << "\" detected at robot xy-position on world: (" << std::setprecision(3) << std::fixed << robot_world_pos.x << "," << robot_world_pos.y << ")"); for(std::vector<LineDetectionResult>::iterator iter_line_points = sensor_line_points.begin(); iter_line_points != sensor_line_points.end(); iter_line_points++) iter_line_points->lineWidth() = barcode.innerRectWorld().width; // Line width within label area of the barcode has max. size } } OLS_Measurement_Simulator::setLines(ols_state, sensor_line_points); OLS_Measurement_Simulator::setBarcode(ols_state, barcode.labelCode(), barcode.flipped()); } // Error simulation and testing: no line detected for some time (line damaged or barcode entered) => fsm must not hang or loose the track! if(m_navigation_state > INITIAL && m_error_simulation_burst_no_line_frequency > 0 && m_error_simulation_burst_no_line_duration > 0 && ros::Time::now() > m_error_simulation_no_line_end + ros::Duration(1/m_error_simulation_burst_no_line_frequency)) { m_error_simulation_no_line_start = ros::Time::now(); m_error_simulation_no_line_end = m_error_simulation_no_line_start + ros::Duration(m_error_simulation_burst_no_line_duration); } if(ros::Time::now() >= m_error_simulation_no_line_start && ros::Time::now() < m_error_simulation_no_line_end) { sensor_line_points.clear(); OLS_Measurement_Simulator::setLines(ols_state, sensor_line_points); } // Publish ols measurement (if we're running the simulation) sick_line_guidance::OLS_Measurement ols_msg = scaleWorldToMeasurement(ols_state); m_ols_measurement_simulator.SetState(ols_msg); if(!m_ols_measurement_simulator.getPublishTopic().empty()) { m_ols_measurement_sensor.set(ols_msg); m_ols_measurement_world.set(ols_state); m_ols_measurement_simulator.schedulePublish(); ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper: publishing lcp[1]=" << std::fixed << std::setprecision(3) << ols_msg.position[1] << ", width[1]=" << ols_msg.width[1] << " on topic \"" << m_ols_measurement_simulator.getPublishTopic() << "\""); } if(m_visualize) { m_map_img.copyTo(m_window_img); // Draw line center points for(std::vector<LineDetectionResult>::iterator iter_lcp = map_line_points.begin(); iter_lcp != map_line_points.end(); iter_lcp++) cv::circle(m_window_img, iter_lcp->centerPos(), 3, CV_RGB(0,0,255), cv::FILLED); for(std::vector<LineDetectionResult>::iterator iter_lcp = sensor_line_points.begin(); iter_lcp != sensor_line_points.end(); iter_lcp++) cv::circle(m_window_img, transformPositionWorldToMap(iter_lcp->centerPos()), 1, CV_RGB(0,255,0), cv::FILLED); // Draw barcode if(!barcode.label().empty()) { cv::rectangle(m_window_img, barcode.outerRectMap(), CV_RGB(255,128,0), cv::FILLED); cv::rectangle(m_window_img, barcode.outerRectMap(), CV_RGB(0,0,0), 1); cv::putText(m_window_img, barcode.label(), cv::Point(barcode.centerMap().x - 24, barcode.centerMap().y + 16), cv::FONT_HERSHEY_SIMPLEX, 0.5, 2); } // Draw robot position and status (green: line or barcode detected, red otherwise) std::string map_color = ImageUtil::isLinePixel(m_map_img, robot_map_pos) ? "black" : "white"; cv::Scalar robot_color = CV_RGB(255,0,0); // default: display robot position in red color sick_line_guidance::OLS_Measurement ols_measurement_sensor = m_ols_measurement_sensor.get(); sick_line_guidance::OLS_Measurement ols_measurement_world = m_ols_measurement_world.get(); if(!sensor_line_points.empty() || ols_measurement_sensor.barcode > 0 || ols_measurement_sensor.extended_code > 0) robot_color = CV_RGB(0,255,0); // line or barcode detected: display robot position in green color // Draw robot cv::Point2d robot_pos1 = ImageUtil::getWorldPointInDirection(robot_world_pos, robot_yaw_angle - CV_PI/2, m_sensor_config.line_sensor_detection_width/2); cv::Point2d robot_pos2 = ImageUtil::getWorldPointInDirection(robot_world_pos, robot_yaw_angle + CV_PI/2, m_sensor_config.line_sensor_detection_width/2); cv::line(m_window_img, transformPositionWorldToMap(robot_pos1), transformPositionWorldToMap(robot_pos2), robot_color, 1); cv::circle(m_window_img, robot_map_pos, 3, robot_color, cv::FILLED); // Print ros time and lcp of main line std::stringstream info; info << "[" << std::fixed << std::setprecision(9) << ros::WallTime::now().toSec() << ", " << ros::Time::now().toSec() << "]"; if((ols_measurement_sensor.status&0x2) != 0) info << ": line[1]: " << std::fixed << std::setprecision(3) << ols_measurement_sensor.position[1] << "," << ols_measurement_sensor.width[1] << " (" << ols_measurement_world.position[1] << "," << ols_measurement_world.width[1] << ")"; cv::putText(m_window_img, info.str(), cv::Point(20, m_map_img.rows-32), cv::FONT_HERSHEY_SIMPLEX, 0.5, 2); // Display the navigation map ROS_INFO_STREAM(sick_line_guidance_demo::TimeFormat::formatDateTime() << "NavigationMapper: robot xy-position on map:(" << std::setprecision(1) << std::fixed << robot_map_pos.x << "," << robot_map_pos.y << "," << map_color << "), linestate:" << (int)(ols_measurement_sensor.status & 0x7) << ((m_navigation_state == FOLLOW_LINE) ? ", follow_line" : "")); m_video_write.write(m_window_img); if(!m_window_name.empty()) { cv::imshow(m_window_name, m_window_img); cv::waitKey(1); } } m_message_rate.sleep(); } }
58.276768
409
0.721392
SICKAG
ed81e202fb0ebb3d782ba5fd290e66c29a61420f
525
cpp
C++
src/hobbits-core/parseresult.cpp
nfi002/hobbits
b63a15e2e6d8238cba08f2bce686887d8626924b
[ "MIT" ]
null
null
null
src/hobbits-core/parseresult.cpp
nfi002/hobbits
b63a15e2e6d8238cba08f2bce686887d8626924b
[ "MIT" ]
1
2020-07-18T23:30:20.000Z
2020-07-18T23:30:20.000Z
src/hobbits-core/parseresult.cpp
nfi002/hobbits
b63a15e2e6d8238cba08f2bce686887d8626924b
[ "MIT" ]
null
null
null
#include "parseresult.h" ParseResult::ParseResult() { } ParseResult::ParseResult(qlonglong val, int mult) { this->_val = val; this->_mult = mult; } qlonglong ParseResult::getVal() { return this->_val; } int ParseResult::getMult() { return this->_mult; } qlonglong ParseResult::getResult() { if (this->isValid()) { return this->_val * this->_mult; } return -1; } bool ParseResult::isValid() { return (this->_mult >= 0 && this->_val >= 0); // No negative results allowed either. }
15
88
0.630476
nfi002
ed84d6114a2d78c11f9036dd7fd2dd95c10ce1d9
12,681
cpp
C++
src/ofxDarknet.cpp
ermuur/ofxDarknet
670101468e86416860fe805cc0e4c61bb2511d0a
[ "MIT" ]
64
2018-12-28T16:18:18.000Z
2022-02-14T16:48:00.000Z
src/ofxDarknet.cpp
Tencv/ofxDarknet
670101468e86416860fe805cc0e4c61bb2511d0a
[ "MIT" ]
6
2019-01-28T14:57:50.000Z
2020-02-19T05:47:05.000Z
src/ofxDarknet.cpp
Tencv/ofxDarknet
670101468e86416860fe805cc0e4c61bb2511d0a
[ "MIT" ]
15
2018-12-19T15:02:51.000Z
2022-03-11T07:03:24.000Z
#include "ofxDarknet.h" ofxDarknet::ofxDarknet() { loaded = false; labelsAvailable = false; } ofxDarknet::~ofxDarknet() { } void ofxDarknet::init( std::string cfgfile, std::string weightfile, std::string nameslist ) { if (nameslist != "") { labelsAvailable = true; } net = parse_network_cfg( cfgfile.c_str() ); load_weights( &net, weightfile.c_str() ); set_batch_network( &net, 1 ); if (!nameslist.empty()){ names = get_labels( (char *) nameslist.c_str() ); } // load layer names int numLayerTypes = 24; int * counts = new int[ numLayerTypes ]; for (int i=0; i<numLayerTypes; i++) {counts[i] = 0;} for (int i=0; i<net.n; i++) { LAYER_TYPE type = net.layers[i].type; string layerName = "Unknown"; if (type == CONVOLUTIONAL) layerName = "Conv"; else if (type == DECONVOLUTIONAL) layerName = "Deconv"; else if (type == CONNECTED) layerName = "FC"; else if (type == MAXPOOL) layerName = "MaxPool"; else if (type == SOFTMAX) layerName = "Softmax"; else if (type == DETECTION) layerName = "Detect"; else if (type == DROPOUT) layerName = "Dropout"; else if (type == CROP) layerName = "Crop"; else if (type == ROUTE) layerName = "Route"; else if (type == COST) layerName = "Cost"; else if (type == NORMALIZATION) layerName = "Normalize"; else if (type == AVGPOOL) layerName = "AvgPool"; else if (type == LOCAL) layerName = "Local"; else if (type == SHORTCUT) layerName = "Shortcut"; else if (type == ACTIVE) layerName = "Active"; else if (type == RNN) layerName = "RNN"; else if (type == GRU) layerName = "GRU"; else if (type == CRNN) layerName = "CRNN"; else if (type == BATCHNORM) layerName = "Batchnorm"; else if (type == NETWORK) layerName = "Network"; else if (type == XNOR) layerName = "XNOR"; else if (type == REGION) layerName = "Region"; else if (type == REORG) layerName = "Reorg"; else if (type == BLANK) layerName = "Blank"; layerNames.push_back(layerName+" "+ofToString(counts[type])); counts[type] += 1; } delete counts; loaded = true; } float * ofxDarknet::get_network_output_layer_gpu(int i) { layer l = net.layers[i]; if(l.type != REGION) cuda_pull_array(l.output_gpu, l.output, l.outputs*l.batch); return l.output; } std::vector< detected_object > ofxDarknet::yolo( ofPixels & pix, float threshold /*= 0.24f */, float maxOverlap /*= 0.5f */ ) { int originalWidth = pix.getWidth(); int originalHeight = pix.getHeight(); ofPixels pix2( pix ); if (pix2.getImageType() != OF_IMAGE_COLOR) { pix2.setImageType(OF_IMAGE_COLOR); } if( pix2.getWidth() != net.w && pix2.getHeight() != net.h ) { pix2.resize( net.w, net.h ); } image im = convert( pix2 ); layer l = net.layers[ net.n - 1 ]; box *boxes = ( box* ) calloc( l.w*l.h*l.n, sizeof( box ) ); float **probs = ( float** ) calloc( l.w*l.h*l.n, sizeof( float * ) ); for( int j = 0; j < l.w*l.h*l.n; ++j ) probs[ j ] = ( float* ) calloc( l.classes, sizeof( float * ) ); network_predict( net, im.data1 ); get_region_boxes( l, 1, 1, threshold, probs, boxes, 0, 0 ); do_nms_sort( boxes, probs, l.w*l.h*l.n, l.classes, 0.4 ); free_image( im ); std::vector< detected_object > detections; int num = l.w*l.h*l.n; int feature_layer = net.n - 2; layer l1 = net.layers[ feature_layer ]; float * features = get_network_output_layer_gpu(feature_layer); vector<size_t> sorted(num); iota(sorted.begin(), sorted.end(), 0); sort(sorted.begin(), sorted.end(), [&probs, &l](int i1, int i2) { return probs[i1][max_index(probs[i1], l.classes)] > probs[i2][max_index(probs[i2], l.classes)]; }); for( int i = 0; i < num; ++i ) { int idx = sorted[i]; int class1 = max_index( probs[ idx ], l.classes ); float prob = probs[ idx ][ class1 ]; if( prob < threshold ) { continue; } int offset = class1 * 123457 % l.classes; float red = get_color( 2, offset, l.classes ); float green = get_color( 1, offset, l.classes ); float blue = get_color( 0, offset, l.classes ); box b = boxes[ idx ]; int left = ( b.x - b.w / 2. )*im.w; int right = ( b.x + b.w / 2. )*im.w; int top = ( b.y - b.h / 2. )*im.h; int bot = ( b.y + b.h / 2. )*im.h; if( left < 0 ) left = 0; if( right > im.w - 1 ) right = im.w - 1; if( top < 0 ) top = 0; if( bot > im.h - 1 ) bot = im.h - 1; left = ofMap( left, 0, net.w, 0, originalWidth ); top = ofMap( top, 0, net.h, 0, originalHeight ); right = ofMap( right, 0, net.w, 0, originalWidth ); bot = ofMap( bot, 0, net.h, 0, originalHeight ); ofRectangle rect = ofRectangle( left, top, right - left, bot - top ); int rect_idx = floor(idx / l.n); float overlap = 0.0; for (auto d : detections) { float left = max(rect.x, d.rect.x); float right = min(rect.x+rect.width, d.rect.x+d.rect.width); float bottom = min(rect.y+rect.height, d.rect.y+d.rect.height); float top = max(rect.y, d.rect.y); float area_intersection = max(0.0f, right-left) * max(0.0f, bottom-top); overlap = max(overlap, area_intersection / (rect.getWidth() * rect.getHeight())); } if (overlap > maxOverlap) { continue; } detected_object detection; detection.label = names[ class1 ]; detection.probability = prob; detection.rect = rect; detection.color = ofColor( red * 255, green * 255, blue * 255); for (int f=0; f<l1.c; f++) { detection.features.push_back(features[rect_idx + l1.w * l1.h * f]); } detections.push_back( detection ); } free_ptrs((void**) probs, num); free(boxes); return detections; } ofImage ofxDarknet::nightmare( ofPixels & pix, int max_layer, int range, int norm, int rounds, int iters, int octaves, float rate, float thresh ) { image im = convert( pix ); for( int e = 0; e < rounds; ++e ) { fprintf( stderr, "Iteration: " ); fflush( stderr ); for( int n = 0; n < iters; ++n ) { fprintf( stderr, "%d, ", n ); fflush( stderr ); int layer = max_layer + rand() % range - range / 2; int octave = rand() % octaves; optimize_picture( &net, im, layer, 1 / pow( 1.33333333, octave ), rate, thresh, norm ); } } return ofImage( convert( im ) ); } std::vector< classification > ofxDarknet::classify( ofPixels & pix, int count ) { int *indexes = ( int* ) calloc( count, sizeof( int ) ); ofPixels pix2( pix ); if (pix2.getImageType() != OF_IMAGE_COLOR) { pix2.setImageType(OF_IMAGE_COLOR); } if( pix2.getWidth() != net.w && pix2.getHeight() != net.h ) { pix2.resize( net.w, net.h ); } image im = convert( pix2 ); float *predictions = network_predict( net, im.data1 ); top_k( predictions, net.outputs, count, indexes ); std::vector< classification > classifications; for( int i = 0; i < count; ++i ) { int index = indexes[ i ]; classification c; c.label = labelsAvailable ? names[ index ] : ofToString(index); c.probability = predictions[ index ]; classifications.push_back( c ); } free_image( im ); free(indexes); return classifications; } std::vector< activations > ofxDarknet::getFeatureMaps(int idxLayer) { std::vector< activations > maps; if (idxLayer > net.n) { return maps; } float * layer = get_network_output_layer_gpu(idxLayer); auto l = net.layers[idxLayer]; int channels = l.out_c; int rows = l.out_h; int cols = l.out_w; // cout << "size feature maps: "<<channels<<" x "<<rows<<" x "<<cols<<endl; int i=0; float min_ = +1e8; float max_ = -1e8; for (int c=0; c<channels; c++) { activations map; map.rows = rows; map.cols = cols; for(int y=0; y<rows; y++) { for(int x=0; x<cols; x++) { float val = layer[i]; map.acts.push_back(val); i++; if (val > max_) { max_ = val; } if (val < min_) { min_ = val; } } } maps.push_back(map); } for (auto & m : maps) { m.min = min_; m.max = max_; } return maps; } void activations::getImage(ofImage & img) { ofPixels pix; pix.allocate(rows, cols, OF_PIXELS_GRAY); for (int i=0; i<rows*cols; i++) { pix[i] = ofMap(acts[i], min, max, 0, 255); } img.setFromPixels(pix); } std::string ofxDarknet::rnn(int num, std::string seed, float temp ) { int inputs = get_network_input_size( net ); for( int i = 0; i < net.n; ++i ) { net.layers[ i ].temperature = temp; } int c = 0; int len = seed.length(); float *input = ( float* ) calloc( inputs, sizeof( float ) ); std::string sampled_text; for( int i = 0; i < len - 1; ++i ) { c = seed[ i ]; input[ c ] = 1; network_predict( net, input ); input[ c ] = 0; char _c = c; sampled_text += _c; } if( len ) c = seed[ len - 1 ]; char _c = c; sampled_text += _c; for( int i = 0; i < num; ++i ) { input[ c ] = 1; float *out = network_predict( net, input ); input[ c ] = 0; for( int j = 0; j < inputs; ++j ) { if( out[ j ] < .0001 ) out[ j ] = 0; } c = sample_array( out, inputs ); char _c = c; sampled_text += _c; } delete input; return sampled_text; } void ofxDarknet::train_rnn( std::string textfile, std::string cfgfile ) { srand( time( 0 ) ); unsigned char *text = 0; int *tokens = 0; size_t size; FILE *fp = fopen( textfile.c_str(), "rb" ); fseek( fp, 0, SEEK_END ); size = ftell( fp ); fseek( fp, 0, SEEK_SET ); text = ( unsigned char* ) calloc( size + 1, sizeof( char ) ); fread( text, 1, size, fp ); fclose( fp ); //char *backup_directory = "/home/pjreddie/backup/"; char *base = basecfg( cfgfile.c_str() ); fprintf( stderr, "%s\n", base ); float avg_loss = -1; network net = parse_network_cfg( cfgfile.c_str() ); int inputs = get_network_input_size( net ); fprintf( stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net.learning_rate, net.momentum, net.decay ); int batch = net.batch; int steps = net.time_steps; int i = ( *net.seen ) / net.batch; int streams = batch / steps; size_t *offsets = ( size_t* ) calloc( streams, sizeof( size_t ) ); int j; for( j = 0; j < streams; ++j ) { offsets[ j ] = rand_size_t() % size; } clock_t time; while( get_current_batch( net ) < net.max_batches ) { i += 1; time = clock(); float_pair p; p = get_rnn_data( text, offsets, inputs, size, streams, steps ); float loss = train_network_datum( net, p.x, p.y ) / ( batch ); free( p.x ); free( p.y ); if( avg_loss < 0 ) avg_loss = loss; avg_loss = avg_loss*.9 + loss*.1; int chars = get_current_batch( net )*batch; fprintf( stderr, "%d: %f, %f avg, %f rate, %lf seconds, %f epochs\n", i, loss, avg_loss, get_current_rate( net ), sec( clock() - time ), ( float ) chars / size ); for( j = 0; j < streams; ++j ) { //printf("%d\n", j); if( rand() % 10 == 0 ) { //fprintf(stderr, "Reset\n"); offsets[ j ] = rand_size_t() % size; reset_rnn_state( net, j ); } } if( i % 1000 == 0 ) { char buff[ 256 ]; sprintf( buff, "%s_%d.weights", base, i ); save_weights( net, buff ); } if( i % 10 == 0 ) { char buff[ 256 ]; sprintf( buff, "%s.backup", base ); save_weights( net, buff ); } } char buff[ 256 ]; sprintf( buff, "%s_final.weights", base ); save_weights( net, buff ); } image ofxDarknet::convert( ofPixels & pix ) { unsigned char *data = ( unsigned char * ) pix.getData(); int h = pix.getHeight(); int w = pix.getWidth(); int c = pix.getNumChannels(); int step = w * c; image im = make_image( w, h, c ); int i, j, k, count = 0;; for( k = 0; k < c; ++k ) { for( i = 0; i < h; ++i ) { for( j = 0; j < w; ++j ) { im.data1[ count++ ] = data[ i*step + j*c + k ] / 255.; } } } return im; } ofPixels ofxDarknet::convert( image & im ) { unsigned char *data = ( unsigned char* ) calloc( im.w*im.h*im.c, sizeof( char ) ); int i, k; for( k = 0; k < im.c; ++k ) { for( i = 0; i < im.w*im.h; ++i ) { data[ i*im.c + k ] = ( unsigned char ) ( 255 * im.data1[ i + k*im.w*im.h ] ); } } ofPixels pix; pix.setFromPixels( data, im.w, im.h, im.c ); return pix; }
29.018307
164
0.560918
ermuur
ed8c8c9064c33414c6b7b794d54471efb93cc98f
96,769
cc
C++
lib/thrift/compiler/cpp/src/thrift/thrifty.cc
NorbertoBurciaga/apache-thrift-tutorial
6da9bb3021e4e330b85d4473a7c1e690d6668827
[ "Apache-2.0" ]
null
null
null
lib/thrift/compiler/cpp/src/thrift/thrifty.cc
NorbertoBurciaga/apache-thrift-tutorial
6da9bb3021e4e330b85d4473a7c1e690d6668827
[ "Apache-2.0" ]
null
null
null
lib/thrift/compiler/cpp/src/thrift/thrifty.cc
NorbertoBurciaga/apache-thrift-tutorial
6da9bb3021e4e330b85d4473a7c1e690d6668827
[ "Apache-2.0" ]
null
null
null
/* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.0.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Copy the first part of user declarations. */ #line 4 "thrift/thrifty.yy" /* yacc.c:339 */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /** * Thrift parser. * * This parser is used on a thrift definition file. * */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <stdio.h> #ifndef _MSC_VER #include <inttypes.h> #else #include <stdint.h> #endif #include <limits.h> #ifdef _MSC_VER #include "thrift/windows/config.h" #endif #include "thrift/main.h" #include "thrift/common.h" #include "thrift/globals.h" #include "thrift/parse/t_program.h" #include "thrift/parse/t_scope.h" #ifdef _MSC_VER //warning C4065: switch statement contains 'default' but no 'case' labels #pragma warning(disable:4065) #endif /** * This global variable is used for automatic numbering of field indices etc. * when parsing the members of a struct. Field values are automatically * assigned starting from -1 and working their way down. */ int y_field_val = -1; /** * This global variable is used for automatic numbering of enum values. * y_enum_val is the last value assigned; the next auto-assigned value will be * y_enum_val+1, and then it continues working upwards. Explicitly specified * enum values reset y_enum_val to that value. */ int32_t y_enum_val = -1; int g_arglist = 0; const int struct_is_struct = 0; const int struct_is_union = 1; #line 139 "thrift/thrifty.cc" /* yacc.c:339 */ # ifndef YY_NULLPTR # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "y.tab.h". */ #ifndef YY_YY_THRIFT_THRIFTY_HH_INCLUDED # define YY_YY_THRIFT_THRIFTY_HH_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* "%code requires" blocks. */ #line 1 "thrift/thrifty.yy" /* yacc.c:355 */ #include "thrift/parse/t_program.h" #line 173 "thrift/thrifty.cc" /* yacc.c:355 */ /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { tok_identifier = 258, tok_literal = 259, tok_doctext = 260, tok_int_constant = 261, tok_dub_constant = 262, tok_include = 263, tok_namespace = 264, tok_cpp_include = 265, tok_cpp_type = 266, tok_xsd_all = 267, tok_xsd_optional = 268, tok_xsd_nillable = 269, tok_xsd_attrs = 270, tok_void = 271, tok_bool = 272, tok_string = 273, tok_binary = 274, tok_slist = 275, tok_senum = 276, tok_i8 = 277, tok_i16 = 278, tok_i32 = 279, tok_i64 = 280, tok_double = 281, tok_map = 282, tok_list = 283, tok_set = 284, tok_oneway = 285, tok_typedef = 286, tok_struct = 287, tok_xception = 288, tok_throws = 289, tok_extends = 290, tok_service = 291, tok_enum = 292, tok_const = 293, tok_required = 294, tok_optional = 295, tok_union = 296, tok_reference = 297 }; #endif /* Tokens. */ #define tok_identifier 258 #define tok_literal 259 #define tok_doctext 260 #define tok_int_constant 261 #define tok_dub_constant 262 #define tok_include 263 #define tok_namespace 264 #define tok_cpp_include 265 #define tok_cpp_type 266 #define tok_xsd_all 267 #define tok_xsd_optional 268 #define tok_xsd_nillable 269 #define tok_xsd_attrs 270 #define tok_void 271 #define tok_bool 272 #define tok_string 273 #define tok_binary 274 #define tok_slist 275 #define tok_senum 276 #define tok_i8 277 #define tok_i16 278 #define tok_i32 279 #define tok_i64 280 #define tok_double 281 #define tok_map 282 #define tok_list 283 #define tok_set 284 #define tok_oneway 285 #define tok_typedef 286 #define tok_struct 287 #define tok_xception 288 #define tok_throws 289 #define tok_extends 290 #define tok_service 291 #define tok_enum 292 #define tok_const 293 #define tok_required 294 #define tok_optional 295 #define tok_union 296 #define tok_reference 297 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { #line 81 "thrift/thrifty.yy" /* yacc.c:355 */ char* id; int64_t iconst; double dconst; bool tbool; t_doc* tdoc; t_type* ttype; t_base_type* tbase; t_typedef* ttypedef; t_enum* tenum; t_enum_value* tenumv; t_const* tconst; t_const_value* tconstv; t_struct* tstruct; t_service* tservice; t_function* tfunction; t_field* tfield; char* dtext; t_field::e_req ereq; t_annotation* tannot; t_field_id tfieldid; #line 292 "thrift/thrifty.cc" /* yacc.c:355 */ }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_THRIFT_THRIFTY_HH_INCLUDED */ /* Copy the second part of user declarations. */ #line 309 "thrift/thrifty.cc" /* yacc.c:358 */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif #if !defined _Noreturn \ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) # if defined _MSC_VER && 1200 <= _MSC_VER # define _Noreturn __declspec (noreturn) # else # define _Noreturn YY_ATTRIBUTE ((__noreturn__)) # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 3 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 173 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 56 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 60 /* YYNRULES -- Number of rules. */ #define YYNRULES 115 /* YYNSTATES -- Number of states. */ #define YYNSTATES 200 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 297 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 52, 53, 43, 2, 44, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 51, 45, 54, 48, 55, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 49, 2, 50, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 46, 2, 47, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 249, 249, 261, 272, 281, 286, 291, 295, 307, 315, 325, 338, 346, 351, 359, 374, 392, 399, 406, 413, 420, 429, 431, 434, 437, 450, 478, 485, 492, 506, 521, 533, 545, 552, 559, 566, 585, 594, 600, 605, 611, 616, 623, 630, 637, 644, 651, 658, 665, 669, 675, 690, 695, 700, 705, 710, 715, 720, 725, 730, 744, 758, 763, 768, 781, 786, 793, 799, 814, 819, 824, 834, 839, 849, 856, 890, 930, 940, 945, 950, 954, 966, 971, 980, 985, 990, 997, 1016, 1021, 1027, 1040, 1045, 1050, 1055, 1060, 1065, 1070, 1075, 1080, 1086, 1097, 1102, 1107, 1114, 1124, 1134, 1145, 1150, 1155, 1161, 1166, 1174, 1180, 1189, 1195 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "tok_identifier", "tok_literal", "tok_doctext", "tok_int_constant", "tok_dub_constant", "tok_include", "tok_namespace", "tok_cpp_include", "tok_cpp_type", "tok_xsd_all", "tok_xsd_optional", "tok_xsd_nillable", "tok_xsd_attrs", "tok_void", "tok_bool", "tok_string", "tok_binary", "tok_slist", "tok_senum", "tok_i8", "tok_i16", "tok_i32", "tok_i64", "tok_double", "tok_map", "tok_list", "tok_set", "tok_oneway", "tok_typedef", "tok_struct", "tok_xception", "tok_throws", "tok_extends", "tok_service", "tok_enum", "tok_const", "tok_required", "tok_optional", "tok_union", "tok_reference", "'*'", "','", "';'", "'{'", "'}'", "'='", "'['", "']'", "':'", "'('", "')'", "'<'", "'>'", "$accept", "Program", "CaptureDocText", "DestroyDocText", "HeaderList", "Header", "Include", "DefinitionList", "Definition", "TypeDefinition", "CommaOrSemicolonOptional", "Typedef", "Enum", "EnumDefList", "EnumDef", "EnumValue", "Senum", "SenumDefList", "SenumDef", "Const", "ConstValue", "ConstList", "ConstListContents", "ConstMap", "ConstMapContents", "StructHead", "Struct", "XsdAll", "XsdOptional", "XsdNillable", "XsdAttributes", "Xception", "Service", "FlagArgs", "UnflagArgs", "Extends", "FunctionList", "Function", "Oneway", "Throws", "FieldList", "Field", "FieldIdentifier", "FieldReference", "FieldRequiredness", "FieldValue", "FunctionType", "FieldType", "BaseType", "SimpleBaseType", "ContainerType", "SimpleContainerType", "MapType", "SetType", "ListType", "CppType", "TypeAnnotations", "TypeAnnotationList", "TypeAnnotation", "TypeAnnotationValue", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 42, 44, 59, 123, 125, 61, 91, 93, 58, 40, 41, 60, 62 }; # endif #define YYPACT_NINF -124 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-124))) #define YYTABLE_NINF -64 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { -124, 15, 9, -124, 26, 33, 35, 13, 36, -124, -124, 132, -124, 39, 40, -124, 41, 123, -124, 42, 45, 46, 123, -124, -124, -124, -124, -124, -124, -124, 61, -124, -124, -124, 16, -124, 19, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, 56, 18, 56, 70, -124, 16, -124, 16, -124, -124, -124, 29, 43, 30, 74, 68, -124, -124, -124, 77, 28, 123, 34, 16, -124, -124, -124, 80, 38, -124, 44, -124, 48, 7, 3, -124, 123, 32, 123, -23, 49, -124, -124, 50, 25, -124, 47, -124, -124, -23, 16, -124, 55, 56, 65, -124, -124, -124, 16, 84, -124, -124, 16, 98, -124, -124, -124, -124, -124, -124, -124, -23, -124, -124, 75, 117, -23, -124, -124, 123, -124, -124, -124, 51, -2, 76, -124, 79, 16, 5, 20, -124, 16, -124, -124, 78, -124, -124, -124, 123, 95, 82, -124, 124, -23, -124, 81, -124, -23, -124, -124, 89, -124, 90, 16, -124, -124, 25, -124, -124, 131, -124, 133, -124, -124, -23, 87, 92, -124, 25, 141, -124, -124, -124, 142, 102, -124, 143, 125, 111, 16, 108, 16, -124, -23, -124, -23, 114, -124, 109, -124, -124, -124 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 6, 0, 13, 1, 0, 3, 0, 0, 0, 5, 7, 0, 11, 0, 0, 10, 0, 0, 49, 0, 0, 0, 0, 50, 12, 15, 17, 18, 19, 14, 0, 20, 21, 16, 110, 9, 0, 87, 94, 91, 92, 93, 95, 96, 97, 98, 99, 108, 0, 108, 0, 88, 110, 89, 110, 101, 102, 103, 0, 65, 0, 0, 53, 112, 8, 34, 0, 0, 0, 0, 110, 90, 100, 74, 0, 0, 28, 0, 52, 0, 0, 0, 107, 0, 0, 0, 24, 3, 64, 62, 3, 0, 74, 115, 109, 111, 24, 110, 33, 0, 108, 0, 22, 23, 25, 110, 77, 73, 67, 110, 0, 27, 40, 39, 37, 38, 48, 45, 24, 41, 42, 3, 0, 24, 35, 32, 0, 106, 105, 60, 0, 82, 3, 26, 31, 110, 0, 0, 36, 110, 114, 113, 0, 76, 80, 81, 0, 70, 0, 66, 0, 24, 46, 0, 43, 24, 51, 104, 79, 69, 0, 110, 30, 29, 0, 44, 78, 0, 86, 0, 85, 61, 24, 84, 0, 47, 0, 55, 74, 83, 54, 57, 3, 56, 59, 72, 0, 110, 0, 110, 74, 24, 74, 24, 3, 75, 3, 68, 58, 71 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int8 yypgoto[] = { -124, -124, -4, -124, -124, -124, -124, -124, -124, -124, -93, -124, -124, -124, -124, -124, -124, -124, -124, -124, -123, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -124, -87, -124, -124, -124, -124, -124, -124, -22, -124, -124, -124, -124, -124, -124, -124, -43, -50, -124, -124, -124 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 1, 106, 4, 2, 9, 10, 5, 24, 25, 104, 26, 27, 90, 111, 135, 28, 81, 98, 29, 118, 119, 137, 120, 136, 30, 31, 79, 181, 184, 187, 32, 33, 108, 148, 75, 132, 149, 160, 189, 87, 107, 131, 167, 146, 177, 169, 50, 51, 52, 53, 54, 55, 56, 57, 67, 64, 80, 95, 123 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 61, 11, 71, 124, 72, 121, 69, 96, 112, 113, 93, 114, 115, 153, 155, 3, 13, -4, -4, -4, 86, 102, 103, 112, 113, 138, 114, 115, 112, 113, 141, 114, 115, -2, 6, 7, 8, 144, 145, 12, 15, 172, 34, 35, 36, 58, 84, 125, 59, 60, 97, 116, 152, 179, 117, 129, 14, 127, 163, 133, 94, 99, 165, 101, 62, 65, 116, 66, 63, 117, 154, 116, 68, 70, 117, 73, 76, 77, 74, 175, 78, 82, 83, 88, 89, 151, 110, 100, 85, 156, 130, 182, 91, 37, 92, 122, 105, 109, 195, 126, 197, 134, 143, 194, 142, 196, 168, 38, 39, 40, 41, 171, 42, 43, 44, 45, 46, 47, 48, 49, 128, 140, 139, -63, 158, 159, 37, 150, 147, 161, 162, 166, 164, 157, 173, 176, 174, 191, 170, 193, 38, 39, 40, 41, 178, 42, 43, 44, 45, 46, 47, 48, 49, 16, 180, 185, 183, 190, 186, 188, 192, 198, 199, 17, 18, 19, 0, 0, 20, 21, 22, 0, 0, 23 }; static const yytype_int16 yycheck[] = { 22, 5, 52, 96, 54, 92, 49, 4, 3, 4, 3, 6, 7, 136, 137, 0, 3, 8, 9, 10, 70, 44, 45, 3, 4, 118, 6, 7, 3, 4, 123, 6, 7, 0, 8, 9, 10, 39, 40, 4, 4, 164, 3, 3, 3, 3, 68, 97, 3, 3, 47, 46, 47, 176, 49, 105, 43, 100, 151, 109, 53, 83, 155, 85, 3, 46, 46, 11, 52, 49, 50, 46, 54, 3, 49, 46, 46, 3, 35, 172, 12, 4, 54, 3, 46, 135, 90, 55, 54, 139, 6, 178, 48, 3, 46, 48, 47, 47, 191, 44, 193, 3, 51, 190, 126, 192, 16, 17, 18, 19, 20, 161, 22, 23, 24, 25, 26, 27, 28, 29, 55, 4, 47, 47, 146, 30, 3, 48, 132, 47, 6, 42, 51, 55, 3, 48, 3, 187, 160, 189, 17, 18, 19, 20, 52, 22, 23, 24, 25, 26, 27, 28, 29, 21, 13, 53, 14, 46, 15, 34, 52, 47, 53, 31, 32, 33, -1, -1, 36, 37, 38, -1, -1, 41 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 57, 60, 0, 59, 63, 8, 9, 10, 61, 62, 58, 4, 3, 43, 4, 21, 31, 32, 33, 36, 37, 38, 41, 64, 65, 67, 68, 72, 75, 81, 82, 87, 88, 3, 3, 3, 3, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 103, 104, 105, 106, 107, 108, 109, 110, 3, 3, 3, 103, 3, 52, 112, 46, 11, 111, 54, 111, 3, 112, 112, 46, 35, 91, 46, 3, 12, 83, 113, 73, 4, 54, 103, 54, 112, 96, 3, 46, 69, 48, 46, 3, 53, 114, 4, 47, 74, 103, 55, 103, 44, 45, 66, 47, 58, 97, 89, 47, 58, 70, 3, 4, 6, 7, 46, 49, 76, 77, 79, 96, 48, 115, 66, 112, 44, 111, 55, 112, 6, 98, 92, 112, 3, 71, 80, 78, 66, 47, 4, 66, 103, 51, 39, 40, 100, 58, 90, 93, 48, 112, 47, 76, 50, 76, 112, 55, 103, 30, 94, 47, 6, 66, 51, 66, 42, 99, 16, 102, 103, 112, 76, 3, 3, 66, 48, 101, 52, 76, 13, 84, 96, 14, 85, 53, 15, 86, 34, 95, 46, 112, 52, 112, 96, 66, 96, 66, 47, 53 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 56, 57, 58, 59, 60, 60, 61, 61, 61, 61, 62, 63, 63, 64, 64, 64, 65, 65, 65, 65, 65, 66, 66, 66, 67, 68, 69, 69, 70, 71, 71, 72, 73, 73, 74, 75, 76, 76, 76, 76, 76, 76, 77, 78, 78, 79, 80, 80, 81, 81, 82, 83, 83, 84, 84, 85, 85, 86, 86, 87, 88, 89, 90, 91, 91, 92, 92, 93, 94, 94, 95, 95, 96, 96, 97, 98, 98, 99, 99, 100, 100, 100, 101, 101, 102, 102, 103, 103, 103, 104, 105, 105, 105, 105, 105, 105, 105, 105, 105, 106, 107, 107, 107, 108, 109, 110, 111, 111, 112, 112, 113, 113, 114, 115, 115 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 2, 0, 0, 3, 0, 1, 4, 3, 2, 2, 3, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 5, 6, 2, 0, 4, 3, 1, 6, 2, 0, 2, 6, 1, 1, 1, 1, 1, 1, 3, 3, 0, 3, 5, 0, 1, 1, 7, 1, 0, 1, 0, 1, 0, 4, 0, 6, 9, 0, 0, 2, 0, 2, 0, 10, 1, 0, 4, 0, 2, 0, 12, 2, 0, 1, 0, 1, 1, 0, 2, 0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 7, 5, 5, 2, 0, 3, 0, 2, 0, 3, 2, 0 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*----------------------------------------. | Print this symbol's value on YYOUTPUT. | `----------------------------------------*/ static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) { FILE *yyo = yyoutput; YYUSE (yyo); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) { YYFPRINTF (yyoutput, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) { unsigned long int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ int yyparse (void) { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 250 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Program -> Headers DefinitionList"); if((g_program_doctext_candidate != NULL) && (g_program_doctext_status != ALREADY_PROCESSED)) { g_program->set_doc(g_program_doctext_candidate); g_program_doctext_status = ALREADY_PROCESSED; } clear_doctext(); } #line 1547 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 3: #line 261 "thrift/thrifty.yy" /* yacc.c:1646 */ { if (g_parse_mode == PROGRAM) { (yyval.dtext) = g_doctext; g_doctext = NULL; } else { (yyval.dtext) = NULL; } } #line 1560 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 4: #line 272 "thrift/thrifty.yy" /* yacc.c:1646 */ { if (g_parse_mode == PROGRAM) { clear_doctext(); } } #line 1570 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 5: #line 282 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("HeaderList -> HeaderList Header"); } #line 1578 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 6: #line 286 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("HeaderList -> "); } #line 1586 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 7: #line 292 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Header -> Include"); } #line 1594 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 8: #line 296 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Header -> tok_namespace tok_identifier tok_identifier"); declare_valid_program_doctext(); if (g_parse_mode == PROGRAM) { g_program->set_namespace((yyvsp[-2].id), (yyvsp[-1].id)); } if ((yyvsp[0].ttype) != NULL) { g_program->set_namespace_annotations((yyvsp[-2].id), (yyvsp[0].ttype)->annotations_); delete (yyvsp[0].ttype); } } #line 1610 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 9: #line 308 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Header -> tok_namespace * tok_identifier"); declare_valid_program_doctext(); if (g_parse_mode == PROGRAM) { g_program->set_namespace("*", (yyvsp[0].id)); } } #line 1622 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 10: #line 316 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Header -> tok_cpp_include tok_literal"); declare_valid_program_doctext(); if (g_parse_mode == PROGRAM) { g_program->add_cpp_include((yyvsp[0].id)); } } #line 1634 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 11: #line 326 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Include -> tok_include tok_literal"); declare_valid_program_doctext(); if (g_parse_mode == INCLUDES) { std::string path = include_file(std::string((yyvsp[0].id))); if (!path.empty()) { g_program->add_include(path, std::string((yyvsp[0].id))); } } } #line 1649 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 12: #line 339 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("DefinitionList -> DefinitionList Definition"); if ((yyvsp[-1].dtext) != NULL && (yyvsp[0].tdoc) != NULL) { (yyvsp[0].tdoc)->set_doc((yyvsp[-1].dtext)); } } #line 1660 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 13: #line 346 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("DefinitionList -> "); } #line 1668 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 14: #line 352 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Definition -> Const"); if (g_parse_mode == PROGRAM) { g_program->add_const((yyvsp[0].tconst)); } (yyval.tdoc) = (yyvsp[0].tconst); } #line 1680 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 15: #line 360 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Definition -> TypeDefinition"); if (g_parse_mode == PROGRAM) { g_scope->add_type((yyvsp[0].ttype)->get_name(), (yyvsp[0].ttype)); if (g_parent_scope != NULL) { g_parent_scope->add_type(g_parent_prefix + (yyvsp[0].ttype)->get_name(), (yyvsp[0].ttype)); } if (! g_program->is_unique_typename((yyvsp[0].ttype))) { yyerror("Type \"%s\" is already defined.", (yyvsp[0].ttype)->get_name().c_str()); exit(1); } } (yyval.tdoc) = (yyvsp[0].ttype); } #line 1699 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 16: #line 375 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Definition -> Service"); if (g_parse_mode == PROGRAM) { g_scope->add_service((yyvsp[0].tservice)->get_name(), (yyvsp[0].tservice)); if (g_parent_scope != NULL) { g_parent_scope->add_service(g_parent_prefix + (yyvsp[0].tservice)->get_name(), (yyvsp[0].tservice)); } g_program->add_service((yyvsp[0].tservice)); if (! g_program->is_unique_typename((yyvsp[0].tservice))) { yyerror("Type \"%s\" is already defined.", (yyvsp[0].tservice)->get_name().c_str()); exit(1); } } (yyval.tdoc) = (yyvsp[0].tservice); } #line 1719 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 17: #line 393 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeDefinition -> Typedef"); if (g_parse_mode == PROGRAM) { g_program->add_typedef((yyvsp[0].ttypedef)); } } #line 1730 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 18: #line 400 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeDefinition -> Enum"); if (g_parse_mode == PROGRAM) { g_program->add_enum((yyvsp[0].tenum)); } } #line 1741 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 19: #line 407 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeDefinition -> Senum"); if (g_parse_mode == PROGRAM) { g_program->add_typedef((yyvsp[0].ttypedef)); } } #line 1752 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 20: #line 414 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeDefinition -> Struct"); if (g_parse_mode == PROGRAM) { g_program->add_struct((yyvsp[0].tstruct)); } } #line 1763 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 21: #line 421 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeDefinition -> Xception"); if (g_parse_mode == PROGRAM) { g_program->add_xception((yyvsp[0].tstruct)); } } #line 1774 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 22: #line 430 "thrift/thrifty.yy" /* yacc.c:1646 */ {} #line 1780 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 23: #line 432 "thrift/thrifty.yy" /* yacc.c:1646 */ {} #line 1786 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 24: #line 434 "thrift/thrifty.yy" /* yacc.c:1646 */ {} #line 1792 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 25: #line 438 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeDef -> tok_typedef FieldType tok_identifier"); validate_simple_identifier( (yyvsp[-2].id)); t_typedef *td = new t_typedef(g_program, (yyvsp[-3].ttype), (yyvsp[-2].id)); (yyval.ttypedef) = td; if ((yyvsp[-1].ttype) != NULL) { (yyval.ttypedef)->annotations_ = (yyvsp[-1].ttype)->annotations_; delete (yyvsp[-1].ttype); } } #line 1807 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 26: #line 451 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Enum -> tok_enum tok_identifier { EnumDefList }"); (yyval.tenum) = (yyvsp[-2].tenum); validate_simple_identifier( (yyvsp[-4].id)); (yyval.tenum)->set_name((yyvsp[-4].id)); if ((yyvsp[0].ttype) != NULL) { (yyval.tenum)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } // make constants for all the enum values if (g_parse_mode == PROGRAM) { const std::vector<t_enum_value*>& enum_values = (yyval.tenum)->get_constants(); std::vector<t_enum_value*>::const_iterator c_iter; for (c_iter = enum_values.begin(); c_iter != enum_values.end(); ++c_iter) { std::string const_name = (yyval.tenum)->get_name() + "." + (*c_iter)->get_name(); t_const_value* const_val = new t_const_value((*c_iter)->get_value()); const_val->set_enum((yyval.tenum)); g_scope->add_constant(const_name, new t_const(g_type_i32, (*c_iter)->get_name(), const_val)); if (g_parent_scope != NULL) { g_parent_scope->add_constant(g_parent_prefix + const_name, new t_const(g_type_i32, (*c_iter)->get_name(), const_val)); } } } } #line 1837 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 27: #line 479 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("EnumDefList -> EnumDefList EnumDef"); (yyval.tenum) = (yyvsp[-1].tenum); (yyval.tenum)->append((yyvsp[0].tenumv)); } #line 1847 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 28: #line 485 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("EnumDefList -> "); (yyval.tenum) = new t_enum(g_program); y_enum_val = -1; } #line 1857 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 29: #line 493 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("EnumDef -> EnumValue"); (yyval.tenumv) = (yyvsp[-2].tenumv); if ((yyvsp[-3].dtext) != NULL) { (yyval.tenumv)->set_doc((yyvsp[-3].dtext)); } if ((yyvsp[-1].ttype) != NULL) { (yyval.tenumv)->annotations_ = (yyvsp[-1].ttype)->annotations_; delete (yyvsp[-1].ttype); } } #line 1873 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 30: #line 507 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("EnumValue -> tok_identifier = tok_int_constant"); if ((yyvsp[0].iconst) < INT32_MIN || (yyvsp[0].iconst) > INT32_MAX) { // Note: this used to be just a warning. However, since thrift always // treats enums as i32 values, I'm changing it to a fatal error. // I doubt this will affect many people, but users who run into this // will have to update their thrift files to manually specify the // truncated i32 value that thrift has always been using anyway. failure("64-bit value supplied for enum %s will be truncated.", (yyvsp[-2].id)); } y_enum_val = static_cast<int32_t>((yyvsp[0].iconst)); (yyval.tenumv) = new t_enum_value((yyvsp[-2].id), y_enum_val); } #line 1891 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 31: #line 522 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("EnumValue -> tok_identifier"); validate_simple_identifier( (yyvsp[0].id)); if (y_enum_val == INT32_MAX) { failure("enum value overflow at enum %s", (yyvsp[0].id)); } ++y_enum_val; (yyval.tenumv) = new t_enum_value((yyvsp[0].id), y_enum_val); } #line 1905 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 32: #line 534 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Senum -> tok_senum tok_identifier { SenumDefList }"); validate_simple_identifier( (yyvsp[-4].id)); (yyval.ttypedef) = new t_typedef(g_program, (yyvsp[-2].tbase), (yyvsp[-4].id)); if ((yyvsp[0].ttype) != NULL) { (yyval.ttypedef)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } } #line 1919 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 33: #line 546 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SenumDefList -> SenumDefList SenumDef"); (yyval.tbase) = (yyvsp[-1].tbase); (yyval.tbase)->add_string_enum_val((yyvsp[0].id)); } #line 1929 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 34: #line 552 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SenumDefList -> "); (yyval.tbase) = new t_base_type("string", t_base_type::TYPE_STRING); (yyval.tbase)->set_string_enum(true); } #line 1939 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 35: #line 560 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SenumDef -> tok_literal"); (yyval.id) = (yyvsp[-1].id); } #line 1948 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 36: #line 567 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Const -> tok_const FieldType tok_identifier = ConstValue"); if (g_parse_mode == PROGRAM) { validate_simple_identifier( (yyvsp[-3].id)); g_scope->resolve_const_value((yyvsp[-1].tconstv), (yyvsp[-4].ttype)); (yyval.tconst) = new t_const((yyvsp[-4].ttype), (yyvsp[-3].id), (yyvsp[-1].tconstv)); validate_const_type((yyval.tconst)); g_scope->add_constant((yyvsp[-3].id), (yyval.tconst)); if (g_parent_scope != NULL) { g_parent_scope->add_constant(g_parent_prefix + (yyvsp[-3].id), (yyval.tconst)); } } else { (yyval.tconst) = NULL; } } #line 1969 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 37: #line 586 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstValue => tok_int_constant"); (yyval.tconstv) = new t_const_value(); (yyval.tconstv)->set_integer((yyvsp[0].iconst)); if (!g_allow_64bit_consts && ((yyvsp[0].iconst) < INT32_MIN || (yyvsp[0].iconst) > INT32_MAX)) { pwarning(1, "64-bit constant \"%" PRIi64"\" may not work in all languages.\n", (yyvsp[0].iconst)); } } #line 1982 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 38: #line 595 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstValue => tok_dub_constant"); (yyval.tconstv) = new t_const_value(); (yyval.tconstv)->set_double((yyvsp[0].dconst)); } #line 1992 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 39: #line 601 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstValue => tok_literal"); (yyval.tconstv) = new t_const_value((yyvsp[0].id)); } #line 2001 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 40: #line 606 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstValue => tok_identifier"); (yyval.tconstv) = new t_const_value(); (yyval.tconstv)->set_identifier((yyvsp[0].id)); } #line 2011 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 41: #line 612 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstValue => ConstList"); (yyval.tconstv) = (yyvsp[0].tconstv); } #line 2020 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 42: #line 617 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstValue => ConstMap"); (yyval.tconstv) = (yyvsp[0].tconstv); } #line 2029 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 43: #line 624 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstList => [ ConstListContents ]"); (yyval.tconstv) = (yyvsp[-1].tconstv); } #line 2038 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 44: #line 631 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstListContents => ConstListContents ConstValue CommaOrSemicolonOptional"); (yyval.tconstv) = (yyvsp[-2].tconstv); (yyval.tconstv)->add_list((yyvsp[-1].tconstv)); } #line 2048 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 45: #line 637 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstListContents =>"); (yyval.tconstv) = new t_const_value(); (yyval.tconstv)->set_list(); } #line 2058 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 46: #line 645 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstMap => { ConstMapContents }"); (yyval.tconstv) = (yyvsp[-1].tconstv); } #line 2067 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 47: #line 652 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstMapContents => ConstMapContents ConstValue CommaOrSemicolonOptional"); (yyval.tconstv) = (yyvsp[-4].tconstv); (yyval.tconstv)->add_map((yyvsp[-3].tconstv), (yyvsp[-1].tconstv)); } #line 2077 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 48: #line 658 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ConstMapContents =>"); (yyval.tconstv) = new t_const_value(); (yyval.tconstv)->set_map(); } #line 2087 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 49: #line 666 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.iconst) = struct_is_struct; } #line 2095 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 50: #line 670 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.iconst) = struct_is_union; } #line 2103 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 51: #line 676 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Struct -> tok_struct tok_identifier { FieldList }"); validate_simple_identifier( (yyvsp[-5].id)); (yyvsp[-2].tstruct)->set_xsd_all((yyvsp[-4].tbool)); (yyvsp[-2].tstruct)->set_union((yyvsp[-6].iconst) == struct_is_union); (yyval.tstruct) = (yyvsp[-2].tstruct); (yyval.tstruct)->set_name((yyvsp[-5].id)); if ((yyvsp[0].ttype) != NULL) { (yyval.tstruct)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } } #line 2120 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 52: #line 691 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = true; } #line 2128 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 53: #line 695 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = false; } #line 2136 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 54: #line 701 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = true; } #line 2144 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 55: #line 705 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = false; } #line 2152 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 56: #line 711 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = true; } #line 2160 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 57: #line 715 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = false; } #line 2168 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 58: #line 721 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tstruct) = (yyvsp[-1].tstruct); } #line 2176 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 59: #line 725 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tstruct) = NULL; } #line 2184 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 60: #line 731 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Xception -> tok_xception tok_identifier { FieldList }"); validate_simple_identifier( (yyvsp[-4].id)); (yyvsp[-2].tstruct)->set_name((yyvsp[-4].id)); (yyvsp[-2].tstruct)->set_xception(true); (yyval.tstruct) = (yyvsp[-2].tstruct); if ((yyvsp[0].ttype) != NULL) { (yyval.tstruct)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } } #line 2200 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 61: #line 745 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Service -> tok_service tok_identifier { FunctionList }"); validate_simple_identifier( (yyvsp[-7].id)); (yyval.tservice) = (yyvsp[-3].tservice); (yyval.tservice)->set_name((yyvsp[-7].id)); (yyval.tservice)->set_extends((yyvsp[-6].tservice)); if ((yyvsp[0].ttype) != NULL) { (yyval.tservice)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } } #line 2216 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 62: #line 758 "thrift/thrifty.yy" /* yacc.c:1646 */ { g_arglist = 1; } #line 2224 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 63: #line 763 "thrift/thrifty.yy" /* yacc.c:1646 */ { g_arglist = 0; } #line 2232 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 64: #line 769 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Extends -> tok_extends tok_identifier"); (yyval.tservice) = NULL; if (g_parse_mode == PROGRAM) { (yyval.tservice) = g_scope->get_service((yyvsp[0].id)); if ((yyval.tservice) == NULL) { yyerror("Service \"%s\" has not been defined.", (yyvsp[0].id)); exit(1); } } } #line 2248 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 65: #line 781 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tservice) = NULL; } #line 2256 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 66: #line 787 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FunctionList -> FunctionList Function"); (yyval.tservice) = (yyvsp[-1].tservice); (yyvsp[-1].tservice)->add_function((yyvsp[0].tfunction)); } #line 2266 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 67: #line 793 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FunctionList -> "); (yyval.tservice) = new t_service(g_program); } #line 2275 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 68: #line 800 "thrift/thrifty.yy" /* yacc.c:1646 */ { validate_simple_identifier( (yyvsp[-6].id)); (yyvsp[-4].tstruct)->set_name(std::string((yyvsp[-6].id)) + "_args"); (yyval.tfunction) = new t_function((yyvsp[-7].ttype), (yyvsp[-6].id), (yyvsp[-4].tstruct), (yyvsp[-2].tstruct), (yyvsp[-8].tbool)); if ((yyvsp[-9].dtext) != NULL) { (yyval.tfunction)->set_doc((yyvsp[-9].dtext)); } if ((yyvsp[-1].ttype) != NULL) { (yyval.tfunction)->annotations_ = (yyvsp[-1].ttype)->annotations_; delete (yyvsp[-1].ttype); } } #line 2292 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 69: #line 815 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = true; } #line 2300 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 70: #line 819 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = false; } #line 2308 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 71: #line 825 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("Throws -> tok_throws ( FieldList )"); (yyval.tstruct) = (yyvsp[-1].tstruct); if (g_parse_mode == PROGRAM && !validate_throws((yyval.tstruct))) { yyerror("Throws clause may not contain non-exception types"); exit(1); } } #line 2321 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 72: #line 834 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tstruct) = new t_struct(g_program); } #line 2329 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 73: #line 840 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FieldList -> FieldList , Field"); (yyval.tstruct) = (yyvsp[-1].tstruct); if (!((yyval.tstruct)->append((yyvsp[0].tfield)))) { yyerror("\"%d: %s\" - field identifier/name has already been used", (yyvsp[0].tfield)->get_key(), (yyvsp[0].tfield)->get_name().c_str()); exit(1); } } #line 2342 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 74: #line 849 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FieldList -> "); y_field_val = -1; (yyval.tstruct) = new t_struct(g_program); } #line 2352 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 75: #line 857 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("tok_int_constant : Field -> FieldType tok_identifier"); if ((yyvsp[-10].tfieldid).auto_assigned) { pwarning(1, "No field key specified for %s, resulting protocol may have conflicts or not be backwards compatible!\n", (yyvsp[-6].id)); if (g_strict >= 192) { yyerror("Implicit field keys are deprecated and not allowed with -strict"); exit(1); } } validate_simple_identifier((yyvsp[-6].id)); (yyval.tfield) = new t_field((yyvsp[-8].ttype), (yyvsp[-6].id), (yyvsp[-10].tfieldid).value); (yyval.tfield)->set_reference((yyvsp[-7].tbool)); (yyval.tfield)->set_req((yyvsp[-9].ereq)); if ((yyvsp[-5].tconstv) != NULL) { g_scope->resolve_const_value((yyvsp[-5].tconstv), (yyvsp[-8].ttype)); validate_field_value((yyval.tfield), (yyvsp[-5].tconstv)); (yyval.tfield)->set_value((yyvsp[-5].tconstv)); } (yyval.tfield)->set_xsd_optional((yyvsp[-4].tbool)); (yyval.tfield)->set_xsd_nillable((yyvsp[-3].tbool)); if ((yyvsp[-11].dtext) != NULL) { (yyval.tfield)->set_doc((yyvsp[-11].dtext)); } if ((yyvsp[-2].tstruct) != NULL) { (yyval.tfield)->set_xsd_attrs((yyvsp[-2].tstruct)); } if ((yyvsp[-1].ttype) != NULL) { (yyval.tfield)->annotations_ = (yyvsp[-1].ttype)->annotations_; delete (yyvsp[-1].ttype); } } #line 2388 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 76: #line 891 "thrift/thrifty.yy" /* yacc.c:1646 */ { if ((yyvsp[-1].iconst) <= 0) { if (g_allow_neg_field_keys) { /* * g_allow_neg_field_keys exists to allow users to add explicitly * specified key values to old .thrift files without breaking * protocol compatibility. */ if ((yyvsp[-1].iconst) != y_field_val) { /* * warn if the user-specified negative value isn't what * thrift would have auto-assigned. */ pwarning(1, "Nonpositive field key (%" PRIi64") differs from what would be " "auto-assigned by thrift (%d).\n", (yyvsp[-1].iconst), y_field_val); } /* * Leave $1 as-is, and update y_field_val to be one less than $1. * The FieldList parsing will catch any duplicate key values. */ y_field_val = static_cast<int32_t>((yyvsp[-1].iconst) - 1); (yyval.tfieldid).value = static_cast<int32_t>((yyvsp[-1].iconst)); (yyval.tfieldid).auto_assigned = false; } else { pwarning(1, "Nonpositive value (%d) not allowed as a field key.\n", (yyvsp[-1].iconst)); (yyval.tfieldid).value = y_field_val--; (yyval.tfieldid).auto_assigned = true; } } else { (yyval.tfieldid).value = static_cast<int32_t>((yyvsp[-1].iconst)); (yyval.tfieldid).auto_assigned = false; } if( (SHRT_MIN > (yyval.tfieldid).value) || ((yyval.tfieldid).value > SHRT_MAX)) { pwarning(1, "Field key (%d) exceeds allowed range (%d..%d).\n", (yyval.tfieldid).value, SHRT_MIN, SHRT_MAX); } } #line 2431 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 77: #line 930 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tfieldid).value = y_field_val--; (yyval.tfieldid).auto_assigned = true; if( (SHRT_MIN > (yyval.tfieldid).value) || ((yyval.tfieldid).value > SHRT_MAX)) { pwarning(1, "Field key (%d) exceeds allowed range (%d..%d).\n", (yyval.tfieldid).value, SHRT_MIN, SHRT_MAX); } } #line 2444 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 78: #line 941 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = true; } #line 2452 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 79: #line 945 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tbool) = false; } #line 2460 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 80: #line 951 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.ereq) = t_field::T_REQUIRED; } #line 2468 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 81: #line 955 "thrift/thrifty.yy" /* yacc.c:1646 */ { if (g_arglist) { if (g_parse_mode == PROGRAM) { pwarning(1, "optional keyword is ignored in argument lists.\n"); } (yyval.ereq) = t_field::T_OPT_IN_REQ_OUT; } else { (yyval.ereq) = t_field::T_OPTIONAL; } } #line 2483 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 82: #line 966 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.ereq) = t_field::T_OPT_IN_REQ_OUT; } #line 2491 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 83: #line 972 "thrift/thrifty.yy" /* yacc.c:1646 */ { if (g_parse_mode == PROGRAM) { (yyval.tconstv) = (yyvsp[0].tconstv); } else { (yyval.tconstv) = NULL; } } #line 2503 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 84: #line 980 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.tconstv) = NULL; } #line 2511 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 85: #line 986 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FunctionType -> FieldType"); (yyval.ttype) = (yyvsp[0].ttype); } #line 2520 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 86: #line 991 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FunctionType -> tok_void"); (yyval.ttype) = g_type_void; } #line 2529 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 87: #line 998 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FieldType -> tok_identifier"); if (g_parse_mode == INCLUDES) { // Ignore identifiers in include mode (yyval.ttype) = NULL; } else { // Lookup the identifier in the current scope (yyval.ttype) = g_scope->get_type((yyvsp[0].id)); if ((yyval.ttype) == NULL) { /* * Either this type isn't yet declared, or it's never declared. Either way allow it and we'll figure it out during generation. */ (yyval.ttype) = new t_typedef(g_program, (yyvsp[0].id), true); } } } #line 2552 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 88: #line 1017 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FieldType -> BaseType"); (yyval.ttype) = (yyvsp[0].ttype); } #line 2561 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 89: #line 1022 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("FieldType -> ContainerType"); (yyval.ttype) = (yyvsp[0].ttype); } #line 2570 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 90: #line 1028 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> SimpleBaseType TypeAnnotations"); if ((yyvsp[0].ttype) != NULL) { (yyval.ttype) = new t_base_type(*static_cast<t_base_type*>((yyvsp[-1].ttype))); (yyval.ttype)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } else { (yyval.ttype) = (yyvsp[-1].ttype); } } #line 2585 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 91: #line 1041 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_string"); (yyval.ttype) = g_type_string; } #line 2594 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 92: #line 1046 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_binary"); (yyval.ttype) = g_type_binary; } #line 2603 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 93: #line 1051 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_slist"); (yyval.ttype) = g_type_slist; } #line 2612 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 94: #line 1056 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_bool"); (yyval.ttype) = g_type_bool; } #line 2621 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 95: #line 1061 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_i8"); (yyval.ttype) = g_type_i8; } #line 2630 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 96: #line 1066 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_i16"); (yyval.ttype) = g_type_i16; } #line 2639 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 97: #line 1071 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_i32"); (yyval.ttype) = g_type_i32; } #line 2648 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 98: #line 1076 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_i64"); (yyval.ttype) = g_type_i64; } #line 2657 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 99: #line 1081 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("BaseType -> tok_double"); (yyval.ttype) = g_type_double; } #line 2666 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 100: #line 1087 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ContainerType -> SimpleContainerType TypeAnnotations"); (yyval.ttype) = (yyvsp[-1].ttype); if ((yyvsp[0].ttype) != NULL) { (yyval.ttype)->annotations_ = (yyvsp[0].ttype)->annotations_; delete (yyvsp[0].ttype); } } #line 2679 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 101: #line 1098 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SimpleContainerType -> MapType"); (yyval.ttype) = (yyvsp[0].ttype); } #line 2688 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 102: #line 1103 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SimpleContainerType -> SetType"); (yyval.ttype) = (yyvsp[0].ttype); } #line 2697 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 103: #line 1108 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SimpleContainerType -> ListType"); (yyval.ttype) = (yyvsp[0].ttype); } #line 2706 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 104: #line 1115 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("MapType -> tok_map <FieldType, FieldType>"); (yyval.ttype) = new t_map((yyvsp[-3].ttype), (yyvsp[-1].ttype)); if ((yyvsp[-5].id) != NULL) { ((t_container*)(yyval.ttype))->set_cpp_name(std::string((yyvsp[-5].id))); } } #line 2718 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 105: #line 1125 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("SetType -> tok_set<FieldType>"); (yyval.ttype) = new t_set((yyvsp[-1].ttype)); if ((yyvsp[-3].id) != NULL) { ((t_container*)(yyval.ttype))->set_cpp_name(std::string((yyvsp[-3].id))); } } #line 2730 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 106: #line 1135 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("ListType -> tok_list<FieldType>"); check_for_list_of_bytes((yyvsp[-2].ttype)); (yyval.ttype) = new t_list((yyvsp[-2].ttype)); if ((yyvsp[0].id) != NULL) { ((t_container*)(yyval.ttype))->set_cpp_name(std::string((yyvsp[0].id))); } } #line 2743 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 107: #line 1146 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.id) = (yyvsp[0].id); } #line 2751 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 108: #line 1150 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.id) = NULL; } #line 2759 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 109: #line 1156 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeAnnotations -> ( TypeAnnotationList )"); (yyval.ttype) = (yyvsp[-1].ttype); } #line 2768 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 110: #line 1161 "thrift/thrifty.yy" /* yacc.c:1646 */ { (yyval.ttype) = NULL; } #line 2776 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 111: #line 1167 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeAnnotationList -> TypeAnnotationList , TypeAnnotation"); (yyval.ttype) = (yyvsp[-1].ttype); (yyval.ttype)->annotations_[(yyvsp[0].tannot)->key] = (yyvsp[0].tannot)->val; delete (yyvsp[0].tannot); } #line 2787 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 112: #line 1174 "thrift/thrifty.yy" /* yacc.c:1646 */ { /* Just use a dummy structure to hold the annotations. */ (yyval.ttype) = new t_struct(g_program); } #line 2796 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 113: #line 1181 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeAnnotation -> TypeAnnotationValue"); (yyval.tannot) = new t_annotation; (yyval.tannot)->key = (yyvsp[-2].id); (yyval.tannot)->val = (yyvsp[-1].id); } #line 2807 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 114: #line 1190 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeAnnotationValue -> = tok_literal"); (yyval.id) = (yyvsp[0].id); } #line 2816 "thrift/thrifty.cc" /* yacc.c:1646 */ break; case 115: #line 1195 "thrift/thrifty.yy" /* yacc.c:1646 */ { pdebug("TypeAnnotationValue ->"); (yyval.id) = strdup("1"); } #line 2825 "thrift/thrifty.cc" /* yacc.c:1646 */ break; #line 2829 "thrift/thrifty.cc" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } #line 1200 "thrift/thrifty.yy" /* yacc.c:1906 */
31.644539
145
0.546714
NorbertoBurciaga
ed907a846ceb8f108937f2bef8431448ebf24349
961
cpp
C++
Roteiro_00/parouimpar.cpp
sigismundo03/Maratona-de-programacao-facape
8e28f1674053f1d1ccd5541e08651e0c230f4ade
[ "MIT" ]
null
null
null
Roteiro_00/parouimpar.cpp
sigismundo03/Maratona-de-programacao-facape
8e28f1674053f1d1ccd5541e08651e0c230f4ade
[ "MIT" ]
null
null
null
Roteiro_00/parouimpar.cpp
sigismundo03/Maratona-de-programacao-facape
8e28f1674053f1d1ccd5541e08651e0c230f4ade
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool par( int value){ bool verdade = false; if((value/2) == 0){ verdade = true; } return verdade; } int main(){ string name[2], nomevecedor[1002]; int valor,valor2,teste=1,i,tamanho,tamanhodovecedor = 0; while(cin>>tamanho && tamanho != 0){ cin>>name[0]>>name[1]; for(i = 0; i < tamanho;i++){ cin>>valor>>valor2; if((valor+valor2)%2 == 0 ){ nomevecedor[tamanhodovecedor] = name[0]; tamanhodovecedor++; }else{ nomevecedor[tamanhodovecedor] = name[1]; tamanhodovecedor++; } } cout<<"Teste "<<teste<<endl; for(i = 0; i < tamanhodovecedor;i++){ cout<<nomevecedor[i]<<endl; } /// zerando variaves teste++; tamanhodovecedor =0; } return 0; }
20.020833
61
0.477627
sigismundo03
ed93be1db3b51f31bc72d97a68975c9b121e1fdf
547
cpp
C++
components/tiled_visuals.cpp
ZamfirYonchev/Jam-game-engine
2c72ce6901d5b5fe6d273f532843f83d8a826523
[ "MIT" ]
null
null
null
components/tiled_visuals.cpp
ZamfirYonchev/Jam-game-engine
2c72ce6901d5b5fe6d273f532843f83d8a826523
[ "MIT" ]
null
null
null
components/tiled_visuals.cpp
ZamfirYonchev/Jam-game-engine
2c72ce6901d5b5fe6d273f532843f83d8a826523
[ "MIT" ]
null
null
null
/* * tiled_visuals.cpp * * Created on: Dec 4, 2021 * Author: zamfi */ #include "tiled_visuals.h" #include "position.h" int TiledVisuals::repeat_x() const { return std::ceil(m_position_accessor(m_self_id).w()/m_tile_w); } int TiledVisuals::repeat_y() const { return std::ceil(m_position_accessor(m_self_id).h()/m_tile_h); } void TiledVisuals::set_repeat_x(const int val) { m_tile_w = m_position_accessor(m_self_id).w()/val; } void TiledVisuals::set_repeat_y(const int val) { m_tile_h = m_position_accessor(m_self_id).h()/val; }
18.233333
63
0.722121
ZamfirYonchev
ed9f4a82e3b131a9d8d0446d386a85ae7aff2e1d
5,534
cpp
C++
Code/settings/DialogGraphOption.cpp
jiaguobing/FastCAE
2348ab87e83fe5c704e4c998cf391229c25ac5d5
[ "BSD-3-Clause" ]
2
2020-02-21T01:04:35.000Z
2020-02-21T03:35:37.000Z
Code/settings/DialogGraphOption.cpp
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2020-03-06T04:49:42.000Z
2020-03-06T04:49:42.000Z
Code/settings/DialogGraphOption.cpp
Sunqia/FastCAE
cbc023fe07b6e306ceefae8b8bd7c12bc1562acb
[ "BSD-3-Clause" ]
1
2021-11-21T13:03:26.000Z
2021-11-21T13:03:26.000Z
#include "DialogGraphOption.h" #include "GraphOption.h" #include "ui_DialogGraphOption.h" #include "mainWindow/mainWindow.h" namespace Setting { GraphOptionDialog::GraphOptionDialog(GUI::MainWindow* mainwindow, GraphOption* op) :/* QFDialog(mainwindow),*/ _ui(new Ui::GraphOptionDialog), _mainWindow(mainwindow), _graphOption(op) { _ui->setupUi(this); connect(this, SIGNAL(updateGraph()), mainwindow, SIGNAL(updateGraphOptionsSig())); init(); } GraphOptionDialog::~GraphOptionDialog() { if (_ui != nullptr) delete _ui; } void GraphOptionDialog::init() { bool has = false; QColor color; //background top _ui->bgTopComboBox->appendBackgroundColors(); color = _graphOption->getBackgroundTopColor(); has = _ui->bgTopComboBox->hasColor(color); if (!has) _ui->bgTopComboBox->updateOtherColor(color); _ui->bgTopComboBox->setCurrentColor(color); //background bottom _ui->bgBottomComboBox->appendBackgroundColors(); color = _graphOption->getBackgroundBottomColor(); has = _ui->bgBottomComboBox->hasColor(color); if (!has) _ui->bgBottomComboBox->updateOtherColor(color); _ui->bgBottomComboBox->setCurrentColor(color); //high light _ui->highLightComboBox->appendPredefinedColors(); color = _graphOption->getHighLightColor(); has = _ui->highLightComboBox->hasColor(color); if (!has) _ui->highLightComboBox->updateOtherColor(color); _ui->highLightComboBox->setCurrentColor(color); //pre high light _ui->preHighLightcomboBox->appendPredefinedColors(); color = _graphOption->getPreHighLightColor(); has = _ui->preHighLightcomboBox->hasColor(color); if (!has) _ui->preHighLightcomboBox->updateOtherColor(color); _ui->preHighLightcomboBox->setCurrentColor(color); //geo surface color _ui->geoSurfaceComboBox->appendPredefinedColors(); color = _graphOption->getGeometrySurfaceColor(); has = _ui->geoSurfaceComboBox->hasColor(color); if (!has) _ui->geoSurfaceComboBox->updateOtherColor(color); _ui->geoSurfaceComboBox->setCurrentColor(color); //geo curve color _ui->geoCurveComboBox->appendPredefinedColors(); color = _graphOption->getGeometryCurveColor(); has = _ui->geoCurveComboBox->hasColor(color); if (!has) _ui->geoCurveComboBox->updateOtherColor(color); _ui->geoCurveComboBox->setCurrentColor(color); //geo point color _ui->geoPointComboBox->appendPredefinedColors(); color = _graphOption->getGeometryPointColor(); has = _ui->geoPointComboBox->hasColor(color); if (!has) _ui->geoPointComboBox->updateOtherColor(color); _ui->geoPointComboBox->setCurrentColor(color); //mesh face _ui->meshFaceComboBox->appendPredefinedColors(); color = _graphOption->getMeshFaceColor(); has = _ui->meshFaceComboBox->hasColor(color); if (!has) _ui->meshFaceComboBox->updateOtherColor(color); _ui->meshFaceComboBox->setCurrentColor(color); //mesh edge _ui->meshEdgeConboBox->appendPredefinedColors(); color = _graphOption->getMeshEdgeColor(); has = _ui->meshEdgeConboBox->hasColor(color); if (!has) _ui->meshEdgeConboBox->updateOtherColor(color); _ui->meshEdgeConboBox->setCurrentColor(color); //mesh node _ui->meshNodeComboBox->appendPredefinedColors(); color = _graphOption->getMeshNodeColor(); has = _ui->meshNodeComboBox->hasColor(color); if (!has) _ui->meshNodeComboBox->updateOtherColor(color); _ui->meshNodeComboBox->setCurrentColor(color); //mesh node size float nodesize = _graphOption->getMeshNodeSize(); _ui->meshNodeSpinBox->setValue(nodesize); //mesh edge size float edgewidth = _graphOption->getMeshEdgeWidth(); _ui->meshEdgeSpinBox->setValue(edgewidth); //geo point size float pointsize = _graphOption->getGeoPointSize(); _ui->geoPointSpinBox->setValue(pointsize); //geo curve width float curvewidth = _graphOption->getGeoCurveWidth(); _ui->geoCurveSpinBox->setValue(curvewidth); int trans = _graphOption->getTransparency(); _ui->TranspSlider->setValue(trans); } void GraphOptionDialog::accept() { _graphOption->setBackgroundTopColor(_ui->bgTopComboBox->currentColor()); _graphOption->setBackgroundBottomColor(_ui->bgBottomComboBox->currentColor()); _graphOption->setHighLightColor(_ui->highLightComboBox->currentColor()); _graphOption->sePretHighLightColor(_ui->preHighLightcomboBox->currentColor()); _graphOption->setGeometrySurfaceColor(_ui->geoSurfaceComboBox->currentColor()); _graphOption->setGeometryCurveColor(_ui->geoCurveComboBox->currentColor()); _graphOption->setGeometryPointColor(_ui->geoPointComboBox->currentColor()); _graphOption->setMeshFaceColor(_ui->meshFaceComboBox->currentColor()); _graphOption->setMeshEdgeColor(_ui->meshEdgeConboBox->currentColor()); _graphOption->setMeshNodeColor(_ui->meshNodeComboBox->currentColor()); _graphOption->setMeshNodeSize(_ui->meshNodeSpinBox->value()); _graphOption->setMeshEdgeWidth(_ui->meshEdgeSpinBox->value()); _graphOption->setGeoPointSize(_ui->geoPointSpinBox->value()); _graphOption->setGeoCurveWidth(_ui->geoCurveSpinBox->value()); _graphOption->setTransparency(_ui->TranspSlider->value()); emit updateGraph(); } void GraphOptionDialog::on_out_ApplyButton_clicked() { accept(); } void GraphOptionDialog::on_out_CancelButton_clicked() { QDialog::reject(); // this->close(); } void GraphOptionDialog::on_out_OkButton_clicked() { accept(); QDialog::accept(); // QDialog::accepted(); } }
36.649007
112
0.738164
jiaguobing
eda27ca825d7324cc3cf8e6868e5cd8966f862cd
4,049
cpp
C++
Boss/Mod/NodeBalanceSwapper.cpp
willcl-ark/clboss
09a802ca00c04bf480c5f2d388f4cbd4500e3211
[ "MIT" ]
null
null
null
Boss/Mod/NodeBalanceSwapper.cpp
willcl-ark/clboss
09a802ca00c04bf480c5f2d388f4cbd4500e3211
[ "MIT" ]
null
null
null
Boss/Mod/NodeBalanceSwapper.cpp
willcl-ark/clboss
09a802ca00c04bf480c5f2d388f4cbd4500e3211
[ "MIT" ]
null
null
null
#include"Boss/Mod/NodeBalanceSwapper.hpp" #include"Boss/ModG/Swapper.hpp" #include"Boss/Msg/ListpeersResult.hpp" #include"Boss/Msg/OnchainFee.hpp" #include"Boss/log.hpp" #include"Jsmn/Object.hpp" #include"Ln/Amount.hpp" #include"S/Bus.hpp" #include"Util/make_unique.hpp" #include<sstream> namespace { /* The minimum percentage of total channel capacity that is * incoming. * * Cannot be higher than 50. */ auto const min_receivable_percent = double(35); /* If fees are high, we do not swap, ***unless*** our incoming * capacity is below this percentage, in which case we end up * triggering anyway. */ auto const min_receivable_percent_highfees = double(2.5); } namespace Boss { namespace Mod { class NodeBalanceSwapper::Impl : ModG::Swapper { private: std::unique_ptr<bool> fees_low; void start() { bus.subscribe<Msg::OnchainFee >([this](Msg::OnchainFee const& m) { if (!fees_low) fees_low = Util::make_unique<bool>(); *fees_low = m.fees_low; return Ev::lift(); }); bus.subscribe<Msg::ListpeersResult >([this](Msg::ListpeersResult const& m) { if (!fees_low) /* Pretend fees are high temporarily. */ fees_low = Util::make_unique<bool>(false); /* Analyze the result. */ auto total_recv = Ln::Amount::sat(0); auto total_send = Ln::Amount::sat(0); try { for ( auto i = std::size_t(0) ; i < m.peers.size() ; ++i ) { auto peer = m.peers[i]; auto channels = peer["channels"]; for ( auto j = std::size_t(0) ; j < channels.size() ; ++j ) { auto chan = channels[j]; /* Skip non-active channels. */ if ( std::string(chan["state"]) != "CHANNELD_NORMAL" ) continue; /* Skip unpublished channels, * they cannot be used for * forwarding anyway. */ if (chan["private"]) continue; auto recv = std::string(chan[ "receivable_msat" ]); auto send = std::string(chan[ "spendable_msat" ]); total_recv += Ln::Amount(recv); total_send += Ln::Amount(send); } } } catch (Jsmn::TypeError const&) { /* Should never happen.... */ auto os = std::ostringstream(); os << m.peers; return Boss::log( bus, Error , "NodeBalanceSwapper: " "Unexpected listpeers: %s" , os.str().c_str() ); } /* Avoid division by 0. */ if ( total_recv == Ln::Amount::sat(0) && total_send == Ln::Amount::sat(0) ) return Ev::lift(); auto total = total_recv + total_send; auto recv_ratio = total_recv / total; auto recv_percent = recv_ratio * 100; if (recv_percent >= min_receivable_percent) /* Nothing to do. */ return Ev::lift(); auto f = [ this , total_recv , total_send , recv_percent ]( Ln::Amount& amount , std::string& why ) { amount = ( (total_send - total_recv) * 2 ) / 3; auto os = std::ostringstream(); os << "receivable = " << total_recv << ", " << "spendable = " << total_send << "; " << "%receivable = " << recv_percent << "; " ; if (*fees_low) { os << "sending funds onchain"; why = os.str(); return true; } else if ( recv_percent > min_receivable_percent_highfees ) { os << "but fees are high"; why = os.str(); return false; } else { os << "fees are high but we have " << "too little receivable" ; why = os.str(); return false; } }; return trigger_swap(f); }); } public: explicit Impl(S::Bus& bus_) : ModG::Swapper( bus_ , "NodeBalanceSwapper" , "incoming_capacity_swapper" ) { start(); } }; NodeBalanceSwapper::NodeBalanceSwapper(NodeBalanceSwapper&&) =default; NodeBalanceSwapper& NodeBalanceSwapper::operator=(NodeBalanceSwapper&&) =default; NodeBalanceSwapper::~NodeBalanceSwapper() =default; NodeBalanceSwapper::NodeBalanceSwapper(S::Bus& bus) : pimpl(Util::make_unique<Impl>(bus)) { } }}
24.689024
71
0.588787
willcl-ark
eda2aa73b060b082fedbdad9fa793219be712cf6
1,846
cpp
C++
Strings/String Matching(or Searching) Algorithms/Using Trie/Creation, Insertion & Searching in a Trie.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
8
2021-02-13T17:07:27.000Z
2021-08-20T08:20:40.000Z
Strings/String Matching(or Searching) Algorithms/Using Trie/Creation, Insertion & Searching in a Trie.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
null
null
null
Strings/String Matching(or Searching) Algorithms/Using Trie/Creation, Insertion & Searching in a Trie.cpp
Edith-3000/Algorithmic-Implementations
7ff8cd615fd453a346b4e851606d47c26f05a084
[ "MIT" ]
5
2021-02-17T18:12:20.000Z
2021-10-10T17:49:34.000Z
// Trie is basically an n-ary tree. #include<bits/stdc++.h> using namespace std; // trie structure for inserting string consisting of lowercase // latin alphabets struct trie { // everything is by-default "public" in a struct // every trie node will contain an array/vector of // pointers each pointing to a similar trie // here we're taking size of the array as 26 trie *nxt[26]; // each trie structure will also contain a end marker // for indicating whether a string end on that trie node or nor bool ended; // constructor trie(){ for(int i = 0; i < 26; i++) nxt[i] = nullptr; ended = false; } }; // root node of the trie structure trie *root; void insert(string s) { trie *curr = root; for(int i = 0; i < s.size(); i++){ // if character not found create a new trie node if(curr->nxt[s[i] - 'a'] == nullptr){ curr->nxt[s[i] - 'a'] = new trie(); } // move forward curr = curr->nxt[s[i] - 'a']; } curr->ended = true; } bool search(string s) { trie *curr = root; for(int i = 0; i < s.size(); i++){ if(curr->nxt[s[i] - 'a'] == nullptr){ return false; } curr = curr->nxt[s[i] - 'a']; } return curr->ended; } int main() { ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); root = new trie(); // inserting different strings in the trie insert("kapil"); insert("choudhary"); insert("kalpana"); insert("kapaar"); // search for a string in the trie if(search("kapil")) cout << "String found." << "\n"; else cout << "String not found." << "\n"; if(search("chaudhary")) cout << "String found." << "\n"; else cout << "String not found." << "\n"; return 0; } /* Sample o/p: String found. String not found. */
21.218391
75
0.601842
Edith-3000
eda8b802fa30ed800d233182a2a1e63693ef05bb
2,147
cpp
C++
src/gui/widgetdrawsimple.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/gui/widgetdrawsimple.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/gui/widgetdrawsimple.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file widgetdrawsimple.cpp * @brief Base class for drawing widgets. * @author RinceWind * @date 2006-10-11 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/gui/precompiled.h" #include "o3d/gui/widgetdrawsimple.h" #include "o3d/engine/matrix.h" #include "o3d/engine/scene/scene.h" #include "o3d/engine/context.h" using namespace o3d; /*--------------------------------------------------------------------------------------- default constructor ---------------------------------------------------------------------------------------*/ WidgetDrawSimple::WidgetDrawSimple(Context *context, BaseObject *parent) : WidgetDrawMode(context, parent) { } WidgetDrawSimple::WidgetDrawSimple(WidgetDrawSimple &dup) : WidgetDrawMode(dup), m_WidgetSet(dup.m_WidgetSet) { } /*--------------------------------------------------------------------------------------- destructor ---------------------------------------------------------------------------------------*/ WidgetDrawSimple::~WidgetDrawSimple() { } /*--------------------------------------------------------------------------------------- Get base width/height ---------------------------------------------------------------------------------------*/ Int32 WidgetDrawSimple::getWidgetWidth() const { return m_WidgetSet.width; } Int32 WidgetDrawSimple::getWidgetHeight() const { return m_WidgetSet.height; } //--------------------------------------------------------------------------------------- // Draw //--------------------------------------------------------------------------------------- void WidgetDrawSimple::draw( Int32 x, Int32 y, Int32 width, Int32 height) { if (!m_material.getTechnique(0).getPass(0).getAmbientMap() || !m_material.getTechnique(0).getPass(0).getAmbientMap()->isValid()) return; if ((width > m_WidgetSet.width) || (height > m_WidgetSet.height)) repeatWidgetElement(m_WidgetSet, x, y, width, height); else drawWidgetElement(m_WidgetSet, x, y, width, height); // finally process the rendering m_material.processMaterial(*this, nullptr, nullptr, DrawInfo()); }
28.626667
89
0.489986
dream-overflow
eda92c81dc6761012687f1753c30ef7e7351dce4
132
hpp
C++
ares/ms/expansion/fmsound/fmsound.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/ms/expansion/fmsound/fmsound.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/ms/expansion/fmsound/fmsound.hpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
struct FMSoundUnit : Expansion { FMSoundUnit(Node::Port); ~FMSoundUnit(); auto serialize(serializer& s) -> void override; };
18.857143
49
0.69697
CasualPokePlayer
eda9730d1182545ac5d0354286e262798ae5082d
7,597
hpp
C++
include/nuls/system/math/elliptic_curve.hpp
ccccbjcn/nuls-v2-cplusplus-sdk
3d5a76452fe0673eba490b26e5a95fea3d5788df
[ "MIT" ]
1
2020-04-26T07:32:52.000Z
2020-04-26T07:32:52.000Z
include/nuls/system/math/elliptic_curve.hpp
CCC-NULS/nuls-cplusplus-sdk
3d5a76452fe0673eba490b26e5a95fea3d5788df
[ "MIT" ]
null
null
null
include/nuls/system/math/elliptic_curve.hpp
CCC-NULS/nuls-cplusplus-sdk
3d5a76452fe0673eba490b26e5a95fea3d5788df
[ "MIT" ]
null
null
null
/** * Copyright (c) 2020 libnuls developers (see AUTHORS) * * This file is part of libnuls. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBNULS_SYSTEM_ELLIPTIC_CURVE_HPP #define LIBNULS_SYSTEM_ELLIPTIC_CURVE_HPP #include <cstddef> #include <nuls/system/compat.hpp> #include <nuls/system/define.hpp> #include <nuls/system/math/hash.hpp> #include <nuls/system/utility/data.hpp> namespace libnuls { namespace system { /// The sign byte value for an even (y-valued) key. static BC_CONSTEXPR uint8_t ec_even_sign = 2; /// Private key: static BC_CONSTEXPR size_t ec_secret_size = 32; typedef byte_array<ec_secret_size> ec_secret; typedef std::vector<ec_secret> secret_list; /// Compressed public key: static BC_CONSTEXPR size_t ec_compressed_size = 33; typedef byte_array<ec_compressed_size> ec_compressed; typedef std::vector<ec_compressed> point_list; /// Uncompressed public key: static BC_CONSTEXPR size_t ec_uncompressed_size = 65; typedef byte_array<ec_uncompressed_size> ec_uncompressed; // Parsed ECDSA signature: static BC_CONSTEXPR size_t ec_signature_size = 64; typedef byte_array<ec_signature_size> ec_signature; // DER encoded signature: static BC_CONSTEXPR size_t max_der_signature_size = 72; typedef data_chunk der_signature; /// DER encoded signature with sighash byte for contract endorsement: static BC_CONSTEXPR size_t min_endorsement_size = 9; static BC_CONSTEXPR size_t max_endorsement_size = 73; typedef data_chunk endorsement; /// Recoverable ecdsa signature for message signing: struct BC_API recoverable_signature { ec_signature signature; uint8_t recovery_id; }; static BC_CONSTEXPR ec_compressed null_compressed_point = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static BC_CONSTEXPR ec_uncompressed null_uncompressed_point = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Add and multiply EC values // ---------------------------------------------------------------------------- /// Compute the sum a += G*b, where G is the curve's generator point. BC_API bool ec_add(ec_compressed& point, const ec_secret& scalar); /// Compute the sum a += G*b, where G is the curve's generator point. BC_API bool ec_add(ec_uncompressed& point, const ec_secret& scalar); /// Compute the sum a = (a + b) % n, where n is the curve order. BC_API bool ec_add(ec_secret& left, const ec_secret& right); /// Compute the product point *= secret. BC_API bool ec_multiply(ec_compressed& point, const ec_secret& scalar); /// Compute the product point *= secret. BC_API bool ec_multiply(ec_uncompressed& point, const ec_secret& scalar); /// Compute the product a = (a * b) % n, where n is the curve order. BC_API bool ec_multiply(ec_secret& left, const ec_secret& right); /// Negate a scalar. BC_API bool ec_negate(ec_secret& scalar); /// Invert a point (flip on Y axis). BC_API bool ec_negate(ec_compressed& point); /// Compute the addition of EC curve points. BC_API bool ec_sum(ec_compressed& result, const point_list& values); // Convert keys // ---------------------------------------------------------------------------- /// Convert an uncompressed public point to compressed. BC_API bool compress(ec_compressed& out, const ec_uncompressed& point); /// Convert a compressed public point to decompressed. BC_API bool decompress(ec_uncompressed& out, const ec_compressed& point); /// Convert a secret to a compressed public point. BC_API bool secret_to_public(ec_compressed& out, const ec_secret& secret); /// Convert a secret parameter to an uncompressed public point. BC_API bool secret_to_public(ec_uncompressed& out, const ec_secret& secret); // Verify keys // ---------------------------------------------------------------------------- /// Verify a secret. BC_API bool verify(const ec_secret& secret); /// Verify a point. BC_API bool verify(const ec_compressed& point); /// Verify a point. BC_API bool verify(const ec_uncompressed& point); // Detect public keys // ---------------------------------------------------------------------------- /// Determine if the compressed public key is even (y-valued). bool is_even_key(const ec_compressed& point); /// Fast detection of compressed public key structure. bool is_compressed_key(const data_slice& point); /// Fast detection of uncompressed public key structure. bool is_uncompressed_key(const data_slice& point); /// Fast detection of compressed or uncompressed public key structure. bool is_public_key(const data_slice& point); /// Fast detection of endorsement structure (DER with signature hash type). bool is_endorsement(const endorsement& endorsement); // DER parse/encode // ---------------------------------------------------------------------------- /// Parse an endorsement into signature hash type and DER signature. BC_API bool parse_endorsement(uint8_t& sighash_type, der_signature& der_signature, const endorsement& endorsement); /// Parse a DER encoded signature with optional strict DER enforcement. /// Treat an empty DER signature as invalid, in accordance with BIP66. BC_API bool parse_signature(ec_signature& out, const der_signature& der_signature, bool strict); /// Encode an EC signature as DER (strict). BC_API bool encode_signature(der_signature& out, const ec_signature& signature); // EC sign/verify // ---------------------------------------------------------------------------- /// Create a deterministic ECDSA signature using a private key. BC_API bool sign(ec_signature& out, const ec_secret& secret, const hash_digest& hash); /// Verify an EC signature using a compressed point. BC_API bool verify_signature(const ec_compressed& point, const hash_digest& hash, const ec_signature& signature); /// Verify an EC signature using an uncompressed point. BC_API bool verify_signature(const ec_uncompressed& point, const hash_digest& hash, const ec_signature& signature); /// Verify an EC signature using a potential point. BC_API bool verify_signature(const data_slice& point, const hash_digest& hash, const ec_signature& signature); // Recoverable sign/recover // ---------------------------------------------------------------------------- /// Create a recoverable signature for use in message signing. BC_API bool sign_recoverable(recoverable_signature& out, const ec_secret& secret, const hash_digest& hash); /// Recover the compressed point from a recoverable message signature. BC_API bool recover_public(ec_compressed& out, const recoverable_signature& recoverable, const hash_digest& hash); /// Recover the uncompressed point from a recoverable message signature. BC_API bool recover_public(ec_uncompressed& out, const recoverable_signature& recoverable, const hash_digest& hash); } // namespace system } // namespace libnuls #endif
35.834906
80
0.700013
ccccbjcn
edaa417d0ed6c5ff860a967f5b291a2fd1d15247
359
cpp
C++
OpenTESArena/src/UI/Button.cpp
TotalCaesar659/OpenTESArena
e72eda7a5e03869309b5ed7375f432d0ad826ff3
[ "MIT" ]
742
2016-03-09T17:18:55.000Z
2022-03-21T07:23:47.000Z
OpenTESArena/src/UI/Button.cpp
TotalCaesar659/OpenTESArena
e72eda7a5e03869309b5ed7375f432d0ad826ff3
[ "MIT" ]
196
2016-06-07T15:19:21.000Z
2021-12-12T16:50:58.000Z
OpenTESArena/src/UI/Button.cpp
TotalCaesar659/OpenTESArena
e72eda7a5e03869309b5ed7375f432d0ad826ff3
[ "MIT" ]
85
2016-04-17T13:25:16.000Z
2022-03-25T06:45:15.000Z
#include "Button.h" ButtonProxy::ButtonProxy(MouseButtonType buttonType, const RectFunction &rectFunc, const Callback &callback, const ActiveFunction &isActiveFunc) : rectFunc(rectFunc), callback(callback), isActiveFunc(isActiveFunc) { this->buttonType = buttonType; } ButtonProxy::ButtonProxy() { this->buttonType = static_cast<MouseButtonType>(-1); }
25.642857
82
0.78273
TotalCaesar659
edaba1edd7d4df4d79b582400024c6bc62b2bb0e
215
cpp
C++
C++/sources/opencv_opengl_toolbox/fileviewer.cpp
sandeepmanandhargithub/Toolbox-ComputerVision
9104a7a020944f2e4cbf383c5c4c7de0d8eab3ea
[ "MIT" ]
null
null
null
C++/sources/opencv_opengl_toolbox/fileviewer.cpp
sandeepmanandhargithub/Toolbox-ComputerVision
9104a7a020944f2e4cbf383c5c4c7de0d8eab3ea
[ "MIT" ]
null
null
null
C++/sources/opencv_opengl_toolbox/fileviewer.cpp
sandeepmanandhargithub/Toolbox-ComputerVision
9104a7a020944f2e4cbf383c5c4c7de0d8eab3ea
[ "MIT" ]
null
null
null
#include "fileviewer.h" #include "ui_fileviewer.h" fileViewer::fileViewer(QWidget *parent) : QWidget(parent), ui(new Ui::fileViewer) { ui->setupUi(this); } fileViewer::~fileViewer() { delete ui; }
14.333333
41
0.665116
sandeepmanandhargithub
edb054bbcd24886cec7ae84ec92ef2abef0d4913
153
cpp
C++
recipes/libmp3lame/all/test_package/test_package.cpp
nadzkie0/conan-center-index
fde12bf20f2c4cb6a7554d09a5c9433a0f5cb72c
[ "MIT" ]
3
2020-04-16T15:01:33.000Z
2022-01-13T08:05:47.000Z
recipes/libmp3lame/all/test_package/test_package.cpp
nadzkie0/conan-center-index
fde12bf20f2c4cb6a7554d09a5c9433a0f5cb72c
[ "MIT" ]
33
2020-02-18T15:54:50.000Z
2022-03-28T08:54:10.000Z
recipes/libmp3lame/all/test_package/test_package.cpp
nadzkie0/conan-center-index
fde12bf20f2c4cb6a7554d09a5c9433a0f5cb72c
[ "MIT" ]
8
2021-05-24T11:46:53.000Z
2021-12-14T17:15:47.000Z
#include <cstdlib> #include <iostream> #include "lame/lame.h" int main() { std::cout << get_lame_version() << std::endl; return EXIT_SUCCESS; }
15.3
49
0.653595
nadzkie0
edbb3315df7384f29c0b0b59fa97de4cb8bdfb8c
5,645
cpp
C++
src/NovelRT.Interop/Graphics/NrtImageRect.cpp
ClxS/NovelRT
f6703813b426dd906952fbf65986edf65ad4a55e
[ "MIT" ]
null
null
null
src/NovelRT.Interop/Graphics/NrtImageRect.cpp
ClxS/NovelRT
f6703813b426dd906952fbf65986edf65ad4a55e
[ "MIT" ]
null
null
null
src/NovelRT.Interop/Graphics/NrtImageRect.cpp
ClxS/NovelRT
f6703813b426dd906952fbf65986edf65ad4a55e
[ "MIT" ]
null
null
null
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root // for more information. #include <NovelRT.Interop/Graphics/NrtImageRect.h> #include <NovelRT.Interop/NrtErrorHandling.h> #include <NovelRT.h> #include <list> using namespace NovelRT::Graphics; using namespace NovelRT::Maths; using namespace NovelRT; #ifdef __cplusplus extern "C" { #endif NrtTransform Nrt_ImageRect_getTransform(NrtImageRectHandle rect) { ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); Transform cppTransform = imageRectPtr->transform(); return *reinterpret_cast<NrtTransform*>(&cppTransform); } NrtResult Nrt_ImageRect_setTransform(NrtImageRectHandle rect, NrtTransform inputTransform) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); imageRectPtr->transform() = *reinterpret_cast<Transform*>(&inputTransform); return NRT_SUCCESS; } int32_t Nrt_ImageRect_getLayer(NrtImageRectHandle rect) { ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); return imageRectPtr->layer(); } NrtResult Nrt_ImageRect_setLayer(NrtImageRectHandle rect, int32_t inputLayer) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); imageRectPtr->layer() = inputLayer; return NRT_SUCCESS; } NrtBool Nrt_ImageRect_getActive(NrtImageRectHandle rect) { ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); if (imageRectPtr->getActive()) { return NRT_TRUE; } return NRT_FALSE; } NrtResult Nrt_ImageRect_setActive(NrtImageRectHandle rect, NrtBool inputBool) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); if (inputBool == NRT_TRUE) { imageRectPtr->setActive(true); } else { imageRectPtr->setActive(false); } return NRT_SUCCESS; } NrtResult Nrt_ImageRect_executeObjectBehaviour(NrtImageRectHandle rect) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); imageRectPtr->executeObjectBehaviour(); return NRT_SUCCESS; } NrtResult Nrt_ImageRect_getTexture(NrtImageRectHandle rect, NrtTextureHandle* outputTexture) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); auto texture = imageRectPtr->texture(); *outputTexture = reinterpret_cast<NrtTextureHandle>(texture.get()); return NRT_SUCCESS; } NrtResult Nrt_ImageRect_setTexture(NrtImageRectHandle rect, NrtTextureHandle inputTexture) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); imageRectPtr->texture() = reinterpret_cast<Texture*>(inputTexture)->shared_from_this(); return NRT_SUCCESS; } NrtResult Nrt_ImageRect_getColourTint(NrtImageRectHandle rect, NrtRGBAConfigHandle* outputColourTint) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); auto colourTint = new RGBAConfig(0, 0, 0, 0); *colourTint = imageRectPtr->colourTint(); *outputColourTint = reinterpret_cast<NrtRGBAConfigHandle>(colourTint); return NRT_SUCCESS; } NrtResult Nrt_ImageRect_setColourTint(NrtImageRectHandle rect, NrtRGBAConfigHandle inputColourTint) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } ImageRect* imageRectPtr = reinterpret_cast<ImageRect*>(rect); imageRectPtr->colourTint() = *reinterpret_cast<RGBAConfig*>(inputColourTint); return NRT_SUCCESS; } NrtResult Nrt_ImageRect_getAsRenderObjectPtr(NrtImageRectHandle rect, NrtRenderObjectHandle* outputRenderObject) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } if (outputRenderObject == nullptr) { Nrt_setErrMsgIsNullptrInternal(); } *outputRenderObject = reinterpret_cast<NrtRenderObjectHandle>(rect); return NRT_SUCCESS; } NrtResult Nrt_ImageRect_destroy(NrtImageRectHandle rect) { if (rect == nullptr) { Nrt_setErrMsgIsNullptrInternal(); return NRT_FAILURE_NULL_INSTANCE_PROVIDED; } delete reinterpret_cast<ImageRect*>(rect); return NRT_SUCCESS; } #ifdef __cplusplus } #endif
27.945545
119
0.656156
ClxS
edbe8a89f1a2fe4c4176f05407a1d95d8d01af0c
672
hpp
C++
libs/naming_base/include/hpx/naming_base.hpp
weilewei/hpx
49eb429a028f04fa4ed0c3860933d0fcced48792
[ "BSL-1.0" ]
null
null
null
libs/naming_base/include/hpx/naming_base.hpp
weilewei/hpx
49eb429a028f04fa4ed0c3860933d0fcced48792
[ "BSL-1.0" ]
null
null
null
libs/naming_base/include/hpx/naming_base.hpp
weilewei/hpx
49eb429a028f04fa4ed0c3860933d0fcced48792
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2016 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef HPX_RUNTIME_NAMING_TYPES_FWD_HPP #define HPX_RUNTIME_NAMING_TYPES_FWD_HPP #include <hpx/config.hpp> #include <cstdint> namespace hpx { namespace naming { using component_type = std::int32_t; using address_type = std::uint64_t; HPX_CONSTEXPR_OR_CONST std::uint32_t invalid_locality_id = ~static_cast<std::uint32_t>(0); }} // namespace hpx::naming #endif
25.846154
80
0.732143
weilewei
edbf129c46b6696275ba0d6ec26628db05389210
1,449
cpp
C++
LeetCode/Problems/Algorithms/#756_PyramidTransitionMatrix_sol2_recursive_backtracking_(A^(N^2))_time_O(N^2)_extra_space_4ms_9.2MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#756_PyramidTransitionMatrix_sol2_recursive_backtracking_(A^(N^2))_time_O(N^2)_extra_space_4ms_9.2MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#756_PyramidTransitionMatrix_sol2_recursive_backtracking_(A^(N^2))_time_O(N^2)_extra_space_4ms_9.2MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { private: unordered_map<string, vector<char>> candidates; void back(string& colors, int pos1, int pos2, const vector<bool>& IS_ROW_END, bool& isValid){ if(pos2 == colors.length()){ isValid = true; } if(isValid){ return; } string currentPair = colors.substr(pos1, 2); for(char candidate: candidates[currentPair]){ colors[pos2] = candidate; back(colors, pos1 + 1 + IS_ROW_END[pos1 + 1], pos2 + 1, IS_ROW_END, isValid); } } public: bool pyramidTransition(string bottom, vector<string>& allowed) { // Step 1: store the candidates candidates.clear(); for(const string& T: allowed){ candidates[T.substr(0, 2)].push_back(T[2]); } // Step 2: init colors and isRowEnd const int N = bottom.length(); const int MAX_SIZE = N * (N + 1) / 2; string colors = bottom; colors.resize(MAX_SIZE); vector<bool> isRowEnd(MAX_SIZE, false); for(int rowSize = N, idx = 0; rowSize >= 1; rowSize -= 1){ isRowEnd[idx + rowSize - 1] = true; idx += rowSize; } // Step 3: backtracking bool isValid = false; back(colors, 0, N, isRowEnd, isValid); return isValid; } };
30.829787
98
0.510007
Tudor67
edbfc6e1df7589ffdc7fcdeea026a39f54dff27e
3,891
cpp
C++
src/Level.cpp
p-mccusker/Gloom-Editor
58ca43c7897f169311a084094b3f9852e56873cf
[ "Apache-2.0" ]
null
null
null
src/Level.cpp
p-mccusker/Gloom-Editor
58ca43c7897f169311a084094b3f9852e56873cf
[ "Apache-2.0" ]
null
null
null
src/Level.cpp
p-mccusker/Gloom-Editor
58ca43c7897f169311a084094b3f9852e56873cf
[ "Apache-2.0" ]
null
null
null
#include "Level.h" Level::Level(uint rows, uint columns, uint height) { //Default width and height of 40 pixels for each tile _cellHeight = _cellWidth = 40; for (int i = 0; i < height; i++) { vector<vector<shared_ptr<Cell>>> grid; uint yCoord = 0; for (int j = 0; j < rows; j++) { uint xCoord = 0; vector<shared_ptr<Cell>> line; for (int k = 0; k < columns; k++) { line.push_back(make_shared<Cell>(k, j, i, _cellHeight, _cellWidth, xCoord, yCoord)); xCoord += _cellWidth; } grid.push_back(line); yCoord += _cellHeight; } _cells.push_back(grid); } } Level::~Level() { } /// <summary> /// Number of columns, x-coordinate /// </summary> /// <returns></returns> uint Level::Width() { return _cells[0][0].size(); } /// <summary> /// Number of rows, y-coordinate /// </summary> /// <returns></returns> uint Level::Length() { return _cells[0].size(); } /// <summary> /// Number of grids, z-coordinate /// </summary> /// <returns></returns> uint Level::Height() { return _cells.size(); } /// <summary> /// Sets the width of each cell in the level in pixels /// </summary> /// <param name="w"></param> void Level::setCellWidth(uint w) { _cellWidth = w; for (auto& grid : _cells) { for (auto& row : grid) { for (auto& cell : row) { cell->setWidth(_cellWidth); } } } } /// <summary> /// Sets the height of each cell in the level in pixels /// </summary> /// <param name="w"></param> void Level::setCellHeight(uint h) { _cellHeight = h; for (auto& grid : _cells) { for (auto& row : grid) { for (auto& cell : row) { cell->setHeight(_cellHeight); } } } } /// <summary> /// increases the width of all cells by w /// </summary> /// <param name="w"></param> void Level::incCellWidth(uint w) { _cellWidth += w; for (auto& grid : _cells) { for (auto& row : grid) { for (auto& cell : row) { cell->setWidth(_cellWidth); } } } } /// <summary> /// increases the height of all cells by h /// </summary> /// <param name="w"></param> void Level::incCellHeight(uint h) { _cellHeight += h; for (auto& grid : _cells) { for (auto& row : grid) { for (auto& cell : row) { cell->setHeight(_cellHeight); } } } } /// <summary> /// decreases the width of all cells by w /// </summary> /// <param name="w"></param> void Level::decCellWidth(uint w) { _cellWidth -= w; for (auto& grid : _cells) { for (auto& row : grid) { for (auto& cell : row) { cell->setWidth(_cellWidth); } } } } /// <summary> /// decreases the height of all cells by h /// </summary> /// <param name="w"></param> void Level::decCellHeight(uint h) { _cellHeight -= h; for (auto& grid : _cells) { for (auto& row : grid) { for (auto& cell : row) { cell->setHeight(_cellHeight); } } } } void Level::addColumns(uint n) { const uint width = Width(); for (uint z = 0; z < Height(); z++) { for (uint y = 0; y < Length(); y++) { for (uint x = width; x < width+n; x++) { _cells[z][y].push_back(make_shared<Cell>(x,y,z)); } } } } void Level::addRows(uint n) { const uint length = Length(); for (uint z = 0; z < Height(); z++) { for (uint y = length; y < length+n; y++) { vector<shared_ptr<Cell>> line; for (uint x = 0; x < Width(); x++) { line.push_back(make_shared<Cell>(x, y, z)); } _cells[z].push_back(line); } } } void Level::addGrids(uint n) { // May need to add ability to decide where to place grid in level const uint height = Height(); for (uint z = height; z < height + n; z++) { vector<vector<shared_ptr<Cell>>> grid; for (uint y = 0; y < Length(); y++) { vector<shared_ptr<Cell>> line; for (uint x = Width(); x < Width() + n; x++) { line.push_back(make_shared<Cell>(x, y, z)); } grid.push_back(line); } _cells.push_back(grid); } } shared_ptr<Cell> Level::getCell(uint x, uint y, uint z) { return _cells[z][y][x]; }
19.953846
66
0.587253
p-mccusker
edc32378ee40d9eebf809264b897fa85a7e1caef
2,758
hpp
C++
ThirdParty/assimp/BoostWorkaround/boost/timer.hpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
null
null
null
ThirdParty/assimp/BoostWorkaround/boost/timer.hpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
null
null
null
ThirdParty/assimp/BoostWorkaround/boost/timer.hpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
null
null
null
// boost timer.hpp header file ---------------------------------------------// // Copyright Beman Dawes 1994-99. 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) // See http://www.boost.org/libs/timer for documentation. // Revision History // 01 Apr 01 Modified to use new <boost/limits.hpp> header. (JMaddock) // 12 Jan 01 Change to inline implementation to allow use without library // builds. See docs for more rationale. (Beman Dawes) // 25 Sep 99 elapsed_max() and elapsed_min() added (John Maddock) // 16 Jul 99 Second beta // 6 Jul 99 Initial boost version #ifndef BOOST_TIMER_HPP #define BOOST_TIMER_HPP //#include <boost/config.hpp> #include <ctime> #include <limits> //#include <boost/limits.hpp> # ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::clock_t; using ::clock; } # endif namespace boost { // timer -------------------------------------------------------------------// // A timer object measures elapsed time. // It is recommended that implementations measure wall clock rather than CPU // time since the intended use is performance measurement on systems where // total elapsed time is more important than just process or CPU time. // Warnings: The maximum measurable elapsed time may well be only 596.5+ hours // due to implementation limitations. The accuracy of timings depends on the // accuracy of timing information provided by the underlying platform, and // this varies a great deal from platform to platform. class timer { public: timer() { _start_time = std::clock(); } // postcondition: elapsed()==0 // timer( const timer& src ); // post: elapsed()==src.elapsed() // ~timer(){} // timer& operator=( const timer& src ); // post: elapsed()==src.elapsed() void restart() { _start_time = std::clock(); } // post: elapsed()==0 double elapsed() const // return elapsed time in seconds { return double(std::clock() - _start_time) / CLOCKS_PER_SEC; } double elapsed_max() const // return estimated maximum value for elapsed() // Portability warning: elapsed_max() may return too high a value on systems // where std::clock_t overflows or resets at surprising values. { return (double((std::numeric_limits<std::clock_t>::max)()) - double(_start_time)) / double(CLOCKS_PER_SEC); } double elapsed_min() const // return minimum value for elapsed() { return double(1)/double(CLOCKS_PER_SEC); } private: std::clock_t _start_time; }; // timer } // namespace boost #endif // BOOST_TIMER_HPP
37.27027
81
0.643582
spetz911
edc53544fdbe13eef2b5a9f1d6faf7a5ddeab0b0
11,654
cpp
C++
Scheduler/CoinOR/examplesMakefiles/fast0507.cpp
enyquist/Concordia_Scheduling
5eb96ed585e7f2002983159b8ee0837b791753fa
[ "MIT" ]
null
null
null
Scheduler/CoinOR/examplesMakefiles/fast0507.cpp
enyquist/Concordia_Scheduling
5eb96ed585e7f2002983159b8ee0837b791753fa
[ "MIT" ]
null
null
null
Scheduler/CoinOR/examplesMakefiles/fast0507.cpp
enyquist/Concordia_Scheduling
5eb96ed585e7f2002983159b8ee0837b791753fa
[ "MIT" ]
null
null
null
// $Id: fast0507.cpp 1574 2011-01-05 01:13:55Z lou $ // Copyright (C) 2005, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #if defined(_MSC_VER) // Turn off compiler warning about long names # pragma warning(disable:4786) #endif #include <cassert> #include <iomanip> // For Branch and bound #include "OsiSolverInterface.hpp" #include "CbcModel.hpp" #include "CbcBranchActual.hpp" #include "CbcBranchUser.hpp" #include "CbcBranchCut.hpp" #include "CbcBranchToFixLots.hpp" #include "CbcCompareUser.hpp" #include "CbcCutGenerator.hpp" #include "CbcHeuristicGreedy.hpp" #include "OsiClpSolverInterface.hpp" #include "CbcSolver3.hpp" // Cuts #include "CglGomory.hpp" #include "CglProbing.hpp" #include "CglKnapsackCover.hpp" #include "CglOddHole.hpp" #include "CglClique.hpp" #include "CglFlowCover.hpp" #include "CglMixedIntegerRounding.hpp" #include "CglMixedIntegerRounding2.hpp" // Preprocessing #include "CglPreProcess.hpp" #include "CoinTime.hpp" //############################################################################# /************************************************************************ This main program reads in an integer model from an mps file. It then sets up some Cgl cut generators and calls branch and cut. Branching is simple binary branching on integer variables. Node selection is depth first until first solution is found and then based on objective and number of unsatisfied integer variables. In this example the functionality is the same as default but it is a user comparison function. Variable branching selection is on maximum minimum-of-up-down change after strong branching on 5 variables closest to 0.5. A simple rounding heuristic is used. ************************************************************************/ // ****** define comparison to choose best next node int main (int argc, const char *argv[]) { CbcSolver3 solver1; // Read in model using argv[1] // and assert that it is a clean model std::string mpsFileName; if (argc>=2) mpsFileName = argv[1]; int numMpsReadErrors = solver1.readMps(mpsFileName.c_str(),""); assert(numMpsReadErrors==0); double time1 = CoinCpuTime(); /* Options are: preprocess to do preprocessing time in minutes if 2 parameters and numeric taken as time */ bool preProcess=false; double minutes=-1.0; int nGoodParam=0; for (int iParam=2; iParam<argc;iParam++) { if (!strcmp(argv[iParam],"preprocess")) { preProcess=true; nGoodParam++; } else if (!strcmp(argv[iParam],"time")) { if (iParam+1<argc&&isdigit(argv[iParam+1][0])) { minutes=atof(argv[iParam+1]); if (minutes>=0.0) { nGoodParam+=2; iParam++; // skip time } } } } if (nGoodParam==0&&argc==3&&isdigit(argv[2][0])) { // If time is given then stop after that number of minutes minutes = atof(argv[2]); if (minutes>=0.0) nGoodParam=1; } if (nGoodParam!=argc-2) { printf("Usage <file> [preprocess] [time <minutes>] or <file> <minutes>\n"); exit(1); } solver1.initialSolve(); // Reduce printout solver1.setHintParam(OsiDoReducePrint,true,OsiHintTry); // Say we want scaling //solver1.setHintParam(OsiDoScale,true,OsiHintTry); //solver1.setCleanupScaling(1); // See if we want preprocessing OsiSolverInterface * solver2=&solver1; CglPreProcess process; if (preProcess) { /* Do not try and produce equality cliques and do up to 5 passes */ solver2 = process.preProcess(solver1,false,5); if (!solver2) { printf("Pre-processing says infeasible\n"); exit(2); } solver2->resolve(); } CbcModel model(*solver2); // Point to solver OsiSolverInterface * solver3 = model.solver(); CbcSolver3 * osiclp = dynamic_cast< CbcSolver3*> (solver3); assert (osiclp); const double fractionFix=0.985; osiclp->initialize(&model,NULL); osiclp->setAlgorithm(2); osiclp->setMemory(1000); osiclp->setNested(fractionFix); //osiclp->setNested(1.0); //off // Set up some cut generators and defaults // Probing first as gets tight bounds on continuous CglProbing generator1; generator1.setUsingObjective(true); generator1.setMaxPass(3); // Number of unsatisfied variables to look at generator1.setMaxProbe(10); // How far to follow the consequences generator1.setMaxLook(50); // Only look at rows with fewer than this number of elements generator1.setMaxElements(200); generator1.setRowCuts(3); CglGomory generator2; // try larger limit generator2.setLimit(300); CglKnapsackCover generator3; CglOddHole generator4; generator4.setMinimumViolation(0.005); generator4.setMinimumViolationPer(0.00002); // try larger limit generator4.setMaximumEntries(200); CglClique generator5; generator5.setStarCliqueReport(false); generator5.setRowCliqueReport(false); CglMixedIntegerRounding mixedGen; /* This is same as default constructor - (1,true,1) I presume if maxAggregate larger then slower but maybe better criterion can be 1 through 3 Reference: Hugues Marchand and Laurence A. Wolsey Aggregation and Mixed Integer Rounding to Solve MIPs Operations Research, 49(3), May-June 2001. */ int maxAggregate=1; bool multiply=true; int criterion=1; CglMixedIntegerRounding2 mixedGen2(maxAggregate,multiply,criterion); CglFlowCover flowGen; // Add in generators // Experiment with -1 and -99 etc model.addCutGenerator(&generator1,-99,"Probing"); //model.addCutGenerator(&generator2,-1,"Gomory"); //model.addCutGenerator(&generator3,-1,"Knapsack"); //model.addCutGenerator(&generator4,-1,"OddHole"); //model.addCutGenerator(&generator5,-1,"Clique"); //model.addCutGenerator(&flowGen,-1,"FlowCover"); //model.addCutGenerator(&mixedGen,-1,"MixedIntegerRounding"); //model.addCutGenerator(&mixedGen2,-1,"MixedIntegerRounding2"); // Say we want timings int numberGenerators = model.numberCutGenerators(); int iGenerator; for (iGenerator=0;iGenerator<numberGenerators;iGenerator++) { CbcCutGenerator * generator = model.cutGenerator(iGenerator); generator->setTiming(true); } // Allow rounding heuristic CbcRounding heuristic1(model); model.addHeuristic(&heuristic1); // And Greedy heuristic CbcHeuristicGreedyCover heuristic2(model); // Use original upper and perturb more heuristic2.setAlgorithm(11); model.addHeuristic(&heuristic2); // Redundant definition of default branching (as Default == User) CbcBranchUserDecision branch; model.setBranchingMethod(&branch); // Definition of node choice CbcCompareUser compare; model.setNodeComparison(compare); int iColumn; int numberColumns = solver3->getNumCols(); // do pseudo costs CbcObject ** objects = new CbcObject * [numberColumns+1]; const CoinPackedMatrix * matrix = solver3->getMatrixByCol(); // Column copy const int * columnLength = matrix->getVectorLengths(); const double * objective = model.getObjCoefficients(); int n=0; for (iColumn=0;iColumn<numberColumns;iColumn++) { if (solver3->isInteger(iColumn)) { double costPer = objective[iColumn]/ ((double) columnLength[iColumn]); CbcSimpleIntegerPseudoCost * newObject = new CbcSimpleIntegerPseudoCost(&model,n,iColumn, costPer,costPer); newObject->setMethod(3); objects[n++]= newObject; } } // and special fix lots branch objects[n++]=new CbcBranchToFixLots(&model,-1.0e-6,fractionFix+0.01,1,0,NULL); model.addObjects(n,objects); for (iColumn=0;iColumn<n;iColumn++) delete objects[iColumn]; delete [] objects; // High priority for odd object int followPriority=1; model.passInPriorities(&followPriority,true); // Do initial solve to continuous model.initialSolve(); // Could tune more model.setMinimumDrop(CoinMin(1.0, fabs(model.getMinimizationObjValue())*1.0e-3+1.0e-4)); if (model.getNumCols()<500) model.setMaximumCutPassesAtRoot(-100); // always do 100 if possible else if (model.getNumCols()<5000) model.setMaximumCutPassesAtRoot(100); // use minimum drop else model.setMaximumCutPassesAtRoot(20); //model.setMaximumCutPasses(1); // Do more strong branching if small //if (model.getNumCols()<5000) //model.setNumberStrong(10); // Switch off strong branching if wanted model.setNumberStrong(0); model.solver()->setIntParam(OsiMaxNumIterationHotStart,100); // If time is given then stop after that number of minutes if (minutes>=0.0) { std::cout<<"Stopping after "<<minutes<<" minutes"<<std::endl; model.setDblParam(CbcModel::CbcMaximumSeconds,60.0*minutes); } // Switch off most output if (model.getNumCols()<300000) { model.messageHandler()->setLogLevel(1); //model.solver()->messageHandler()->setLogLevel(0); } else { model.messageHandler()->setLogLevel(2); model.solver()->messageHandler()->setLogLevel(1); } //model.messageHandler()->setLogLevel(2); //model.solver()->messageHandler()->setLogLevel(2); //model.setPrintFrequency(50); #define DEBUG_CUTS #ifdef DEBUG_CUTS // Set up debugger by name (only if no preprocesing) if (!preProcess) { std::string problemName ; //model.solver()->getStrParam(OsiProbName,problemName) ; //model.solver()->activateRowCutDebugger(problemName.c_str()) ; model.solver()->activateRowCutDebugger("cap6000a") ; } #endif // Do complete search try { model.branchAndBound(); } catch (CoinError e) { e.print(); if (e.lineNumber()>=0) std::cout<<"This was from a CoinAssert"<<std::endl; exit(0); } //void printHowMany(); //printHowMany(); std::cout<<mpsFileName<<" took "<<CoinCpuTime()-time1<<" seconds, " <<model.getNodeCount()<<" nodes with objective " <<model.getObjValue() <<(!model.status() ? " Finished" : " Not finished") <<std::endl; // Print more statistics std::cout<<"Cuts at root node changed objective from "<<model.getContinuousObjective() <<" to "<<model.rootObjectiveAfterCuts()<<std::endl; for (iGenerator=0;iGenerator<numberGenerators;iGenerator++) { CbcCutGenerator * generator = model.cutGenerator(iGenerator); std::cout<<generator->cutGeneratorName()<<" was tried " <<generator->numberTimesEntered()<<" times and created " <<generator->numberCutsInTotal()<<" cuts of which " <<generator->numberCutsActive()<<" were active after adding rounds of cuts"; if (generator->timing()) std::cout<<" ( "<<generator->timeInCutGenerator()<<" seconds)"<<std::endl; else std::cout<<std::endl; } // Print solution if finished - we can't get names from Osi! if (model.getMinimizationObjValue()<1.0e50) { // post process if (preProcess) process.postProcess(*model.solver()); int numberColumns = model.solver()->getNumCols(); const double * solution = model.solver()->getColSolution(); int iColumn; std::cout<<std::setiosflags(std::ios::fixed|std::ios::showpoint)<<std::setw(14); std::cout<<"--------------------------------------"<<std::endl; for (iColumn=0;iColumn<numberColumns;iColumn++) { double value=solution[iColumn]; if (fabs(value)>1.0e-7&&model.solver()->isInteger(iColumn)) std::cout<<std::setw(6)<<iColumn<<" "<<value<<std::endl; } std::cout<<"--------------------------------------"<<std::endl; std::cout<<std::resetiosflags(std::ios::fixed|std::ios::showpoint|std::ios::scientific); } return 0; }
31.928767
92
0.678394
enyquist
edc664e4b802762cc6f3874259e4b256e1ed153f
9,953
cpp
C++
Chapter/10_ConsoleSystem/Core/ProcessManager.cpp
arkiny/OSwithMSVC
90cd62ce9bbe8301942e024404f32b04874e7906
[ "MIT" ]
1
2021-05-09T01:24:05.000Z
2021-05-09T01:24:05.000Z
Chapter/10_ConsoleSystem/Core/ProcessManager.cpp
arkiny/OSwithMSVC
90cd62ce9bbe8301942e024404f32b04874e7906
[ "MIT" ]
null
null
null
Chapter/10_ConsoleSystem/Core/ProcessManager.cpp
arkiny/OSwithMSVC
90cd62ce9bbe8301942e024404f32b04874e7906
[ "MIT" ]
null
null
null
#include "SkyOS.h" #include "KernelProcessLoader.h" #include "UserProcessLoader.h" ProcessManager* ProcessManager::m_processManager = nullptr; static int kernelStackIndex = 1; extern int g_stackPhysicalAddressPool; #define TASK_GENESIS_ID 1000 ProcessManager::ProcessManager() { m_nextThreadId = 1000; m_pCurrentTask = nullptr; m_pKernelProcessLoader = new KernelProcessLoader(); m_pUserProcessLoader = new UserProcessLoader(); m_taskList = new TaskList(); } ProcessManager::~ProcessManager() { } Thread* ProcessManager::CreateThread(Process* pProcess, FILE* file, LPVOID param) { unsigned char buf[512]; IMAGE_DOS_HEADER* dosHeader = 0; IMAGE_NT_HEADERS* ntHeaders = 0; unsigned char* memory = 0; //파일에서 512바이트를 읽고 유효한 PE 파일인지 검증한다. int readCnt = StorageManager::GetInstance()->ReadFile(file, buf, 1, 512); if (0 == readCnt) return nullptr; //유효하지 않은 PE파일이면 파일 핸들을 닫고 종료한다. if (!ValidatePEImage(buf)) { SkyConsole::Print("Invalid PE Format!! %s\n", pProcess->m_processName); StorageManager::GetInstance()->CloseFile(file); return nullptr; } dosHeader = (IMAGE_DOS_HEADER*)buf; ntHeaders = (IMAGE_NT_HEADERS*)(dosHeader->e_lfanew + (uint32_t)buf); pProcess->m_imageBase = ntHeaders->OptionalHeader.ImageBase; pProcess->m_imageSize = ntHeaders->OptionalHeader.SizeOfImage; Thread* pThread = new Thread(); pThread->m_pParent = pProcess; pThread->m_imageBase = ntHeaders->OptionalHeader.ImageBase; pThread->m_imageSize = ntHeaders->OptionalHeader.SizeOfImage; pThread->m_dwPriority = 1; pThread->m_taskState = TASK_STATE_INIT; pThread->m_initialStack = 0; pThread->m_stackLimit = PAGE_SIZE; pThread->SetThreadId(m_nextThreadId++); memset(&pThread->frame, 0, sizeof(trapFrame)); pThread->frame.eip = (uint32_t)ntHeaders->OptionalHeader.AddressOfEntryPoint + ntHeaders->OptionalHeader.ImageBase; pThread->frame.flags = 0x200; //#ifdef _DEBUG SkyConsole::Print("Process ImageBase : 0x%X\n", ntHeaders->OptionalHeader.ImageBase); //#endif //파일로부터 읽은 데이터 페이지 수 계산 int pageRest = 0; if ((pThread->m_imageSize % 4096) > 0) pageRest = 1; pProcess->m_dwPageCount = (pThread->m_imageSize / 4096) + pageRest; //파일을 메모리에 할당하는데 필요한 물리 메모리 할당 unsigned char* physicalMemory = (unsigned char*)PhysicalMemoryManager::AllocBlocks(pProcess->m_dwPageCount); //물리주소를 가상주소로 매핑한다 //주의 현재 실행중인 프로세스의 가상주소와 생성될 프로세스의 가상주소에 로드된 실행파일의 물리주소를 똑같이 매핑한 후 //복사가 완료되면 현재 실행중인 프로세스에 생성된 PTE를 삭제한다. for (DWORD i = 0; i < pProcess->m_dwPageCount; i++) { VirtualMemoryManager::MapPhysicalAddressToVirtualAddresss(GetCurrentTask()->m_pParent->GetPageDirectory(), ntHeaders->OptionalHeader.ImageBase + i * PAGE_SIZE, (uint32_t)physicalMemory + i * PAGE_SIZE, I86_PTE_PRESENT | I86_PTE_WRITABLE); } for (DWORD i = 0; i < pProcess->m_dwPageCount; i++) { VirtualMemoryManager::MapPhysicalAddressToVirtualAddresss(pProcess->GetPageDirectory(), ntHeaders->OptionalHeader.ImageBase + i * PAGE_SIZE, (uint32_t)physicalMemory + i * PAGE_SIZE, I86_PTE_PRESENT | I86_PTE_WRITABLE); } memory = (unsigned char*)ntHeaders->OptionalHeader.ImageBase; memset(memory, 0, pThread->m_imageSize); memcpy(memory, buf, 512); //파일을 메모리로 로드한다. int fileRest = 0; if ((pThread->m_imageSize % 512) != 0) fileRest = 1; int readCount = (pThread->m_imageSize / 512) + fileRest; for (int i = 1; i < readCount; i++) { if (file->_eof == 1) break; readCnt = StorageManager::GetInstance()->ReadFile(file, memory + 512 * i, 512, 1); } //스택을 생성하고 주소공간에 매핑한다. void* stackAddress = (void*)(g_stackPhysicalAddressPool - PAGE_SIZE * 10 * kernelStackIndex++); //스레드에 ESP, EBP 설정 pThread->m_initialStack = (void*)((uint32_t)stackAddress + PAGE_SIZE * 10); pThread->frame.esp = (uint32_t)pThread->m_initialStack; pThread->frame.ebp = pThread->frame.esp; pThread->frame.eax = 0; pThread->frame.ecx = 0; pThread->frame.edx = 0; pThread->frame.ebx = 0; pThread->frame.esi = 0; pThread->frame.edi = 0; //파일 로드에 사용된 페이지 테이블을 회수한다. for (DWORD i = 0; i < pProcess->m_dwPageCount; i++) { VirtualMemoryManager::UnmapPageTable(GetCurrentTask()->m_pParent->GetPageDirectory(), (uint32_t)physicalMemory + i * PAGE_SIZE); } m_taskList->push_back(pThread); return pThread; } Thread* ProcessManager::CreateThread(Process* pProcess, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID param) { //스레드 객체를 생성하고 변수를 초기화한다. Thread* pThread = new Thread(); pThread->m_pParent = pProcess; // 부모 프로세스 pThread->SetThreadId(m_nextThreadId++); //스레드 아이디 설정 pThread->m_dwPriority = 1; //우선순위 pThread->m_taskState = TASK_STATE_INIT; //태스크 상태 pThread->m_waitingTime = TASK_RUNNING_TIME; //실행시간 pThread->m_stackLimit = STACK_SIZE; //스택 크기 pThread->m_imageBase = 0; pThread->m_imageSize = 0; memset(&pThread->frame, 0, sizeof(trapFrame)); pThread->frame.eip = (uint32_t)lpStartAddress; //EIP pThread->frame.flags = 0x200; //플래그 pThread->m_startParam = param; //파라메터 //스택을 생성하고 주소공간에 매핑한다. void* stackAddress = (void*)(g_stackPhysicalAddressPool - PAGE_SIZE * 10 * kernelStackIndex++); #ifdef _DEBUG SkyConsole::Print("Stack : %x\n", stackAddress); #endif //ESP pThread->m_initialStack = (void*)((uint32_t)stackAddress + STACK_SIZE); pThread->frame.esp = (uint32_t)pThread->m_initialStack; //ESP pThread->frame.ebp = pThread->frame.esp; //EBP //태스크 리스트에 스레드를 추가한다. m_taskList->push_back(pThread); return pThread; } Process* ProcessManager::CreateProcessFromMemory(const char* appName, LPTHREAD_START_ROUTINE lpStartAddress, void* param, UINT32 processType) { Process* pProcess = nullptr; if (processType == PROCESS_KERNEL) pProcess = m_pKernelProcessLoader->CreateProcessFromMemory(appName, lpStartAddress, param); else pProcess = m_pUserProcessLoader->CreateProcessFromMemory(appName, lpStartAddress, param); if (pProcess == nullptr) return nullptr; if (param == nullptr) param = pProcess; Thread* pThread = CreateThread(pProcess, lpStartAddress, param); SKY_ASSERT(pThread != nullptr, "MainThread is null."); bool result = pProcess->AddMainThread(pThread); SKY_ASSERT(result == true, "AddMainThread Method Failed."); result = AddProcess(pProcess); SKY_ASSERT(result == true, "AddProcess Method Failed."); #ifdef _SKY_DEBUG SkyConsole::Print("Process Created. Process Id : %d\n", pProcess->GetProcessId()); #endif return pProcess; } Process* ProcessManager::CreateProcessFromFile(char* appName, void* param, UINT32 processType) { FILE* file; SkyConsole::Print("Open File : %s\n", appName); file = StorageManager::GetInstance()->OpenFile(appName, "r"); if (file == nullptr || file->_flags == FS_INVALID) return nullptr; if ((file->_flags & FS_DIRECTORY) == FS_DIRECTORY) return nullptr; Process* pProcess = nullptr; if (processType == PROCESS_KERNEL) pProcess = m_pKernelProcessLoader->CreateProcessFromFile(appName, param); else pProcess = m_pUserProcessLoader->CreateProcessFromFile(appName, param); if (pProcess == nullptr) { StorageManager::GetInstance()->CloseFile(file); return nullptr; } Thread* pThread = CreateThread(pProcess, file, NULL); if (pThread == nullptr) return nullptr; bool result = pProcess->AddMainThread(pThread); SKY_ASSERT(result == true, "AddMainThread Method Failed."); kEnterCriticalSection(); result = AddProcess(pProcess); kLeaveCriticalSection(); SKY_ASSERT(result == true, "AddProcess Method Failed."); #ifdef _SKY_DEBUG SkyConsole::Print("Process Created. Process Id : %d\n", pProcess->GetProcessId()); #endif StorageManager::GetInstance()->CloseFile(file); return pProcess; } Process* ProcessManager::FindProcess(int processId) { ProcessList::iterator iter = m_processList.find(processId); if (iter == m_processList.end()) return nullptr; return (*iter).second; } Thread* ProcessManager::FindTask(DWORD taskId) { auto iter = m_taskList->begin(); for (; iter != m_taskList->end(); iter++) { Thread* pThread = *iter; if (pThread->GetThreadId() == taskId) return pThread; } return nullptr; } bool ProcessManager::AddProcess(Process* pProcess) { if (pProcess == nullptr) return false; int entryPoint = 0; unsigned int procStack = 0; if (pProcess->GetProcessId() == PROC_INVALID_ID) return false; if (!pProcess->GetPageDirectory()) return false; Thread* pThread = pProcess->GetMainThread(); #ifdef _DEBUG // 메인스레드의 EIP, ESP를 얻는다 entryPoint = pThread->frame.eip; procStack = pThread->frame.esp; SkyConsole::Print("eip : %x\n", pThread->frame.eip); SkyConsole::Print("page directory : %x\n", pProcess->GetPageDirectory()); SkyConsole::Print("procStack : %x\n", procStack); #endif m_processList[pProcess->GetProcessId()] = pProcess; return true; } bool ProcessManager::RemoveProcess(int processId) { kEnterCriticalSection(); map<int, Process*>::iterator iter = m_processList.find(processId); Process* pProcess = (*iter).second; if (pProcess == nullptr) { kLeaveCriticalSection(); return false; } m_processList.erase(iter); map<int, Thread*>::iterator threadIter = pProcess->m_threadList.begin(); for (; threadIter != pProcess->m_threadList.end(); threadIter++) { Thread* pThread = (*threadIter).second; m_taskList->remove(pThread); delete pThread; } pProcess->m_threadList.clear(); if (pProcess->m_lpHeap) { SkyConsole::Print("default heap free : 0x%x\n", pProcess->m_lpHeap); delete pProcess->m_lpHeap; pProcess->m_lpHeap = nullptr; } VirtualMemoryManager::FreePageDirectory(pProcess->GetPageDirectory()); delete pProcess; kLeaveCriticalSection(); return true; } bool ProcessManager::RemoveTerminatedProcess() { auto iter = m_terminatedProcessList.begin(); for (; iter != m_terminatedProcessList.end(); iter++) { RemoveProcess((*iter).second->GetProcessId()); } m_terminatedProcessList.clear(); return true; } bool ProcessManager::ReserveRemoveProcess(Process* pProcess) { m_terminatedProcessList[pProcess->GetProcessId()] = pProcess; return true; }
26.12336
141
0.728424
arkiny
edcb8b59a0c2dbcdc798f74034925ee0722025fc
6,145
hpp
C++
optionals/faction_the_zone/CfgGroups.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
6
2018-05-05T22:28:57.000Z
2019-07-06T08:46:51.000Z
optionals/faction_the_zone/CfgGroups.hpp
Schwaggot/kellerkompanie-mods
7a389e49e3675866dbde1b317a44892926976e9d
[ "MIT" ]
107
2018-04-11T19:42:27.000Z
2019-09-13T19:05:31.000Z
optionals/faction_the_zone/CfgGroups.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
3
2018-10-03T11:54:46.000Z
2019-02-28T13:30:16.000Z
class CfgGroups { class east { class GVAR(opfor) { name = QUOTE(Kellerkompanie The Zone); class Bandits { name = QUOTE(Bandits); class GVAR(opfor_bandit_group_4) { name = QUOTE(4 Bandits); faction = QGVAR(opfor); side = 0; class Unit0 { vehicle = QGVAR(opfor_bandit1); rank = QUOTE(CORPORAL); position[] = {0,0,0}; side = 0; }; class Unit1 { vehicle = QGVAR(opfor_bandit2); rank = QUOTE(PRIVATE); position[] = {0,-3,0}; side = 0; }; class Unit2 { vehicle = QGVAR(opfor_bandit3); rank = QUOTE(PRIVATE); position[] = {0,-6,0}; side = 0; }; class Unit3 { vehicle = QGVAR(opfor_bandit4); rank = QUOTE(PRIVATE); position[] = {0,-9,0}; side = 0; }; }; class GVAR(opfor_bandit_group_4_alt) { name = QUOTE(4 Bandits (alt.)); faction = QGVAR(opfor); side = 0; class Unit0 { vehicle = QGVAR(opfor_bandit5); rank = QUOTE(CORPORAL); position[] = {0,0,0}; side = 0; }; class Unit1 { vehicle = QGVAR(opfor_bandit6); rank = QUOTE(PRIVATE); position[] = {0,-3,0}; side = 0; }; class Unit2 { vehicle = QGVAR(opfor_bandit7); rank = QUOTE(PRIVATE); position[] = {0,-6,0}; side = 0; }; class Unit3 { vehicle = QGVAR(opfor_bandit8); rank = QUOTE(PRIVATE); position[] = {0,-9,0}; side = 0; }; }; class GVAR(opfor_bandit_group_8) { name = QUOTE(8 Bandits); faction = QGVAR(opfor); side = 0; class Unit0 { vehicle = QGVAR(opfor_bandit1); rank = QUOTE(SERGEANT); position[] = {0,0,0}; side = 0; }; class Unit1 { vehicle = QGVAR(opfor_bandit2); rank = QUOTE(CORPORAL); position[] = {3,0,0}; side = 0; }; class Unit2 { vehicle = QGVAR(opfor_bandit3); rank = QUOTE(PRIVATE); position[] = {0,-3,0}; side = 0; }; class Unit3 { vehicle = QGVAR(opfor_bandit4); rank = QUOTE(PRIVATE); position[] = {0,-6,0}; side = 0; }; class Unit4 { vehicle = QGVAR(opfor_bandit5); rank = QUOTE(PRIVATE); position[] = {0,-9,0}; side = 0; }; class Unit5 { vehicle = QGVAR(opfor_bandit6); rank = QUOTE(PRIVATE); position[] = {0,-12,0}; side = 0; }; class Unit6 { vehicle = QGVAR(opfor_bandit7); rank = QUOTE(PRIVATE); position[] = {3,-3,0}; side = 0; }; class Unit7 { vehicle = QGVAR(opfor_bandit8); rank = QUOTE(PRIVATE); position[] = {3,-6,0}; side = 0; }; }; }; class Stalkers { name = QUOTE(Stalkers); class GVAR(opfor_stalker_group_5) { name = QUOTE(5 Stalkers); faction = QGVAR(opfor); side = 0; class Unit0 { vehicle = QGVAR(opfor_stalker1); rank = QUOTE(CORPORAL); position[] = {0,0,0}; side = 0; }; class Unit1 { vehicle = QGVAR(opfor_stalker2); rank = QUOTE(PRIVATE); position[] = {0,-3,0}; side = 0; }; class Unit2 { vehicle = QGVAR(opfor_stalker3); rank = QUOTE(PRIVATE); position[] = {0,-6,0}; side = 0; }; class Unit3 { vehicle = QGVAR(opfor_stalker4); rank = QUOTE(PRIVATE); position[] = {0,-9,0}; side = 0; }; class Unit4 { vehicle = QGVAR(opfor_stalker5); rank = QUOTE(PRIVATE); position[] = {0,-12,0}; side = 0; }; }; }; }; }; };
36.796407
56
0.296989
kellerkompanie
edce46f09fbb30e52d6a507700192cb4a8129fba
11,581
cpp
C++
guilib/src/OdometryViewer.cpp
redater/PAM-BATR
3fc8f95972ec13963a53c5448921b59df80a8c8b
[ "BSD-3-Clause" ]
1
2017-05-25T20:41:33.000Z
2017-05-25T20:41:33.000Z
guilib/src/OdometryViewer.cpp
redater/PAM-BATR
3fc8f95972ec13963a53c5448921b59df80a8c8b
[ "BSD-3-Clause" ]
null
null
null
guilib/src/OdometryViewer.cpp
redater/PAM-BATR
3fc8f95972ec13963a53c5448921b59df80a8c8b
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke 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 "rtabmap/gui/OdometryViewer.h" #include "rtabmap/core/util3d.h" #include "rtabmap/core/OdometryEvent.h" #include "rtabmap/utilite/ULogger.h" #include "rtabmap/utilite/UConversion.h" #include "rtabmap/gui/UCv2Qt.h" #include "rtabmap/gui/ImageView.h" #include "rtabmap/gui/CloudViewer.h" #include <QPushButton> #include <QSpinBox> #include <QDoubleSpinBox> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QApplication> namespace rtabmap { OdometryViewer::OdometryViewer(int maxClouds, int decimation, float voxelSize, int qualityWarningThr, QWidget * parent) : QDialog(parent), imageView_(new ImageView(this)), cloudView_(new CloudViewer(this)), processingData_(false), odomImageShow_(true), odomImageDepthShow_(true), lastOdomPose_(Transform::getIdentity()), qualityWarningThr_(qualityWarningThr), id_(0), validDecimationValue_(1) { qRegisterMetaType<rtabmap::SensorData>("rtabmap::SensorData"); qRegisterMetaType<rtabmap::OdometryInfo>("rtabmap::OdometryInfo"); imageView_->setImageDepthShown(false); imageView_->setMinimumSize(320, 240); cloudView_->setCameraFree(); cloudView_->setGridShown(true); QLabel * maxCloudsLabel = new QLabel("Max clouds", this); QLabel * voxelLabel = new QLabel("Voxel", this); QLabel * decimationLabel = new QLabel("Decimation", this); maxCloudsSpin_ = new QSpinBox(this); maxCloudsSpin_->setMinimum(0); maxCloudsSpin_->setMaximum(100); maxCloudsSpin_->setValue(maxClouds); voxelSpin_ = new QDoubleSpinBox(this); voxelSpin_->setMinimum(0); voxelSpin_->setMaximum(1); voxelSpin_->setDecimals(3); voxelSpin_->setSingleStep(0.01); voxelSpin_->setSuffix(" m"); voxelSpin_->setValue(voxelSize); decimationSpin_ = new QSpinBox(this); decimationSpin_->setMinimum(1); decimationSpin_->setMaximum(16); decimationSpin_->setValue(decimation); timeLabel_ = new QLabel(this); QPushButton * clearButton = new QPushButton("clear", this); QPushButton * closeButton = new QPushButton("close", this); connect(clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(closeButton, SIGNAL(clicked()), this, SLOT(reject())); //layout QHBoxLayout * layout = new QHBoxLayout(); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(imageView_,1); layout->addWidget(cloudView_,1); QHBoxLayout * hlayout2 = new QHBoxLayout(); hlayout2->setMargin(0); hlayout2->addWidget(maxCloudsLabel); hlayout2->addWidget(maxCloudsSpin_); hlayout2->addWidget(voxelLabel); hlayout2->addWidget(voxelSpin_); hlayout2->addWidget(decimationLabel); hlayout2->addWidget(decimationSpin_); hlayout2->addWidget(timeLabel_); hlayout2->addStretch(1); hlayout2->addWidget(clearButton); hlayout2->addWidget(closeButton); QVBoxLayout * vlayout = new QVBoxLayout(this); vlayout->setMargin(0); vlayout->setSpacing(0); vlayout->addLayout(layout, 1); vlayout->addLayout(hlayout2); this->setLayout(vlayout); } OdometryViewer::~OdometryViewer() { this->unregisterFromEventsManager(); this->clear(); UDEBUG(""); } void OdometryViewer::clear() { addedClouds_.clear(); cloudView_->clear(); } void OdometryViewer::processData(const rtabmap::SensorData & data, const rtabmap::OdometryInfo & info) { processingData_ = true; int quality = info.inliers; bool lost = false; bool lostStateChanged = false; if(data.pose().isNull()) { UDEBUG("odom lost"); // use last pose lostStateChanged = imageView_->getBackgroundColor() != Qt::darkRed; imageView_->setBackgroundColor(Qt::darkRed); cloudView_->setBackgroundColor(Qt::darkRed); lost = true; } else if(info.inliers>0 && qualityWarningThr_ && info.inliers < qualityWarningThr_) { UDEBUG("odom warn, quality(inliers)=%d thr=%d", info.inliers, qualityWarningThr_); lostStateChanged = imageView_->getBackgroundColor() == Qt::darkRed; imageView_->setBackgroundColor(Qt::darkYellow); cloudView_->setBackgroundColor(Qt::darkYellow); } else { UDEBUG("odom ok"); lostStateChanged = imageView_->getBackgroundColor() == Qt::darkRed; imageView_->setBackgroundColor(cloudView_->getDefaultBackgroundColor()); cloudView_->setBackgroundColor(Qt::black); } timeLabel_->setText(QString("%1 s").arg(info.time)); if(!data.image().empty() && !data.depthOrRightImage().empty() && data.fx()>0.0f && data.fyOrBaseline()>0.0f) { UDEBUG("New pose = %s, quality=%d", data.pose().prettyPrint().c_str(), quality); if(data.image().cols % decimationSpin_->value() == 0 && data.image().rows % decimationSpin_->value() == 0) { validDecimationValue_ = decimationSpin_->value(); } else { UWARN("Decimation (%d) must be a denominator of the width and height of " "the image (%d/%d). Using last valid decimation value (%d).", decimationSpin_->value(), data.image().cols, data.image().rows, validDecimationValue_); } // visualization: buffering the clouds // Create the new cloud pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud; if(!data.depth().empty()) { cloud = util3d::cloudFromDepthRGB( data.image(), data.depth(), data.cx(), data.cy(), data.fx(), data.fy(), validDecimationValue_); } else if(!data.rightImage().empty()) { cloud = util3d::cloudFromStereoImages( data.image(), data.rightImage(), data.cx(), data.cy(), data.fx(), data.baseline(), validDecimationValue_); } if(voxelSpin_->value() > 0.0f && cloud->size()) { cloud = util3d::voxelize<pcl::PointXYZRGB>(cloud, voxelSpin_->value()); } if(cloud->size()) { cloud = util3d::transformPointCloud<pcl::PointXYZRGB>(cloud, data.localTransform()); if(!data.pose().isNull()) { if(cloudView_->getAddedClouds().contains("cloudtmp")) { cloudView_->removeCloud("cloudtmp"); } while(maxCloudsSpin_->value()>0 && (int)addedClouds_.size() > maxCloudsSpin_->value()) { UASSERT(cloudView_->removeCloud(addedClouds_.first())); addedClouds_.pop_front(); } data.id()?id_=data.id():++id_; std::string cloudName = uFormat("cloud%d", id_); addedClouds_.push_back(cloudName); UASSERT(cloudView_->addCloud(cloudName, cloud, data.pose())); } else { cloudView_->addOrUpdateCloud("cloudtmp", cloud, lastOdomPose_); } } } if(!data.pose().isNull()) { lastOdomPose_ = data.pose(); cloudView_->updateCameraTargetPosition(data.pose()); } if(info.localMap.size()) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); cloud->resize(info.localMap.size()); int i=0; for(std::multimap<int, cv::Point3f>::const_iterator iter=info.localMap.begin(); iter!=info.localMap.end(); ++iter) { (*cloud)[i].x = iter->second.x; (*cloud)[i].y = iter->second.y; (*cloud)[i++].z = iter->second.z; } cloudView_->addOrUpdateCloud("localmap", cloud); } if(!data.image().empty()) { if(info.type == 0) { imageView_->setFeatures(info.words, Qt::yellow); } else if(info.type == 1) { std::vector<cv::KeyPoint> kpts; cv::KeyPoint::convert(info.refCorners, kpts); imageView_->setFeatures(kpts, Qt::red); } imageView_->clearLines(); if(lost) { if(lostStateChanged) { // save state odomImageShow_ = imageView_->isImageShown(); odomImageDepthShow_ = imageView_->isImageDepthShown(); } imageView_->setImageDepth(uCvMat2QImage(data.image())); imageView_->setImageShown(true); imageView_->setImageDepthShown(true); } else { if(lostStateChanged) { // restore state imageView_->setImageShown(odomImageShow_); imageView_->setImageDepthShown(odomImageDepthShow_); } imageView_->setImage(uCvMat2QImage(data.image())); if(imageView_->isImageDepthShown()) { imageView_->setImageDepth(uCvMat2QImage(data.depthOrRightImage())); } if(info.type == 0) { if(imageView_->isFeaturesShown()) { for(unsigned int i=0; i<info.wordMatches.size(); ++i) { imageView_->setFeatureColor(info.wordMatches[i], Qt::red); // outliers } for(unsigned int i=0; i<info.wordInliers.size(); ++i) { imageView_->setFeatureColor(info.wordInliers[i], Qt::green); // inliers } } } } if(info.type == 1 && info.cornerInliers.size()) { if(imageView_->isFeaturesShown() || imageView_->isLinesShown()) { //draw lines UASSERT(info.refCorners.size() == info.newCorners.size()); for(unsigned int i=0; i<info.cornerInliers.size(); ++i) { if(imageView_->isFeaturesShown()) { imageView_->setFeatureColor(info.cornerInliers[i], Qt::green); // inliers } if(imageView_->isLinesShown()) { imageView_->addLine( info.refCorners[info.cornerInliers[i]].x, info.refCorners[info.cornerInliers[i]].y, info.newCorners[info.cornerInliers[i]].x, info.newCorners[info.cornerInliers[i]].y, Qt::blue); } } } } if(!data.image().empty()) { imageView_->setSceneRect(QRectF(0,0,(float)data.image().cols, (float)data.image().rows)); } } imageView_->update(); cloudView_->update(); QApplication::processEvents(); processingData_ = false; } void OdometryViewer::handleEvent(UEvent * event) { if(!processingData_ && this->isVisible()) { if(event->getClassName().compare("OdometryEvent") == 0) { rtabmap::OdometryEvent * odomEvent = (rtabmap::OdometryEvent*)event; if(odomEvent->data().isValid()) { processingData_ = true; QMetaObject::invokeMethod(this, "processData", Q_ARG(rtabmap::SensorData, odomEvent->data()), Q_ARG(rtabmap::OdometryInfo, odomEvent->info())); } } } } } /* namespace rtabmap */
30.396325
122
0.677575
redater
edd08954bb398e4414cdc08003847733dace611f
3,008
cpp
C++
jerome_tool/Help.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
3
2018-06-11T10:48:54.000Z
2021-05-30T07:10:15.000Z
jerome_tool/Help.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
jerome_tool/Help.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
// // Help.cpp // jerome // // Created by Anton Leuski on 9/5/16. // Copyright © 2016 Anton Leuski & ICT/USC. All rights reserved. // // This file is part of Jerome. // // 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 <iostream> #include <iomanip> #include "Help.hpp" void Help::manual(std::ostream& out) const { out << description() << std::endl << "usage: " << Commander::shared().executable() << " " << name() << " <command>" << std::endl; Commander::shared().printCommandList(out); } static const char* oCommand = "help-command"; static const char* oCommandArgs = "help-command-args"; po::options_description Help::hiddenOptions() const { auto opts = Command::hiddenOptions(); opts.add_options() (oCommand, po::value<std::string>(), "command") (oCommandArgs, po::value<std::vector<std::string>>(), "arguments for command"); return opts; } po::positional_options_description Help::positionalOptions() const { return Command::positionalOptions() .add(oCommand, 1) .add(oCommandArgs, -1); } OptionalError Help::parseAndRun(const std::vector<std::string>& args) { po::options_description all_options; all_options .add(options()) .add(hiddenOptions()); // I must make it a variable because the parser will store a pointer // to this object auto positional_options = positionalOptions(); // note that I cannot break this instructions into seprate files for // customization because both command_line_parser and parsed_options // store pointers to options_description. An attempt to copy eithoer one // of them will lead to a crash. Blame boost program_option library design. po::parsed_options parsed = po::command_line_parser(args) .options(all_options) .positional(positional_options) .allow_unregistered() // because of this line I have reimplement the function .run(); storeParsedResults(parsed); return run(); } OptionalError Help::run() { if (variables()[oCommand].empty()) { Commander::shared().usage(std::cout); return Error::NO_ERROR; } std::string commandName = variables()[oCommand].as<std::string>(); if (!Commander::shared().hasCommandWithName(commandName)) { return Error("unknown command \"" + commandName + "\""); } Commander::shared().command(commandName).printManual(std::cout); return Error::NO_ERROR; } std::string Help::description() const { return "description of the commands"; } std::string Help::name() const { return "help"; }
28.11215
82
0.701463
leuski-ict
edd6a9fe5f4b3bbec07a5d5a0d5a0fb2d5e995d3
2,041
hpp
C++
contrib/autoboost/autoboost/mpl/advance.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
contrib/autoboost/autoboost/mpl/advance.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
contrib/autoboost/autoboost/mpl/advance.hpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
#ifndef AUTOBOOST_MPL_ADVANCE_HPP_INCLUDED #define AUTOBOOST_MPL_ADVANCE_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <autoboost/mpl/advance_fwd.hpp> #include <autoboost/mpl/less.hpp> #include <autoboost/mpl/negate.hpp> #include <autoboost/mpl/long.hpp> #include <autoboost/mpl/if.hpp> #include <autoboost/mpl/tag.hpp> #include <autoboost/mpl/apply_wrap.hpp> #include <autoboost/mpl/aux_/advance_forward.hpp> #include <autoboost/mpl/aux_/advance_backward.hpp> #include <autoboost/mpl/aux_/value_wknd.hpp> #include <autoboost/mpl/aux_/na_spec.hpp> #include <autoboost/mpl/aux_/nttp_decl.hpp> namespace autoboost { namespace mpl { // default implementation for forward/bidirectional iterators template< typename Tag > struct advance_impl { template< typename Iterator, typename N > struct apply { typedef typename less< N,long_<0> >::type backward_; typedef typename if_< backward_, negate<N>, N >::type offset_; typedef typename if_< backward_ , aux::advance_backward< AUTOBOOST_MPL_AUX_VALUE_WKND(offset_)::value > , aux::advance_forward< AUTOBOOST_MPL_AUX_VALUE_WKND(offset_)::value > >::type f_; typedef typename apply_wrap1<f_,Iterator>::type type; }; }; template< typename AUTOBOOST_MPL_AUX_NA_PARAM(Iterator) , typename AUTOBOOST_MPL_AUX_NA_PARAM(N) > struct advance : advance_impl< typename tag<Iterator>::type > ::template apply<Iterator,N> { }; template< typename Iterator , AUTOBOOST_MPL_AUX_NTTP_DECL(long, N) > struct advance_c : advance_impl< typename tag<Iterator>::type > ::template apply<Iterator,long_<N> > { }; AUTOBOOST_MPL_AUX_NA_SPEC(2, advance) }} #endif // AUTOBOOST_MPL_ADVANCE_HPP_INCLUDED
26.506494
83
0.719745
CaseyCarter
eddd9e4d8879a08cc69c08a3421507f23e261240
7,316
cc
C++
test/gtest/uct/ib/test_rc.cc
Bayyapu/ucx
b339b76ad67d2cc69e14598bac59b00b2d05d9ee
[ "BSD-3-Clause" ]
null
null
null
test/gtest/uct/ib/test_rc.cc
Bayyapu/ucx
b339b76ad67d2cc69e14598bac59b00b2d05d9ee
[ "BSD-3-Clause" ]
null
null
null
test/gtest/uct/ib/test_rc.cc
Bayyapu/ucx
b339b76ad67d2cc69e14598bac59b00b2d05d9ee
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2016. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2016. ALL RIGHTS RESERVED. * Copyright (C) ARM Ltd. 2016.All rights reserved. * See file LICENSE for terms. */ #include "test_rc.h" #define UCT_RC_INSTANTIATE_TEST_CASE(_test_case) \ _UCT_INSTANTIATE_TEST_CASE(_test_case, rc) \ _UCT_INSTANTIATE_TEST_CASE(_test_case, rc_mlx5) void test_rc::init() { uct_test::init(); m_e1 = uct_test::create_entity(0); m_entities.push_back(m_e1); m_e2 = uct_test::create_entity(0); m_entities.push_back(m_e2); connect(); } void test_rc::connect() { m_e1->connect(0, *m_e2, 0); m_e2->connect(0, *m_e1, 0); uct_iface_set_am_handler(m_e1->iface(), 0, am_dummy_handler, NULL, UCT_CB_FLAG_SYNC); uct_iface_set_am_handler(m_e2->iface(), 0, am_dummy_handler, NULL, UCT_CB_FLAG_SYNC); } class test_rc_max_wr : public test_rc { protected: virtual void init() { ucs_status_t status1, status2; status1 = uct_config_modify(m_iface_config, "TX_MAX_WR", "32"); status2 = uct_config_modify(m_iface_config, "TX_MAX_BB", "32"); if (status1 != UCS_OK && status2 != UCS_OK) { UCS_TEST_ABORT("Error: cannot set rc max wr/bb"); } test_rc::init(); } }; /* Check that max_wr stops from sending */ UCS_TEST_P(test_rc_max_wr, send_limit) { /* first 32 messages should be OK */ send_am_messages(m_e1, 32, UCS_OK); /* next message - should fail */ send_am_messages(m_e1, 1, UCS_ERR_NO_RESOURCE); progress_loop(); send_am_messages(m_e1, 1, UCS_OK); } UCT_RC_INSTANTIATE_TEST_CASE(test_rc_max_wr) int test_rc_flow_control::req_count = 0; ucs_status_t test_rc_flow_control::am_send(uct_pending_req_t *self) { pending_send_request_t *req = ucs_container_of(self, pending_send_request_t, uct); ucs_status_t status = uct_ep_am_short(req->ep, 0, 0, NULL,0); ucs_debug("sending short with grant %d ",status); return status; } void test_rc_flow_control::validate_grant(entity *e) { ucs_time_t timeout = ucs_get_time() + ucs_time_from_sec(UCT_TEST_TIMEOUT_IN_SEC); while ((ucs_get_time() < timeout) && (!get_fc_ptr(e)->fc_wnd)) { short_progress_loop(); } EXPECT_GT(get_fc_ptr(e)->fc_wnd, 0); } /* Check that FC window works as expected: * - If FC enabled, only 'wnd' messages can be sent in a row * - If FC is disabled 'wnd' does not limit senders flow */ void test_rc_flow_control::test_general(int wnd, int soft_thresh, int hard_thresh, bool is_fc_enabled) { set_fc_attributes(m_e1, is_fc_enabled, wnd, soft_thresh, hard_thresh); send_am_messages(m_e1, wnd, UCS_OK); send_am_messages(m_e1, 1, is_fc_enabled ? UCS_ERR_NO_RESOURCE : UCS_OK); validate_grant(m_e1); send_am_messages(m_e1, 1, UCS_OK); if (!is_fc_enabled) { /* Make valgrind happy, need to enable FC for proper cleanup */ set_fc_attributes(m_e1, true, wnd, wnd, 1); } flush(); } void test_rc_flow_control::test_pending_grant(int wnd) { /* Block send capabilities of m_e2 for fc grant to be * added to the pending queue. */ disable_entity(m_e2); set_fc_attributes(m_e1, true, wnd, wnd, 1); send_am_messages(m_e1, wnd, UCS_OK); progress_loop(); /* Now m_e1 should be blocked by FC window and FC grant * should be in pending queue of m_e2. */ send_am_messages(m_e1, 1, UCS_ERR_NO_RESOURCE); EXPECT_LE(get_fc_ptr(m_e1)->fc_wnd, 0); /* Enable send capabilities of m_e2 and send AM message * to force pending queue dispatch */ enable_entity(m_e2); set_tx_moderation(m_e2, 0); send_am_messages(m_e2, 1, UCS_OK); /* Check that m_e1 got grant */ validate_grant(m_e1); send_am_messages(m_e1, 1, UCS_OK); } void test_rc_flow_control::test_pending_purge(int wnd, int num_pend_sends) { uct_pending_req_t reqs[num_pend_sends]; disable_entity(m_e2); set_fc_attributes(m_e1, true, wnd, wnd, 1); req_count = 0; send_am_messages(m_e1, wnd, UCS_OK); progress_loop(); /* Now m2 ep should have FC grant message in the pending queue. * Add some user pending requests as well */ for (int i = 0; i < num_pend_sends; i ++) { reqs[i].func = NULL; /* make valgrind happy */ EXPECT_EQ(uct_ep_pending_add(m_e2->ep(0), &reqs[i]), UCS_OK); } uct_ep_pending_purge(m_e2->ep(0), purge_cb, NULL); EXPECT_EQ(num_pend_sends, req_count); } /* Check that FC window works as expected */ UCS_TEST_P(test_rc_flow_control, general_enabled) { test_general(8, 4, 2, true); } UCS_TEST_P(test_rc_flow_control, general_disabled) { test_general(8, 4, 2, false); } /* Test the scenario when ep is being destroyed while there is * FC grant message in the pending queue */ UCS_TEST_P(test_rc_flow_control, pending_only_fc) { int wnd = 2; disable_entity(m_e2); set_fc_attributes(m_e1, true, wnd, wnd, 1); send_am_messages(m_e1, wnd, UCS_OK); progress_loop(); m_e2->destroy_ep(0); ASSERT_TRUE(rc_iface(m_e2)->tx.arbiter.current == NULL); } /* Check that user callback passed to uct_ep_pending_purge is not * invoked for FC grant message */ UCS_TEST_P(test_rc_flow_control, pending_purge) { test_pending_purge(2, 5); } UCS_TEST_P(test_rc_flow_control, pending_grant) { test_pending_grant(5); } UCT_RC_INSTANTIATE_TEST_CASE(test_rc_flow_control) #if ENABLE_STATS void test_rc_flow_control_stats::test_general(int wnd, int soft_thresh, int hard_thresh) { uint64_t v; set_fc_attributes(m_e1, true, wnd, soft_thresh, hard_thresh); send_am_messages(m_e1, wnd, UCS_OK); send_am_messages(m_e1, 1, UCS_ERR_NO_RESOURCE); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e1)->stats, UCT_RC_FC_STAT_NO_CRED); EXPECT_EQ(1ul, v); progress_loop(); validate_grant(m_e1); send_am_messages(m_e1, 1, UCS_OK); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e1)->stats, UCT_RC_FC_STAT_TX_HARD_REQ); EXPECT_EQ(1ul, v); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e1)->stats, UCT_RC_FC_STAT_RX_PURE_GRANT); EXPECT_EQ(1ul, v); flush(); } UCS_TEST_P(test_rc_flow_control_stats, general) { test_general(5, 2, 1); } UCS_TEST_P(test_rc_flow_control_stats, soft_request) { uint64_t v; int wnd = 8; int s_thresh = 4; int h_thresh = 1; set_fc_attributes(m_e1, true, wnd, s_thresh, h_thresh); send_am_messages(m_e1, wnd - (s_thresh - 1), UCS_OK); progress_loop(); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e1)->stats, UCT_RC_FC_STAT_TX_SOFT_REQ); EXPECT_EQ(1ul, v); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e2)->stats, UCT_RC_FC_STAT_RX_SOFT_REQ); EXPECT_EQ(1ul, v); send_am_messages(m_e2, 1, UCS_OK); progress_loop(); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e1)->stats, UCT_RC_FC_STAT_RX_GRANT); EXPECT_EQ(1ul, v); v = UCS_STATS_GET_COUNTER(get_fc_ptr(m_e2)->stats, UCT_RC_FC_STAT_TX_GRANT); EXPECT_EQ(1ul, v); } UCT_RC_INSTANTIATE_TEST_CASE(test_rc_flow_control_stats) #endif
27.503759
85
0.677556
Bayyapu
ede2bc114b93da6fa90a72e5829bce0ce5272997
5,733
cpp
C++
src/bind/lens_File.cpp
lubyk/lens
05541de73c2df31680c6273a796a624323ac2c04
[ "MIT" ]
1
2016-01-21T22:07:58.000Z
2016-01-21T22:07:58.000Z
src/bind/lens_File.cpp
lubyk/lens
05541de73c2df31680c6273a796a624323ac2c04
[ "MIT" ]
1
2015-11-21T13:56:01.000Z
2015-11-30T20:03:50.000Z
src/bind/lens_File.cpp
lubyk/lens
05541de73c2df31680c6273a796a624323ac2c04
[ "MIT" ]
null
null
null
/** * * MACHINE GENERATED FILE. DO NOT EDIT. * * Bindings for class File * * This file has been generated by dub 2.2.1. */ #include "dub/dub.h" #include "lens/File.h" using namespace lens; /** lens::File::File(const char *path, Mode mode) * include/lens/File.h:98 */ static int File_File(lua_State *L) { try { const char *path = dub::checkstring(L, 1); lens::File::Mode mode = (lens::File::Mode)dub::checkint(L, 2); File *retval__ = new File(path, mode); dub::pushudata(L, retval__, "lens.File", true); return 1; } catch (std::exception &e) { lua_pushfstring(L, "new: %s", e.what()); } catch (...) { lua_pushfstring(L, "new: Unknown exception"); } return dub::error(L); } /** virtual lens::File::~File() * include/lens/File.h:112 */ static int File__File(lua_State *L) { try { DubUserdata *userdata = ((DubUserdata*)dub::checksdata_d(L, 1, "lens.File")); if (userdata->gc) { File *self = (File *)userdata->ptr; delete self; } userdata->gc = false; return 0; } catch (std::exception &e) { lua_pushfstring(L, "__gc: %s", e.what()); } catch (...) { lua_pushfstring(L, "__gc: Unknown exception"); } return dub::error(L); } /** int lens::File::fd() * include/lens/File.h:116 */ static int File_fd(lua_State *L) { try { File *self = *((File **)dub::checksdata(L, 1, "lens.File")); lua_pushnumber(L, self->fd()); return 1; } catch (std::exception &e) { lua_pushfstring(L, "fd: %s", e.what()); } catch (...) { lua_pushfstring(L, "fd: Unknown exception"); } return dub::error(L); } /** void lens::File::close() * include/lens/File.h:120 */ static int File_close(lua_State *L) { try { File *self = *((File **)dub::checksdata(L, 1, "lens.File")); self->close(); return 0; } catch (std::exception &e) { lua_pushfstring(L, "close: %s", e.what()); } catch (...) { lua_pushfstring(L, "close: Unknown exception"); } return dub::error(L); } /** LuaStackSize lens::File::read(size_t sz, lua_State *L) * include/lens/File.h:129 */ static int File_read(lua_State *L) { try { File *self = *((File **)dub::checksdata(L, 1, "lens.File")); size_t sz = dub::checkint(L, 2); return self->read(sz, L); } catch (std::exception &e) { lua_pushfstring(L, "read: %s", e.what()); } catch (...) { lua_pushfstring(L, "read: Unknown exception"); } return dub::error(L); } /** LuaStackSize lens::File::readLine(lua_State *L) * include/lens/File.h:132 */ static int File_readLine(lua_State *L) { try { File *self = *((File **)dub::checksdata(L, 1, "lens.File")); return self->readLine(L); } catch (std::exception &e) { lua_pushfstring(L, "readLine: %s", e.what()); } catch (...) { lua_pushfstring(L, "readLine: Unknown exception"); } return dub::error(L); } /** LuaStackSize lens::File::readAll(lua_State *L) * include/lens/File.h:135 */ static int File_readAll(lua_State *L) { try { File *self = *((File **)dub::checksdata(L, 1, "lens.File")); return self->readAll(L); } catch (std::exception &e) { lua_pushfstring(L, "readAll: %s", e.what()); } catch (...) { lua_pushfstring(L, "readAll: Unknown exception"); } return dub::error(L); } /** LuaStackSize lens::File::write(lua_State *L) * include/lens/File.h:138 */ static int File_write(lua_State *L) { try { File *self = *((File **)dub::checksdata(L, 1, "lens.File")); return self->write(L); } catch (std::exception &e) { lua_pushfstring(L, "write: %s", e.what()); } catch (...) { lua_pushfstring(L, "write: Unknown exception"); } return dub::error(L); } // --=============================================== __tostring static int File___tostring(lua_State *L) { File *self = *((File **)dub::checksdata_n(L, 1, "lens.File")); lua_pushfstring(L, "lens.File: %p (%i)", self, self-> fd()); return 1; } // --=============================================== METHODS static const struct luaL_Reg File_member_methods[] = { { "new" , File_File }, { "__gc" , File__File }, { "fd" , File_fd }, { "close" , File_close }, { "read" , File_read }, { "readLine" , File_readLine }, { "readAll" , File_readAll }, { "write" , File_write }, { "__tostring" , File___tostring }, { "deleted" , dub::isDeleted }, { NULL, NULL}, }; // --=============================================== CONSTANTS static const struct dub::const_Reg File_const[] = { { "None" , File::None }, { "Read" , File::Read }, { "Write" , File::Write }, { "Append" , File::Append }, { "Events" , File::Events }, { "DeleteEvent" , File::DeleteEvent }, { "WriteEvent" , File::WriteEvent }, { "ExtendEvent" , File::ExtendEvent }, { "AttribEvent" , File::AttribEvent }, { "LinkEvent" , File::LinkEvent }, { "RenameEvent" , File::RenameEvent }, { "RevokeEvent" , File::RevokeEvent }, { "NoneEvent" , File::NoneEvent }, { "OK" , File::OK }, { "Wait" , File::Wait }, { "End" , File::End }, { NULL, 0}, }; extern "C" int luaopen_lens_File(lua_State *L) { // Create the metatable which will contain all the member methods luaL_newmetatable(L, "lens.File"); // <mt> // register class constants dub::register_const(L, File_const); // register member methods dub::fregister(L, File_member_methods); // setup meta-table dub::setup(L, "lens.File"); // <mt> return 1; }
27.695652
81
0.54823
lubyk
ede87b17544ec85f5498388092a544c3907e5c84
1,673
cpp
C++
99_sketch/win.cpp
kumaashi/VulkanSandbox
bb7c4e633dcd14d4ff4d2f279da48a2a78e1df5e
[ "Unlicense" ]
null
null
null
99_sketch/win.cpp
kumaashi/VulkanSandbox
bb7c4e633dcd14d4ff4d2f279da48a2a78e1df5e
[ "Unlicense" ]
null
null
null
99_sketch/win.cpp
kumaashi/VulkanSandbox
bb7c4e633dcd14d4ff4d2f279da48a2a78e1df5e
[ "Unlicense" ]
null
null
null
#include "win.h" static LRESULT WINAPI WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int temp = wParam & 0xFFF0; switch (msg) { case WM_SYSCOMMAND: if (temp == SC_MONITORPOWER || temp == SC_SCREENSAVE) { return 0; } break; case WM_IME_SETCONTEXT: lParam &= ~ISC_SHOWUIALL; return 0; break; case WM_CLOSE: case WM_DESTROY: PostQuitMessage(0); return 0; break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) PostQuitMessage(0); break; case WM_SIZE: break; } return DefWindowProc(hWnd, msg, wParam, lParam); } HWND win_init(const char *appname, int Width, int Height) { static WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_CLASSDC | CS_VREDRAW | CS_HREDRAW, WindowProc, 0L, 0L, GetModuleHandle(NULL), LoadIcon(NULL, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), (HBRUSH)GetStockObject(BLACK_BRUSH), NULL, appname, NULL }; wcex.hInstance = GetModuleHandle(NULL); RegisterClassEx(&wcex); DWORD styleex = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; DWORD style = WS_OVERLAPPEDWINDOW; style &= ~(WS_SIZEBOX | WS_MAXIMIZEBOX | WS_MINIMIZEBOX); RECT rc; SetRect( &rc, 0, 0, Width, Height ); AdjustWindowRectEx( &rc, style, FALSE, styleex); rc.right -= rc.left; rc.bottom -= rc.top; HWND hWnd = CreateWindowEx(styleex, appname, appname, style, 0, 0, rc.right, rc.bottom, NULL, NULL, wcex.hInstance, NULL); ShowWindow(hWnd, SW_SHOW); UpdateWindow(hWnd); ShowCursor(TRUE); return hWnd; } BOOL win_proc_msg() { MSG msg; BOOL IsActive = TRUE; while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) IsActive = FALSE; TranslateMessage(&msg); DispatchMessage(&msg); } return IsActive; }
25.738462
124
0.708906
kumaashi
ede8d50579f6b9c9eddc199a4549552ea5b74aad
1,369
cpp
C++
lcs.cpp
Sdccoding/Data-Structure_Algorithms_Coding
169ac55ae0a916e49276658c7fbe362ef78b5484
[ "MIT" ]
null
null
null
lcs.cpp
Sdccoding/Data-Structure_Algorithms_Coding
169ac55ae0a916e49276658c7fbe362ef78b5484
[ "MIT" ]
null
null
null
lcs.cpp
Sdccoding/Data-Structure_Algorithms_Coding
169ac55ae0a916e49276658c7fbe362ef78b5484
[ "MIT" ]
null
null
null
//Find LCS in terms of LIS,when 1 array has unique elemnts //Find LIS in O(nlogn) #include<bits/stdc++.h> using namespace std; #define pb push_back #define mk make_pair #define fi first #define se second #define ll long long int #define ld long double #define MOD 1000000007 #define endl "\n" #define pi pair<int,int> #define JALDI ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); void so(vector<ll> &v) { sort(v.begin(),v.end()); } int main() { JALDI; ll n,m; cin>>n>>m; vector<ll>s(n),t(m); for(ll i=0;i<n;i++) cin>>s[i]; unordered_map<int,int>mp; for(ll i=0;i<m;i++) { cin>>t[i]; mp[t[i]]=i; } for(ll i=0;i<n;i++) { if(mp.find(s[i])!=mp.end()) { s[i]=mp[s[i]]; } else s[i]=-1; } vector<ll>tail; for(ll i=0;i<n;i++) { if(s[i]==-1) continue; else if(tail.size()==0) { tail.pb(s[i]); } else if(s[i]>=tail.back()) { tail.pb(s[i]); } else if(s[i]<tail[0]) { tail[0]=s[i]; } else { auto it=lower_bound(tail.begin(),tail.end(),s[i]); *it=s[i]; } } cout<<tail.size()<<endl; return 0; }
14.410526
72
0.450694
Sdccoding
ede9d6ee7995c5a5f58e99cd3f15d93f22197ca1
17,422
cpp
C++
pwiz_tools/commandline/idconvert.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
2
2019-12-28T21:24:36.000Z
2020-04-18T03:52:05.000Z
pwiz_tools/commandline/idconvert.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
pwiz_tools/commandline/idconvert.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
// // $Id: idconvert.cpp 6865 2014-10-31 21:47:12Z chambm $ // // // Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu> // // Copyright 2011 Vanderbilt University - Nashville, TN 37232 // // 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 "pwiz/utility/misc/Std.hpp" #include "pwiz/utility/misc/Filesystem.hpp" #include "pwiz/data/identdata/DefaultReaderList.hpp" #include "pwiz/data/identdata/IdentDataFile.hpp" //#include "pwiz/data/identdata/IO.hpp" #include "pwiz/data/identdata/Version.hpp" #include "pwiz/Version.hpp" #include "boost/program_options.hpp" using namespace pwiz::cv; using namespace pwiz::data; using namespace pwiz::identdata; using namespace pwiz::util; struct Config { vector<string> filenames; //vector<string> filters; string outputPath; string extension; bool verbose; IdentDataFile::WriteConfig writeConfig; //string contactFilename; //bool merge; Config() : outputPath("."), verbose(false)//, merge(false) {} string outputFilename(const string& inputFilename, const IdentData& inputIdentData, bool multipleOutputs) const; }; string Config::outputFilename(const string& filename, const IdentData& idd, bool multipleOutputs) const { if (idd.dataCollection.inputs.spectraData.empty()) throw runtime_error("[Config::outputFilename] no spectraData elements"); string sourceName; if (multipleOutputs) sourceName = idd.id; if (sourceName.empty()) sourceName = bfs::basename(idd.dataCollection.inputs.spectraData[0]->name); if (sourceName.empty()) sourceName = bfs::basename(filename); // this list is for Windows; it's a superset of the POSIX list string illegalFilename = "\\/*:?<>|\""; BOOST_FOREACH(char& c, sourceName) if (illegalFilename.find(c) != string::npos) c = '_'; bfs::path fullPath = bfs::path(outputPath) / (sourceName + extension); return fullPath.string(); } ostream& operator<<(ostream& os, const Config& config) { os << "format: " << config.writeConfig << endl; os << "outputPath: " << config.outputPath << endl; os << "extension: " << config.extension << endl; //os << "contactFilename: " << config.contactFilename << endl; os << endl; /*os << "filters:\n "; copy(config.filters.begin(), config.filters.end(), ostream_iterator<string>(os,"\n ")); os << endl;*/ os << "filenames:\n "; copy(config.filenames.begin(), config.filenames.end(), ostream_iterator<string>(os,"\n ")); os << endl; return os; } Config parseCommandLine(int argc, const char* argv[]) { namespace po = boost::program_options; ostringstream usage; usage << "Usage: idconvert [options] [filemasks]\n" << "Convert mass spec identification file formats.\n" << "\n" << "Return value: # of failed files.\n" << "\n"; Config config; string filelistFilename; string configFilename; bool format_text = false; bool format_mzIdentML = false; bool format_pepXML = false; //bool gzip = false; po::options_description od_config("Options"); od_config.add_options() ("filelist,f", po::value<string>(&filelistFilename), ": specify text file containing filenames") ("outdir,o", po::value<string>(&config.outputPath)->default_value(config.outputPath), ": set output directory ('-' for stdout) [.]") ("config,c", po::value<string>(&configFilename), ": configuration file (optionName=value)") ("ext,e", po::value<string>(&config.extension)->default_value(config.extension), ": set extension for output files [mzid|pepXML|txt]") ("mzIdentML", po::value<bool>(&format_mzIdentML)->zero_tokens(), ": write mzIdentML format [default]") ("pepXML", po::value<bool>(&format_pepXML)->zero_tokens(), ": write pepXML format") ("text", po::value<bool>(&format_text)->zero_tokens(), ": write hierarchical text format") ("verbose,v", po::value<bool>(&config.verbose)->zero_tokens(), ": display detailed progress information") /*("contactInfo,i", po::value<string>(&config.contactFilename), ": filename for contact info") ("gzip,g", po::value<bool>(&gzip)->zero_tokens(), ": gzip entire output file (adds .gz to filename)") ("filter", po::value< vector<string> >(&config.filters), ": add a spectrum list filter") ("merge", po::value<bool>(&config.merge)->zero_tokens(), ": create a single output file from multiple input files by merging file-level metadata and concatenating spectrum lists")*/ ; // append options description to usage string usage << od_config; // extra usage usage << "Examples:\n" << endl << "# convert sequest.pepXML to sequest.mzid\n" << "idconvert sequest.pepXML\n" << endl << "# convert sequest.protXML to sequest.mzid\n" << "# Also reads any pepXML file referenced in the \n" << "# protXML file if available. If the protXML \n" << "# file has been moved from its original location, \n" << "# the pepXML will still be found if it has also \n" << "# been moved to the same position relative to the \n" << "# protXML file. This relative position is determined \n" << "# by reading the protXML protein_summary:summary_xml \n" << "# and protein_summary_header:source_files values.\n" << "idconvert sequest.protXML\n" << endl << "# convert mascot.mzid to mascot.pepXML\n" << "idconvert mascot.mzid --pepXML\n" << endl << "# put output file in my_output_dir\n" << "idconvert omssa.pepXML -o my_output_dir\n" << endl << "# use a configuration file\n" << "idconvert xtandem.pep.xml -c config.txt\n" << endl << "# example configuration file\n" << "pepXML=true\n" //<< "gzip=true\n" << endl << endl << "Questions, comments, and bug reports:\n" << "http://proteowizard.sourceforge.net\n" << "support@proteowizard.org\n" << "\n" << "ProteoWizard release: " << pwiz::Version::str() << " (" << pwiz::Version::LastModified() << ")" << endl << "ProteoWizard IdentData: " << pwiz::identdata::Version::str() << " (" << pwiz::identdata::Version::LastModified() << ")" << endl << "Build date: " << __DATE__ << " " << __TIME__ << endl; if (argc <= 1) throw usage_exception(usage.str()); // handle positional arguments const char* label_args = "args"; po::options_description od_args; od_args.add_options()(label_args, po::value< vector<string> >(), ""); po::positional_options_description pod_args; pod_args.add(label_args, -1); po::options_description od_parse; od_parse.add(od_config).add(od_args); // parse command line po::variables_map vm; po::store(po::command_line_parser(argc, (char**)argv). options(od_parse).positional(pod_args).run(), vm); po::notify(vm); // parse config file if required if (!configFilename.empty()) { ifstream is(configFilename.c_str()); if (is) { cout << "Reading configuration file " << configFilename << "\n\n"; po::store(parse_config_file(is, od_config), vm); po::notify(vm); } else { cout << "Unable to read configuration file " << configFilename << "\n\n"; } } // remember filenames from command line if (vm.count(label_args)) { config.filenames = vm[label_args].as< vector<string> >(); // expand the filenames by globbing to handle wildcards vector<bfs::path> globbedFilenames; BOOST_FOREACH(const string& filename, config.filenames) if (expand_pathmask(bfs::path(filename), globbedFilenames) == 0) cout << "[idconvert] no files found matching \"" << filename << "\"" << endl; config.filenames.clear(); BOOST_FOREACH(const bfs::path& filename, globbedFilenames) config.filenames.push_back(filename.string()); } // parse filelist if required if (!filelistFilename.empty()) { ifstream is(filelistFilename.c_str()); while (is) { string filename; getline(is, filename); if (is) config.filenames.push_back(filename); } } // check stuff if (config.filenames.empty()) throw user_error("[idconvert] No files specified."); int count = format_text + format_mzIdentML + format_pepXML; if (count > 1) throw user_error("[idconvert] Multiple format flags specified."); if (format_text) config.writeConfig.format = IdentDataFile::Format_Text; if (format_mzIdentML) config.writeConfig.format = IdentDataFile::Format_MzIdentML; if (format_pepXML) config.writeConfig.format = IdentDataFile::Format_pepXML; //config.writeConfig.gzipped = gzip; // if true, file is written as .gz if (config.extension.empty()) { switch (config.writeConfig.format) { case IdentDataFile::Format_Text: config.extension = ".txt"; break; case IdentDataFile::Format_MzIdentML: config.extension = ".mzid"; break; case IdentDataFile::Format_pepXML: config.extension = ".pepXML"; break; default: throw user_error("[idconvert] Unsupported format."); } /*if (config.writeConfig.gzipped) { config.extension += ".gz"; }*/ } return config; } /*void addContactInfo(MSData& msd, const string& contactFilename) { ifstream is(contactFilename.c_str()); if (!is) { cerr << "unable to read contact info: " << contactFilename << endl; return; } Contact contact; IO::read(is, contact); msd.fileDescription.contacts.push_back(contact); }*/ struct UserFeedbackIterationListener : public IterationListener { virtual Status update(const UpdateMessage& updateMessage) { int index = updateMessage.iterationIndex; int count = updateMessage.iterationCount; // when the index is 0, create a new line if (index == 0) cout << endl; cout << updateMessage.message; if (index > 0) { cout << ": " << index+1; if (count > 0) cout << "/" << count; } // add tabs to erase all of the previous line cout << "\t\t\t\r" << flush; return Status_Ok; } }; /*void calculateSourceFilePtrSHA1(const SourceFilePtr& sourceFilePtr) { calculateSourceFileSHA1(*sourceFilePtr); }*/ /*int mergeFiles(const vector<string>& filenames, const Config& config, const ReaderList& readers) { vector<MSDataPtr> msdList; int failedFileCount = 0; BOOST_FOREACH(const string& filename, filenames) { try { cout << "processing file: " << filename << endl; readers.read(filename, msdList); } catch (exception& e) { ++failedFileCount; cerr << "Error reading file " << filename << ":\n" << e.what() << endl; } } // handle progress updates if requested IterationListenerRegistry iterationListenerRegistry; UserFeedbackIterationListener feedback; // update on the first spectrum, the last spectrum, the 100th spectrum, the 200th spectrum, etc. const size_t iterationPeriod = 100; iterationListenerRegistry.addListener(feedback, iterationPeriod); IterationListenerRegistry* pILR = config.verbose ? &iterationListenerRegistry : 0; try { MSDataMerger msd(msdList); cout << "calculating source file checksums" << endl; // calculate SHA1 checksums for_each(msd.fileDescription.sourceFilePtrs.begin(), msd.fileDescription.sourceFilePtrs.end(), &calculateSourceFilePtrSHA1); if (!config.contactFilename.empty()) addContactInfo(msd, config.contactFilename); SpectrumListFactory::wrap(msd, config.filters); string outputFilename = config.outputFilename("merged-spectra", msd); cout << "writing output file: " << outputFilename << endl; if (config.outputPath == "-") MSDataFile::write(msd, cout, config.writeConfig, pILR); else MSDataFile::write(msd, outputFilename, config.writeConfig, pILR); } catch (exception& e) { failedFileCount = (int)filenames.size(); cerr << "Error merging files: " << e.what() << endl; } return failedFileCount; }*/ void processFile(const string& filename, const Config& config, const ReaderList& readers) { // handle progress updates if requested IterationListenerRegistry iterationListenerRegistry; // update on the first spectrum, the last spectrum, the 100th spectrum, the 200th spectrum, etc. const double iterationPeriod = 0.5; iterationListenerRegistry.addListenerWithTimer(IterationListenerPtr(new UserFeedbackIterationListener), iterationPeriod); IterationListenerRegistry* pILR = config.verbose ? &iterationListenerRegistry : 0; // read in data file cout << "processing file: " << filename << endl; vector<IdentDataPtr> iddList; Reader::Config readerConfig; readerConfig.iterationListenerRegistry = pILR; readerConfig.ignoreProteinDetectionList = config.writeConfig.format == IdentDataFile::Format_pepXML; readers.read(filename, iddList, readerConfig); for (size_t i=0; i < iddList.size(); ++i) { IdentData& idd = *iddList[i]; try { // process the data /*if (!config.contactFilename.empty()) addContactInfo(msd, config.contactFilename);*/ // write out the new data file string outputFilename = config.outputFilename(filename, idd, iddList.size() > 1); cout << "writing output file: " << outputFilename << endl; if (config.outputPath == "-") IdentDataFile::write(idd, outputFilename, cout, config.writeConfig); else IdentDataFile::write(idd, outputFilename, config.writeConfig, pILR); } catch (exception& e) { cerr << "Error writing analysis " << (i+1) << " in " << bfs::path(filename).leaf() << ":\n" << e.what() << endl; } } cout << endl; } int go(const Config& config) { cout << config; boost::filesystem::create_directories(config.outputPath); DefaultReaderList readers; int failedFileCount = 0; /*if (config.merge) failedFileCount = mergeFiles(config.filenames, config, readers); else*/ { BOOST_FOREACH(const string& filename, config.filenames) { try { processFile(filename, config, readers); } catch (exception& e) { failedFileCount++; cout << e.what() << endl; cout << "Error processing file " << filename << "\n\n"; } } } return failedFileCount; } int main(int argc, const char* argv[]) { try { Config config = parseCommandLine(argc, argv); return go(config); } catch (usage_exception& e) { cerr << e.what() << endl; return 0; } catch (user_error& e) { cerr << e.what() << endl; return 1; } catch (boost::program_options::error& e) { cerr << "Invalid command-line: " << e.what() << endl; return 1; } catch (exception& e) { cerr << e.what() << endl; } catch (...) { cerr << "[" << argv[0] << "] Caught unknown exception.\n"; } cerr << "Please report this error to support@proteowizard.org.\n" << "Attach the command output and this version information in your report:\n" << "\n" << "ProteoWizard release: " << pwiz::Version::str() << " (" << pwiz::Version::LastModified() << ")" << endl << "ProteoWizard IdentData: " << pwiz::identdata::Version::str() << " (" << pwiz::identdata::Version::LastModified() << ")" << endl << "Build date: " << __DATE__ << " " << __TIME__ << endl; return 1; }
31.734062
141
0.596372
shze
edeb285194394566d4fcbcd0905cc5aee7d520e2
6,141
cpp
C++
src/SystemResources.in.cpp
atlantis07/LimeSuite
9c365b144dc8fcc277a77843adf7dd4d55ba6406
[ "Apache-2.0" ]
null
null
null
src/SystemResources.in.cpp
atlantis07/LimeSuite
9c365b144dc8fcc277a77843adf7dd4d55ba6406
[ "Apache-2.0" ]
null
null
null
src/SystemResources.in.cpp
atlantis07/LimeSuite
9c365b144dc8fcc277a77843adf7dd4d55ba6406
[ "Apache-2.0" ]
null
null
null
/** @file SystemResources.h @author Lime Microsystems @brief APIs for locating system resources. */ #include "SystemResources.h" #include "ErrorReporting.h" #include <cstdlib> //getenv, system #include <vector> #include <sstream> #include <iostream> #ifdef _MSC_VER #include <windows.h> #include <shlobj.h> #include <io.h> //access mode constants #define F_OK 0 #define R_OK 2 #define W_OK 4 #endif #ifdef __unix__ #include <pwd.h> #include <unistd.h> #endif #include <sys/types.h> #include <sys/stat.h> //stat std::string lime::getLimeSuiteRoot(void) { //first check the environment variable const char *limeSuiteRoot = std::getenv("LIME_SUITE_ROOT"); if (limeSuiteRoot != nullptr) return limeSuiteRoot; // Get the path to the current dynamic linked library. // The path to this library can be used to determine // the installation root without prior knowledge. #if defined(_MSC_VER) && defined(LIME_DLL) char path[MAX_PATH]; HMODULE hm = NULL; if (GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) &lime::getLimeSuiteRoot, &hm)) { const DWORD size = GetModuleFileNameA(hm, path, sizeof(path)); if (size != 0) { const std::string libPath(path, size); const size_t slash0Pos = libPath.find_last_of("/\\"); const size_t slash1Pos = libPath.substr(0, slash0Pos).find_last_of("/\\"); if (slash0Pos != std::string::npos && slash1Pos != std::string::npos) return libPath.substr(0, slash1Pos); } } #endif //_MSC_VER && LIME_DLL return "@LIME_SUITE_ROOT@"; } std::string lime::getHomeDirectory(void) { //first check the HOME environment variable const char *userHome = std::getenv("HOME"); if (userHome != nullptr) return userHome; //use unix user id lookup to get the home directory #ifdef __unix__ const char *pwDir = getpwuid(getuid())->pw_dir; if (pwDir != nullptr) return pwDir; #endif return ""; } /*! * The generic location for data storage with user permission level. */ static std::string getBareAppDataDirectory(void) { //always check APPDATA (usually windows, but can be set for linux) const char *appDataDir = std::getenv("APPDATA"); if (appDataDir != nullptr) return appDataDir; //use windows API to query for roaming app data directory #ifdef _MSC_VER char csidlAppDataDir[MAX_PATH]; if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, csidlAppDataDir))) { return csidlAppDataDir; } #endif //xdg freedesktop standard location environment variable #ifdef __unix__ const char *xdgDataHome = std::getenv("XDG_DATA_HOME"); if (xdgDataHome != nullptr) return xdgDataHome; #endif //xdg freedesktop standard location for data in home directory return lime::getHomeDirectory() + "/.local/share"; } std::string lime::getAppDataDirectory(void) { return getBareAppDataDirectory() + "/LimeSuite"; } std::string lime::getConfigDirectory(void) { //xdg standard is XDG_CONFIG_HOME or $HOME/.config //but historically we have used $HOME/.limesuite return lime::getHomeDirectory() + "/.limesuite"; } std::vector<std::string> lime::listImageSearchPaths(void) { std::vector<std::string> imageSearchPaths; //separator for search paths in the environment variable #ifdef _MSC_VER static const char sep = ';'; #else static const char sep = ':'; #endif //check the environment's search path const char *imagePathEnv = std::getenv("LIME_IMAGE_PATH"); if (imagePathEnv != nullptr) { std::stringstream imagePaths(imagePathEnv); std::string imagePath; while (std::getline(imagePaths, imagePath, sep)) { if (imagePath.empty()) continue; imageSearchPaths.push_back(imagePath); } } //search directories in the user's home directory imageSearchPaths.push_back(lime::getAppDataDirectory() + "/images"); //search global installation directories imageSearchPaths.push_back(lime::getLimeSuiteRoot() + "/share/LimeSuite/images"); return imageSearchPaths; } std::string lime::locateImageResource(const std::string &name) { for (const auto &searchPath : lime::listImageSearchPaths()) { const std::string fullPath(searchPath + "/@VERSION_MAJOR@.@VERSION_MINOR@/" + name); if (access(fullPath.c_str(), R_OK) == 0) return fullPath; } return ""; } int lime::downloadImageResource(const std::string &name) { const std::string destDir(lime::getAppDataDirectory() + "/images/@VERSION_MAJOR@.@VERSION_MINOR@"); const std::string destFile(destDir + "/" + name); const std::string sourceUrl("http://downloads.myriadrf.org/project/limesuite/@VERSION_MAJOR@.@VERSION_MINOR@/" + name); //check if the directory already exists struct stat s; if (stat(destDir.c_str(), &s) == 0) { if ((s.st_mode & S_IFDIR) == 0) { return lime::ReportError("Not a directory: %s", destDir.c_str()); } } //create images directory else { #ifdef __unix__ const std::string mkdirCmd("mkdir -p \""+destDir+"\""); #else const std::string mkdirCmd("md.exe \""+destDir+"\""); #endif int result = std::system(mkdirCmd.c_str()); if (result != 0) return lime::ReportError(result, "Failed: %s", mkdirCmd.c_str()); } //check for write access if (access(destDir.c_str(), W_OK) != 0) lime::ReportError("Cannot write: %s", destDir.c_str()); //download the file #ifdef __unix__ const std::string dnloadCmd("wget --output-document=\""+destFile+"\" \""+sourceUrl+"\""); #else const std::string dnloadCmd("powershell.exe -Command \"(new-object System.Net.WebClient).DownloadFile('"+sourceUrl+"', '"+destFile+"')\""); #endif int result = std::system(dnloadCmd.c_str()); if (result != 0) return lime::ReportError(result, "Failed: %s", dnloadCmd.c_str()); return 0; }
29.81068
143
0.658362
atlantis07
edeea8fe78da3db68b868d896923f2a56c5631e7
1,897
hh
C++
packages/solid/Region.hh
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
2
2020-04-13T20:06:41.000Z
2021-02-12T17:55:54.000Z
packages/solid/Region.hh
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
1
2018-10-22T21:03:35.000Z
2018-10-22T21:03:35.000Z
packages/solid/Region.hh
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
3
2019-04-03T02:15:37.000Z
2022-01-04T05:50:23.000Z
#ifndef Region_hh #define Region_hh #include <memory> #include <vector> #include "Surface.hh" template<class T1, class T2> class Conversion; class Material; class XML_Node; /* Describes a solid geometry region The memory for the regions must be allocated before the data is initialized, as a region can be defined in terms of other regions. Because of this, the "initialize" function must be called after the constructor. This allows construction of the regions in any order without regard for interdependencies. */ class Region { public: // Is the point inside or outside of the region enum class Relation { INSIDE, OUTSIDE }; std::shared_ptr<Conversion<Relation, std::string> > relation_conversion() const; // Constructor Region(int index, std::shared_ptr<Material> material, std::vector<Surface::Relation> const &surface_relations, std::vector<std::shared_ptr<Surface> > const &surfaces); int index() const { return index_; } int number_of_surfaces() const { return surfaces_.size(); } std::shared_ptr<Material> material() const { return material_; } Surface::Relation surface_relation(int s) const { return surface_relations_[s]; } std::shared_ptr<Surface> const &surface(int s) const { return surfaces_[s]; } std::vector<std::shared_ptr<Surface> > const &surfaces() const { return surfaces_; } Relation relation(std::vector<double> const &point) const; virtual void check_class_invariants() const; virtual void output(XML_Node output_node) const; private: int index_; std::shared_ptr<Material> material_; std::vector<Surface::Relation> surface_relations_; std::vector<std::shared_ptr<Surface> > surfaces_; }; #endif
23.7125
84
0.663679
brbass
edf0a36ef614a3d4eb6c066bc9ba1732344b6097
18,182
cc
C++
release/src/router/aria2/src/FileEntry.cc
Clarkmania/ripetomato
5eda5521468cb9cb7156ae6750cf8229b776d10e
[ "FSFAP" ]
3
2019-01-13T09:19:57.000Z
2022-01-15T12:16:14.000Z
release/src/router/aria2/src/FileEntry.cc
Clarkmania/ripetomato
5eda5521468cb9cb7156ae6750cf8229b776d10e
[ "FSFAP" ]
1
2020-07-28T08:22:45.000Z
2020-07-28T08:22:45.000Z
release/src/router/aria2/src/FileEntry.cc
Clarkmania/ripetomato
5eda5521468cb9cb7156ae6750cf8229b776d10e
[ "FSFAP" ]
1
2020-03-06T21:17:24.000Z
2020-03-06T21:17:24.000Z
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "FileEntry.h" #include <cassert> #include <algorithm> #include "util.h" #include "URISelector.h" #include "Logger.h" #include "LogFactory.h" #include "wallclock.h" #include "a2algo.h" #include "uri.h" #include "PeerStat.h" #include "fmt.h" #include "ServerStatMan.h" #include "ServerStat.h" namespace aria2 { bool FileEntry::RequestFaster::operator() (const SharedHandle<Request>& lhs, const SharedHandle<Request>& rhs) const { if(!lhs->getPeerStat()) { return false; } if(!rhs->getPeerStat()) { return true; } int lspd = lhs->getPeerStat()->getAvgDownloadSpeed(); int rspd = rhs->getPeerStat()->getAvgDownloadSpeed(); return lspd > rspd || (lspd == rspd && lhs.get() < rhs.get()); } FileEntry::FileEntry (const std::string& path, int64_t length, int64_t offset, const std::vector<std::string>& uris) : path_(path), uris_(uris.begin(), uris.end()), length_(length), offset_(offset), requested_(true), uniqueProtocol_(false), maxConnectionPerServer_(1), lastFasterReplace_(0) {} FileEntry::FileEntry() : length_(0), offset_(0), requested_(false), uniqueProtocol_(false), maxConnectionPerServer_(1) {} FileEntry::~FileEntry() {} FileEntry& FileEntry::operator=(const FileEntry& entry) { if(this != &entry) { path_ = entry.path_; length_ = entry.length_; offset_ = entry.offset_; requested_ = entry.requested_; } return *this; } bool FileEntry::operator<(const FileEntry& fileEntry) const { return offset_ < fileEntry.offset_; } bool FileEntry::exists() const { return File(getPath()).exists(); } int64_t FileEntry::gtoloff(int64_t goff) const { assert(offset_ <= goff); return goff-offset_; } void FileEntry::getUris(std::vector<std::string>& uris) const { uris.insert(uris.end(), spentUris_.begin(), spentUris_.end()); uris.insert(uris.end(), uris_.begin(), uris_.end()); } namespace { template<typename InputIterator, typename OutputIterator> OutputIterator enumerateInFlightHosts (InputIterator first, InputIterator last, OutputIterator out) { for(; first != last; ++first) { uri_split_result us; if(uri_split(&us, (*first)->getUri().c_str()) == 0) { *out++ = uri::getFieldString(us, USR_HOST, (*first)->getUri().c_str()); } } return out; } } // namespace SharedHandle<Request> FileEntry::getRequest (const SharedHandle<URISelector>& selector, bool uriReuse, const std::vector<std::pair<size_t, std::string> >& usedHosts, const std::string& referer, const std::string& method) { SharedHandle<Request> req; if(requestPool_.empty()) { std::vector<std::string> inFlightHosts; enumerateInFlightHosts(inFlightRequests_.begin(), inFlightRequests_.end(), std::back_inserter(inFlightHosts)); for(int g = 0; g < 2; ++g) { std::vector<std::string> pending; std::vector<std::string> ignoreHost; while(1) { std::string uri = selector->select(this, usedHosts); if(uri.empty()) { break; } req.reset(new Request()); if(req->setUri(uri)) { if(std::count(inFlightHosts.begin(), inFlightHosts.end(),req->getHost()) >= maxConnectionPerServer_) { pending.push_back(uri); ignoreHost.push_back(req->getHost()); req.reset(); continue; } if(referer == "*") { // Assuming uri has already been percent-encoded. req->setReferer(uri); } else { req->setReferer(util::percentEncodeMini(referer)); } req->setMethod(method); spentUris_.push_back(uri); inFlightRequests_.insert(req); break; } else { req.reset(); } } uris_.insert(uris_.begin(), pending.begin(), pending.end()); if(g == 0 && uriReuse && !req && uris_.size() == pending.size()) { // Reuse URIs other than ones in pending reuseUri(ignoreHost); } else { break; } } } else { // Skip Request object if it is still // sleeping(Request::getWakeTime() < global::wallclock()). If all // pooled objects are sleeping, return first one. Caller should // inspect returned object's getWakeTime(). RequestPool::iterator i = requestPool_.begin(); RequestPool::iterator eoi = requestPool_.end(); for(; i != eoi; ++i) { if((*i)->getWakeTime() <= global::wallclock()) { break; } } if(i == eoi) { i = requestPool_.begin(); } req = *i; requestPool_.erase(i); inFlightRequests_.insert(req); A2_LOG_DEBUG(fmt("Picked up from pool: %s", req->getUri().c_str())); } return req; } SharedHandle<Request> FileEntry::findFasterRequest(const SharedHandle<Request>& base) { const int startupIdleTime = 10; if(requestPool_.empty() || lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) { return SharedHandle<Request>(); } const SharedHandle<PeerStat>& fastest = (*requestPool_.begin())->getPeerStat(); if(!fastest) { return SharedHandle<Request>(); } const SharedHandle<PeerStat>& basestat = base->getPeerStat(); // TODO hard coded value. See PREF_STARTUP_IDLE_TIME if(!basestat || (basestat->getDownloadStartTime(). difference(global::wallclock()) >= startupIdleTime && fastest->getAvgDownloadSpeed()*0.8 > basestat->calculateDownloadSpeed())){ // TODO we should consider that "fastest" is very slow. SharedHandle<Request> fastestRequest = *requestPool_.begin(); requestPool_.erase(requestPool_.begin()); inFlightRequests_.insert(fastestRequest); lastFasterReplace_ = global::wallclock(); return fastestRequest; } return SharedHandle<Request>(); } SharedHandle<Request> FileEntry::findFasterRequest (const SharedHandle<Request>& base, const std::vector<std::pair<size_t, std::string> >& usedHosts, const SharedHandle<ServerStatMan>& serverStatMan) { const int startupIdleTime = 10; const int SPEED_THRESHOLD = 20*1024; if(lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) { return SharedHandle<Request>(); } std::vector<std::string> inFlightHosts; enumerateInFlightHosts(inFlightRequests_.begin(), inFlightRequests_.end(), std::back_inserter(inFlightHosts)); const SharedHandle<PeerStat>& basestat = base->getPeerStat(); A2_LOG_DEBUG("Search faster server using ServerStat."); // Use first 10 good URIs to introduce some randomness. const size_t NUM_URI = 10; std::vector<std::pair<SharedHandle<ServerStat>, std::string> > fastCands; std::vector<std::string> normCands; for(std::deque<std::string>::const_iterator i = uris_.begin(), eoi = uris_.end(); i != eoi && fastCands.size() < NUM_URI; ++i) { uri_split_result us; if(uri_split(&us, (*i).c_str()) == -1) { continue; } std::string host = uri::getFieldString(us, USR_HOST, (*i).c_str()); std::string protocol = uri::getFieldString(us, USR_SCHEME, (*i).c_str()); if(std::count(inFlightHosts.begin(), inFlightHosts.end(), host) >= maxConnectionPerServer_) { A2_LOG_DEBUG(fmt("%s has already used %d times, not considered.", (*i).c_str(), maxConnectionPerServer_)); continue; } if(findSecond(usedHosts.begin(), usedHosts.end(), host) != usedHosts.end()) { A2_LOG_DEBUG(fmt("%s is in usedHosts, not considered", (*i).c_str())); continue; } SharedHandle<ServerStat> ss = serverStatMan->find(host, protocol); if(ss && ss->isOK()) { if((basestat && ss->getDownloadSpeed() > basestat->calculateDownloadSpeed()*1.5) || (!basestat && ss->getDownloadSpeed() > SPEED_THRESHOLD)) { fastCands.push_back(std::make_pair(ss, *i)); } } } if(!fastCands.empty()) { std::sort(fastCands.begin(), fastCands.end(), ServerStatFaster()); SharedHandle<Request> fastestRequest(new Request()); const std::string& uri = fastCands.front().second; A2_LOG_DEBUG(fmt("Selected %s from fastCands", uri.c_str())); fastestRequest->setUri(uri); fastestRequest->setReferer(base->getReferer()); uris_.erase(std::find(uris_.begin(), uris_.end(), uri)); spentUris_.push_back(uri); inFlightRequests_.insert(fastestRequest); lastFasterReplace_ = global::wallclock(); return fastestRequest; } A2_LOG_DEBUG("No faster server found."); return SharedHandle<Request>(); } void FileEntry::storePool(const SharedHandle<Request>& request) { const SharedHandle<PeerStat>& peerStat = request->getPeerStat(); if(peerStat) { // We need to calculate average download speed here in order to // store Request in the right position in the pool. peerStat->calculateAvgDownloadSpeed(); } requestPool_.insert(request); } void FileEntry::poolRequest(const SharedHandle<Request>& request) { removeRequest(request); if(!request->removalRequested()) { storePool(request); } } bool FileEntry::removeRequest(const SharedHandle<Request>& request) { return inFlightRequests_.erase(request) == 1; } void FileEntry::removeURIWhoseHostnameIs(const std::string& hostname) { std::deque<std::string> newURIs; for(std::deque<std::string>::const_iterator itr = uris_.begin(), eoi = uris_.end(); itr != eoi; ++itr) { uri_split_result us; if(uri_split(&us, (*itr).c_str()) == -1) { continue; } if(us.fields[USR_HOST].len != hostname.size() || memcmp((*itr).c_str()+us.fields[USR_HOST].off, hostname.c_str(), hostname.size()) != 0) { newURIs.push_back(*itr); } } A2_LOG_DEBUG(fmt("Removed %lu duplicate hostname URIs for path=%s", static_cast<unsigned long>(uris_.size()-newURIs.size()), getPath().c_str())); uris_.swap(newURIs); } void FileEntry::removeIdenticalURI(const std::string& uri) { uris_.erase(std::remove(uris_.begin(), uris_.end(), uri), uris_.end()); } void FileEntry::addURIResult(std::string uri, error_code::Value result) { uriResults_.push_back(URIResult(uri, result)); } namespace { class FindURIResultByResult { private: error_code::Value r_; public: FindURIResultByResult(error_code::Value r):r_(r) {} bool operator()(const URIResult& uriResult) const { return uriResult.getResult() == r_; } }; } // namespace void FileEntry::extractURIResult (std::deque<URIResult>& res, error_code::Value r) { std::deque<URIResult>::iterator i = std::stable_partition(uriResults_.begin(), uriResults_.end(), FindURIResultByResult(r)); std::copy(uriResults_.begin(), i, std::back_inserter(res)); uriResults_.erase(uriResults_.begin(), i); } void FileEntry::reuseUri(const std::vector<std::string>& ignore) { if(A2_LOG_DEBUG_ENABLED) { for(std::vector<std::string>::const_iterator i = ignore.begin(), eoi = ignore.end(); i != eoi; ++i) { A2_LOG_DEBUG(fmt("ignore host=%s", (*i).c_str())); } } std::deque<std::string> uris = spentUris_; std::sort(uris.begin(), uris.end()); uris.erase(std::unique(uris.begin(), uris.end()), uris.end()); std::vector<std::string> errorUris(uriResults_.size()); std::transform(uriResults_.begin(), uriResults_.end(), errorUris.begin(), std::mem_fun_ref(&URIResult::getURI)); std::sort(errorUris.begin(), errorUris.end()); errorUris.erase(std::unique(errorUris.begin(), errorUris.end()), errorUris.end()); if(A2_LOG_DEBUG_ENABLED) { for(std::vector<std::string>::const_iterator i = errorUris.begin(), eoi = errorUris.end(); i != eoi; ++i) { A2_LOG_DEBUG(fmt("error URI=%s", (*i).c_str())); } } std::vector<std::string> reusableURIs; std::set_difference(uris.begin(), uris.end(), errorUris.begin(), errorUris.end(), std::back_inserter(reusableURIs)); std::vector<std::string>::iterator insertionPoint = reusableURIs.begin(); for(std::vector<std::string>::iterator i = reusableURIs.begin(), eoi = reusableURIs.end(); i != eoi; ++i) { uri_split_result us; if(uri_split(&us, (*i).c_str()) == 0 && std::find(ignore.begin(), ignore.end(), uri::getFieldString(us, USR_HOST, (*i).c_str())) == ignore.end()) { if(i != insertionPoint) { *insertionPoint = *i; } ++insertionPoint; } } reusableURIs.erase(insertionPoint, reusableURIs.end()); size_t ininum = reusableURIs.size(); if(A2_LOG_DEBUG_ENABLED) { A2_LOG_DEBUG(fmt("Found %u reusable URIs", static_cast<unsigned int>(ininum))); for(std::vector<std::string>::const_iterator i = reusableURIs.begin(), eoi = reusableURIs.end(); i != eoi; ++i) { A2_LOG_DEBUG(fmt("URI=%s", (*i).c_str())); } } uris_.insert(uris_.end(), reusableURIs.begin(), reusableURIs.end()); } void FileEntry::releaseRuntimeResource() { requestPool_.clear(); inFlightRequests_.clear(); } namespace { template<typename InputIterator> void putBackUri (std::deque<std::string>& uris, InputIterator first, InputIterator last) { for(; first != last; ++first) { uris.push_front((*first)->getUri()); } } } // namespace void FileEntry::putBackRequest() { putBackUri(uris_, requestPool_.begin(), requestPool_.end()); putBackUri(uris_, inFlightRequests_.begin(), inFlightRequests_.end()); } namespace { template<typename InputIterator, typename T> InputIterator findRequestByUri (InputIterator first, InputIterator last, const T& uri) { for(; first != last; ++first) { if(!(*first)->removalRequested() && (*first)->getUri() == uri) { return first; } } return last; } } // namespace bool FileEntry::removeUri(const std::string& uri) { std::deque<std::string>::iterator itr = std::find(spentUris_.begin(), spentUris_.end(), uri); if(itr == spentUris_.end()) { itr = std::find(uris_.begin(), uris_.end(), uri); if(itr == uris_.end()) { return false; } else { uris_.erase(itr); return true; } } else { spentUris_.erase(itr); SharedHandle<Request> req; InFlightRequestSet::iterator riter = findRequestByUri(inFlightRequests_.begin(), inFlightRequests_.end(), uri); if(riter == inFlightRequests_.end()) { RequestPool::iterator riter = findRequestByUri(requestPool_.begin(), requestPool_.end(), uri); if(riter == requestPool_.end()) { return true; } else { req = *riter; requestPool_.erase(riter); } } else { req = *riter; } req->requestRemoval(); return true; } } std::string FileEntry::getBasename() const { return File(path_).getBasename(); } std::string FileEntry::getDirname() const { return File(path_).getDirname(); } size_t FileEntry::setUris(const std::vector<std::string>& uris) { uris_.clear(); return addUris(uris.begin(), uris.end()); } bool FileEntry::addUri(const std::string& uri) { std::string peUri = util::percentEncodeMini(uri); if(uri_split(NULL, peUri.c_str()) == 0) { uris_.push_back(peUri); return true; } else { return false; } } bool FileEntry::insertUri(const std::string& uri, size_t pos) { std::string peUri = util::percentEncodeMini(uri); if(uri_split(NULL, peUri.c_str()) == 0) { pos = std::min(pos, uris_.size()); uris_.insert(uris_.begin()+pos, peUri); return true; } else { return false; } } void FileEntry::setPath(const std::string& path) { path_ = path; } void FileEntry::setContentType(const std::string& contentType) { contentType_ = contentType; } size_t FileEntry::countInFlightRequest() const { return inFlightRequests_.size(); } size_t FileEntry::countPooledRequest() const { return requestPool_.size(); } void FileEntry::setOriginalName(const std::string& originalName) { originalName_ = originalName; } bool FileEntry::emptyRequestUri() const { return uris_.empty() && inFlightRequests_.empty() && requestPool_.empty(); } void writeFilePath (std::ostream& o, const SharedHandle<FileEntry>& entry, bool memory) { if(entry->getPath().empty()) { std::vector<std::string> uris; entry->getUris(uris); if(uris.empty()) { o << "n/a"; } else { o << uris.front(); } } else { if(memory) { o << "[MEMORY]" << File(entry->getPath()).getBasename(); } else { o << entry->getPath(); } } } } // namespace aria2
29.70915
80
0.650093
Clarkmania
edf1fbcd166750ff6482174ea741e731218485c9
1,750
cpp
C++
tests/unit/general/test_zlib.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
1
2020-08-15T07:00:22.000Z
2020-08-15T07:00:22.000Z
tests/unit/general/test_zlib.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
null
null
null
tests/unit/general/test_zlib.cpp
stefanhenneking/mfem
dc4715e03d177233ea0d891f2875324cadb06dc4
[ "BSD-3-Clause" ]
1
2021-09-15T14:14:29.000Z
2021-09-15T14:14:29.000Z
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "mfem.hpp" #include "catch.hpp" using namespace mfem; #ifdef MFEM_USE_ZLIB TEST_CASE("Save and load file", "[zlib]") { std::string mesh_name = "zlib_test.mesh"; Mesh mesh(2, 3, Element::QUADRILATERAL, 0, 2.0, 3.0); SECTION("Save compressed mesh with bool argument") { // Write compressed mesh to disk. ofgzstream mesh_file(mesh_name, true); mesh.Print(mesh_file); REQUIRE(mesh_file.fail() == false); } SECTION("Save compressed mesh saved with bool argument") { // Load compressed mesh and create new mesh object. Mesh loaded_mesh(mesh_name.c_str()); REQUIRE(mesh.Dimension() == loaded_mesh.Dimension()); REQUIRE(std::remove(mesh_name.c_str()) == 0); } SECTION("Save compressed mesh with string argument") { ofgzstream mesh_file(mesh_name, "zwb6"); mesh.Print(mesh_file); REQUIRE(mesh_file.fail() == false); } SECTION("Load compressed mesh saved with string argument") { // Load compressed mesh and create new mesh object. Mesh loaded_mesh(mesh_name.c_str()); REQUIRE(mesh.Dimension() == loaded_mesh.Dimension()); REQUIRE(std::remove(mesh_name.c_str()) == 0); } } #endif
29.166667
80
0.684571
stefanhenneking
edf3bf559ad9311c86fc2fb2156b6a78c6b5b5da
2,647
hpp
C++
Samples/EnginePrototype/PrototypeApplication.hpp
samkusin/overview
affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1
[ "MIT" ]
null
null
null
Samples/EnginePrototype/PrototypeApplication.hpp
samkusin/overview
affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1
[ "MIT" ]
null
null
null
Samples/EnginePrototype/PrototypeApplication.hpp
samkusin/overview
affddf0b21f7e76ad9dae1425a4f5ac6a29a24c1
[ "MIT" ]
null
null
null
// // GameController.hpp // EnginePrototype // // Created by Samir Sinha on 12/9/15. // // #ifndef Prototype_Application_hpp #define Prototype_Application_hpp #include "GameTypes.hpp" #include "Common.hpp" #include "ResourceFactory.hpp" #include "UICore/UIEngine.hpp" #include "Engine/EntityDatabase.hpp" #include "Engine/Messages/Core.hpp" #include "Engine/Render/RenderContext.hpp" #include "Engine/Controller/ControllerTypes.hpp" #include "Engine/ViewStack.hpp" #include "CKGfx/GfxTypes.hpp" #include "CKGfx/NodeRenderer.hpp" #include <cinek/allocator.hpp> #include <cinek/taskscheduler.hpp> #include <ckmsg/messenger.hpp> #include <ckmsg/server.hpp> #include <ckmsg/client.hpp> #include <functional> #include <string> namespace cinek { class GameEntityFactory; struct ApplicationContext; class PrototypeApplication { public: PrototypeApplication ( gfx::Context& gfxContext, const gfx::NodeRenderer::ProgramMap& programs, const gfx::NodeRenderer::UniformMap& uniforms, NVGcontext* nvg ); ~PrototypeApplication(); void beginFrame(); void simulateFrame(CKTimeDelta dt); void renderFrame(CKTimeDelta dt, const gfx::Rect& viewRect, const cinek::input::InputState& inputState); void endFrame(); private: gfx::Context* _gfxContext; // important - Application context must be destroyed after all objects // below are destroyed. unique_ptr<ApplicationContext> _appContext; TaskScheduler _taskScheduler; ckmsg::Messenger _messenger; ove::MessageServer _server; ove::MessageClient _client; ove::MessageClientSender _clientSender; ove::ResourceFactory _resourceFactory; gfx::NodeRenderer::ProgramMap _renderPrograms; gfx::NodeRenderer::UniformMap _renderUniforms; gfx::NodeRenderer _renderer; NVGcontext* _nvg; unique_ptr<ove::RenderGraph> _renderGraph; ove::RenderContext _renderContext; unique_ptr<ove::EntityDatabase> _entityDb; unique_ptr<ove::SceneDataContext> _sceneData; unique_ptr<ove::SceneDebugDrawer> _sceneDbgDraw; unique_ptr<ove::Scene> _scene; unique_ptr<ove::Pathfinder> _pathfinder; unique_ptr<ove::PathfinderDebug> _pathfinderDebug; unique_ptr<NavDataContext> _navDataContext; unique_ptr<ove::NavSystem> _navSystem; unique_ptr<TransformDataContext> _transformDataContext; unique_ptr<ove::TransformSystem> _transformSystem; unique_ptr<GameEntityFactory> _componentFactory; ove::ViewStack _viewStack; }; } #endif /* Prototype_Application_hpp */
24.284404
75
0.722327
samkusin
edf3de456d91f0f6b3b4cedc269b1142465547c3
4,955
cpp
C++
EllysDeathStars.cpp
felikjunvianto/kfile-tc-srm-submissions
c98b21c6dbffb8c80b97abddc08d77c508aa43dc
[ "MIT" ]
null
null
null
EllysDeathStars.cpp
felikjunvianto/kfile-tc-srm-submissions
c98b21c6dbffb8c80b97abddc08d77c508aa43dc
[ "MIT" ]
null
null
null
EllysDeathStars.cpp
felikjunvianto/kfile-tc-srm-submissions
c98b21c6dbffb8c80b97abddc08d77c508aa43dc
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; class EllysDeathStars { public: double getMax(vector <string> stars, vector <string> ships) { } }; // BEGIN CUT HERE #include <ctime> #include <cmath> #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main(int argc, char* argv[]) { if (argc == 1) { cout << "Testing EllysDeathStars (1000.0 points)" << endl << endl; for (int i = 0; i < 20; i++) { ostringstream s; s << argv[0] << " " << i; int exitCode = system(s.str().c_str()); if (exitCode) cout << "#" << i << ": Runtime Error" << endl; } int T = time(NULL)-1337452065; double PT = T/60.0, TT = 75.0; cout.setf(ios::fixed,ios::floatfield); cout.precision(2); cout << endl; cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl; cout << "Score : " << 1000.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl; } else { int _tc; istringstream(argv[1]) >> _tc; EllysDeathStars _obj; double _expected, _received; time_t _start = clock(); switch (_tc) { case 0: { string stars[] = {"2 2"}; string ships[] = {"1 1 5 3 2 1 2"}; _expected = 0.894427190999916; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; } case 1: { string stars[] = {"12 10", "7 5"}; string ships[] = {"10 10 12 10 1 1 3", "6 1 8 10 1 2 3", "3 6 8 2 5 3 1", "42 42 42 42 6 6 6"}; _expected = 4.983770744659944; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; } case 2: { string stars[] = {"5 77", "60 50", "10 46", "22 97", "87 69"}; string ships[] = {"42 17 66 11 5 7 13", "10 10 20 20 3 3 3", "13 15 18 9 4 1 2", "99 71 63 81 19 4 60", "27 34 56 43 11 3 12"}; _expected = 0.0; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; } case 3: { string stars[] = {"141 393", "834 847", "568 43", "18 228", "515 794", "167 283", "849 333", "719 738", "434 261", "613 800", "127 340", "466 938", "598 601"}; string ships[] = {"410 951 472 100 337 226 210", "713 352 677 908 731 687 300", "191 41 337 92 446 716 213", "598 889 446 907 148 650 203", "168 556 470 924 344 369 198", "300 182 350 936 737 533 45", "410 871 488 703 746 631 80", "270 777 636 539 172 103 56", "466 906 522 98 693 77 309", "768 698 846 110 14 643 14", "755 724 664 465 263 759 120"}; _expected = 31.965770956316362; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; } /*case 4: { string stars[] = ; string ships[] = ; _expected = ; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; }*/ /*case 5: { string stars[] = ; string ships[] = ; _expected = ; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; }*/ /*case 6: { string stars[] = ; string ships[] = ; _expected = ; _received = _obj.getMax(vector <string>(stars, stars+sizeof(stars)/sizeof(string)), vector <string>(ships, ships+sizeof(ships)/sizeof(string))); break; }*/ default: return 0; } cout.setf(ios::fixed,ios::floatfield); cout.precision(2); double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC; if (abs(_expected-_received) < 1e-9 || (_received > min(_expected*(1.0-1e-9), _expected*(1.0+1e-9)) && _received < max(_expected*(1.0-1e-9), _expected*(1.0+1e-9)))) cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl; else { cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl; cout.precision(10); cout << " Expected: " << _expected << endl; cout << " Received: " << _received << endl; } } } // END CUT HERE
33.255034
167
0.569526
felikjunvianto
edf549339fe1f22307d75e232580293c447e6f88
3,650
cpp
C++
test/unit/cuda/test-forall-view.cpp
resslerruntime/RAJA
43a7f76d50972fa8c7aaad05fb361de5e91c2620
[ "BSD-3-Clause" ]
1
2019-09-27T02:45:41.000Z
2019-09-27T02:45:41.000Z
test/unit/cuda/test-forall-view.cpp
resslerruntime/RAJA
43a7f76d50972fa8c7aaad05fb361de5e91c2620
[ "BSD-3-Clause" ]
null
null
null
test/unit/cuda/test-forall-view.cpp
resslerruntime/RAJA
43a7f76d50972fa8c7aaad05fb361de5e91c2620
[ "BSD-3-Clause" ]
null
null
null
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-19, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #include <cstdlib> #include <string> #include "RAJA/RAJA.hpp" #include "RAJA_gtest.hpp" using namespace RAJA; using namespace std; const size_t block_size = 256; static double* arr_h; static double* arr_d; static Index_type alen; static double test_val; struct ForallViewCUDA : ::testing::Test { virtual void SetUp() { alen = 100000; test_val = 0.123; arr_h = (double*)allocate_aligned(DATA_ALIGN, alen * sizeof(double)); for (Index_type i = 0; i < alen; ++i) { arr_h[i] = double(rand() % 65536); } cudaErrchk(cudaMalloc((void**)&arr_d, alen * sizeof(double))); cudaErrchk(cudaMemcpy(arr_d, arr_h, alen * sizeof(double), cudaMemcpyHostToDevice)); } virtual void TearDown() { free_aligned(arr_h); cudaErrchk(cudaFree(arr_d)); } }; CUDA_TEST_F(ForallViewCUDA, ForallViewLayout) { const Index_type alen = ::alen; double* arr_h = ::arr_h; double* arr_d = ::arr_d; double test_val = ::test_val; const RAJA::Layout<1> my_layout(alen); RAJA::View<double, RAJA::Layout<1>> view(arr_d, my_layout); forall<RAJA::cuda_exec<block_size>>(RAJA::RangeSegment(0, alen), [=] RAJA_HOST_DEVICE(Index_type i) { view(i) = test_val; }); cudaErrchk(cudaMemcpy(arr_h, arr_d, alen * sizeof(double), cudaMemcpyDeviceToHost)); for (Index_type i = 0; i < alen; ++i) { EXPECT_EQ(arr_h[i], test_val); } } CUDA_TEST_F(ForallViewCUDA, ForallViewOffsetLayout) { const Index_type alen = ::alen; double* arr_h = ::arr_h; double* arr_d = ::arr_d; double test_val = ::test_val; RAJA::OffsetLayout<1> my_layout = RAJA::make_offset_layout<1>({{1}}, {{alen + 1}}); RAJA::View<double, RAJA::OffsetLayout<1>> view(arr_d, my_layout); forall<RAJA::cuda_exec<block_size>>(RAJA::RangeSegment(1, alen + 1), [=] RAJA_DEVICE(Index_type i) { view(i) = test_val; }); cudaErrchk(cudaMemcpy(arr_h, arr_d, alen * sizeof(double), cudaMemcpyDeviceToHost)); for (Index_type i = 0; i < alen; ++i) { EXPECT_EQ(arr_h[i], test_val); } } CUDA_TEST_F(ForallViewCUDA, ForallViewOffsetLayout2D) { using RAJA::Index_type; Index_type* box; const Index_type DIM = 2; const Index_type N = 2; const Index_type boxSize = (N + 2) * (N + 2); cudaErrchk(cudaMallocManaged((void**)&box, boxSize * sizeof(Index_type), cudaMemAttachGlobal)); RAJA::OffsetLayout<DIM> layout = RAJA::make_offset_layout<DIM>({{-1, -1}}, {{2, 2}}); RAJA::View<Index_type, RAJA::OffsetLayout<DIM>> boxview(box, layout); forall<RAJA::cuda_exec<256>>(RAJA::RangeSegment(0, N * N), [=] RAJA_HOST_DEVICE(Index_type i) { const int col = i % N; const int row = i / N; boxview(row, col) = 1000; }); for (Index_type row = 0; row < N; ++row) { for (Index_type col = 0; col < N; ++col) { int id = (col + 1) + (N + 2) * (row + 1); EXPECT_EQ(box[id], 1000); } } cudaErrchk(cudaFree(box)); }
28.515625
88
0.556986
resslerruntime
edf56876548982c8df49bd0276eb0d1c6e2cb7ff
20,891
cpp
C++
src/game/server/fogcontroller.cpp
hitmen047/City-17-Episode-One-Source-2013
7c210bca82dad51b17bb6d47dee94a996111fd77
[ "Unlicense" ]
9
2016-06-03T17:39:38.000Z
2018-11-15T13:51:07.000Z
src/game/server/fogcontroller.cpp
KyleGospo/City-17-Episode-One-Source-2013
0cc2bb3c19dd411f0eb3e86665cec2eec8952d5e
[ "Unlicense" ]
2
2017-01-10T11:45:03.000Z
2018-05-23T16:42:56.000Z
src/game/server/fogcontroller.cpp
hitmen047/City-17-Episode-One-Source-2013
7c210bca82dad51b17bb6d47dee94a996111fd77
[ "Unlicense" ]
7
2016-06-03T17:40:07.000Z
2019-09-08T16:43:31.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // An entity that allows level designer control over the fog parameters. // //============================================================================= #include "cbase.h" #include "fogcontroller.h" #include "entityinput.h" #include "entityoutput.h" #include "eventqueue.h" #include "player.h" #include "world.h" #include "ndebugoverlay.h" #ifdef C17 #include "KeyValues.h" #include "filesystem.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" CFogSystem s_FogSystem( "FogSystem" ); #ifdef C17 ConVar debug_fog_lerping("debug_fog_lerping", "0", FCVAR_CHEAT); #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CFogSystem *FogSystem( void ) { return &s_FogSystem; } LINK_ENTITY_TO_CLASS( env_fog_controller, CFogController ); BEGIN_DATADESC( CFogController ) DEFINE_INPUTFUNC( FIELD_FLOAT, "SetStartDist", InputSetStartDist ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetEndDist", InputSetEndDist ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetMaxDensity", InputSetMaxDensity ), DEFINE_INPUTFUNC( FIELD_VOID, "TurnOn", InputTurnOn ), DEFINE_INPUTFUNC( FIELD_VOID, "TurnOff", InputTurnOff ), DEFINE_INPUTFUNC( FIELD_COLOR32, "SetColor", InputSetColor ), DEFINE_INPUTFUNC( FIELD_COLOR32, "SetColorSecondary", InputSetColorSecondary ), DEFINE_INPUTFUNC( FIELD_INTEGER, "SetFarZ", InputSetFarZ ), DEFINE_INPUTFUNC( FIELD_STRING, "SetAngles", InputSetAngles ), DEFINE_INPUTFUNC( FIELD_COLOR32, "SetColorLerpTo", InputSetColorLerpTo ), DEFINE_INPUTFUNC( FIELD_COLOR32, "SetColorSecondaryLerpTo", InputSetColorSecondaryLerpTo ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetStartDistLerpTo", InputSetStartDistLerpTo ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetEndDistLerpTo", InputSetEndDistLerpTo ), #ifdef C17 DEFINE_INPUTFUNC(FIELD_FLOAT, "SetMaxDensLerpTo", InputSetMaxDensLerpTo), DEFINE_INPUTFUNC(FIELD_FLOAT, "SetFarZLerpTo", InputSetFarZLerpTo), //DEFINE_INPUTFUNC( FIELD_VOID, "StartFogTransition", InputStartFogTransition ), DEFINE_INPUTFUNC(FIELD_BOOLEAN, "SetUseBlending", InputSetUseBlending), #else DEFINE_INPUTFUNC( FIELD_VOID, "StartFogTransition", InputStartFogTransition ), #endif // Quiet classcheck //DEFINE_EMBEDDED( m_fog ), #ifdef C17 DEFINE_KEYFIELD(m_iszFogSet, FIELD_STRING, "FogScript"), #endif DEFINE_KEYFIELD( m_bUseAngles, FIELD_BOOLEAN, "use_angles" ), DEFINE_KEYFIELD( m_fog.colorPrimary, FIELD_COLOR32, "fogcolor" ), DEFINE_KEYFIELD( m_fog.colorSecondary, FIELD_COLOR32, "fogcolor2" ), DEFINE_KEYFIELD( m_fog.dirPrimary, FIELD_VECTOR, "fogdir" ), DEFINE_KEYFIELD( m_fog.enable, FIELD_BOOLEAN, "fogenable" ), DEFINE_KEYFIELD( m_fog.blend, FIELD_BOOLEAN, "fogblend" ), DEFINE_KEYFIELD( m_fog.start, FIELD_FLOAT, "fogstart" ), DEFINE_KEYFIELD( m_fog.end, FIELD_FLOAT, "fogend" ), DEFINE_KEYFIELD( m_fog.maxdensity, FIELD_FLOAT, "fogmaxdensity" ), DEFINE_KEYFIELD( m_fog.farz, FIELD_FLOAT, "farz" ), DEFINE_KEYFIELD( m_fog.duration, FIELD_FLOAT, "foglerptime" ), DEFINE_THINKFUNC( SetLerpValues ), DEFINE_FIELD( m_iChangedVariables, FIELD_INTEGER ), #ifdef C17 DEFINE_KEYFIELD(m_fog.colorPrimaryLerpTo, FIELD_COLOR32, "fogcolorlerpto"), DEFINE_KEYFIELD(m_fog.colorSecondaryLerpTo, FIELD_COLOR32, "fogcolor2lerpto"), DEFINE_KEYFIELD(m_fog.startLerpTo, FIELD_FLOAT, "fogstartlerpto"), DEFINE_KEYFIELD(m_fog.endLerpTo, FIELD_FLOAT, "fogendlerpto"), DEFINE_KEYFIELD(m_fog.maxdensityLerpTo, FIELD_FLOAT, "fogmaxdensitylerpto"), DEFINE_KEYFIELD(m_fog.farzLerpTo, FIELD_FLOAT, "fogfarzlerpto"), #else DEFINE_FIELD( m_fog.lerptime, FIELD_TIME ), DEFINE_FIELD( m_fog.colorPrimaryLerpTo, FIELD_COLOR32 ), DEFINE_FIELD( m_fog.colorSecondaryLerpTo, FIELD_COLOR32 ), DEFINE_FIELD( m_fog.startLerpTo, FIELD_FLOAT ), DEFINE_FIELD( m_fog.endLerpTo, FIELD_FLOAT ), #endif END_DATADESC() IMPLEMENT_SERVERCLASS_ST_NOBASE( CFogController, DT_FogController ) // fog data SendPropInt( SENDINFO_STRUCTELEM( m_fog.enable ), 1, SPROP_UNSIGNED ), SendPropInt( SENDINFO_STRUCTELEM( m_fog.blend ), 1, SPROP_UNSIGNED ), SendPropVector( SENDINFO_STRUCTELEM(m_fog.dirPrimary), -1, SPROP_COORD), SendPropInt( SENDINFO_STRUCTELEM( m_fog.colorPrimary ), 32, SPROP_UNSIGNED ), SendPropInt( SENDINFO_STRUCTELEM( m_fog.colorSecondary ), 32, SPROP_UNSIGNED ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.start ), 0, SPROP_NOSCALE ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.end ), 0, SPROP_NOSCALE ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.maxdensity ), 0, SPROP_NOSCALE ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.farz ), 0, SPROP_NOSCALE ), SendPropInt( SENDINFO_STRUCTELEM( m_fog.colorPrimaryLerpTo ), 32, SPROP_UNSIGNED ), SendPropInt( SENDINFO_STRUCTELEM( m_fog.colorSecondaryLerpTo ), 32, SPROP_UNSIGNED ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.startLerpTo ), 0, SPROP_NOSCALE ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.endLerpTo ), 0, SPROP_NOSCALE ), #ifndef C17 SendPropFloat( SENDINFO_STRUCTELEM( m_fog.lerptime ), 0, SPROP_NOSCALE ), SendPropFloat( SENDINFO_STRUCTELEM( m_fog.duration ), 0, SPROP_NOSCALE ), #endif END_SEND_TABLE() #ifdef C17 #define FOG_FILE "scripts/fog_parameters.txt" #endif CFogController::CFogController() { // Make sure that old maps without fog fields don't get wacked out fog values. m_fog.enable = false; m_fog.maxdensity = 1.0f; #ifdef C17 m_iszFogSet = NULL_STRING; m_fog.colorPrimaryLerpTo.GetForModify() = m_fog.colorPrimary.Get(); m_fog.colorSecondaryLerpTo.GetForModify() = m_fog.colorSecondary.Get(); m_fog.startLerpTo.GetForModify() = m_fog.start.Get(); m_fog.endLerpTo.GetForModify() = m_fog.end.Get(); m_fog.maxdensityLerpTo = m_fog.maxdensity.Get(); m_fog.farzLerpTo = m_fog.farz.Get(); m_flLerpSpeed = 0.01; #endif } CFogController::~CFogController() { } #ifdef C17 void CFogController::ReadParams(KeyValues *pKeyValue) { if (pKeyValue == NULL) { Assert(!"Fog controller couldn't be initialized!"); return; } int r, g, b, a; Color Savecolor = pKeyValue->GetColor("primarycolor"); Savecolor.GetColor(r, g, b, a); m_fog.colorPrimary.GetForModify().r = (float)r; m_fog.colorPrimary.GetForModify().g = (float)g; m_fog.colorPrimary.GetForModify().b = (float)b; m_fog.colorPrimaryLerpTo.GetForModify() = m_fog.colorPrimary.Get(); Savecolor = pKeyValue->GetColor("secondarycolor"); Savecolor.GetColor(r, g, b, a); m_fog.colorSecondary.GetForModify().r = (float)r; m_fog.colorSecondary.GetForModify().g = (float)g; m_fog.colorSecondary.GetForModify().b = (float)b; m_fog.colorSecondaryLerpTo.GetForModify() = m_fog.colorSecondary.Get(); m_fog.start.GetForModify() = pKeyValue->GetFloat("start"); m_fog.startLerpTo.GetForModify() = m_fog.start.Get(); m_fog.end.GetForModify() = pKeyValue->GetFloat("end"); m_fog.endLerpTo.GetForModify() = m_fog.end.Get(); m_fog.maxdensity.GetForModify() = pKeyValue->GetFloat("density"); m_fog.maxdensityLerpTo = m_fog.maxdensity.Get(); m_fog.farz.GetForModify() = pKeyValue->GetFloat("farz"); m_fog.farzLerpTo = m_fog.farz.Get(); m_flLerpSpeed = pKeyValue->GetFloat("lerpspeed"); } void CFogController::PrepareFogParams(const char *pKeyName) { KeyValues *pKV = new KeyValues("FogFile"); if (!pKV->LoadFromFile(filesystem, FOG_FILE, "MOD")) { pKV->deleteThis(); Assert(!"Couldn't find fog paramater file! Fog value load aborted!"); return; } KeyValues *pKVSubkey; if (pKeyName) { pKVSubkey = pKV->FindKey(pKeyName); ReadParams(pKVSubkey); } pKV->deleteThis(); } #endif void CFogController::Spawn( void ) { BaseClass::Spawn(); #ifdef C17 if (m_iszFogSet != NULL_STRING) { PrepareFogParams((char *)STRING(m_iszFogSet)); } #endif m_fog.colorPrimaryLerpTo = m_fog.colorPrimary; m_fog.colorSecondaryLerpTo = m_fog.colorSecondary; } //----------------------------------------------------------------------------- // Activate! //----------------------------------------------------------------------------- void CFogController::Activate( ) { BaseClass::Activate(); if ( m_bUseAngles ) { AngleVectors( GetAbsAngles(), &m_fog.dirPrimary.GetForModify() ); m_fog.dirPrimary.GetForModify() *= -1.0f; } } #ifdef C17 void CFogController::StartTransition(void) { SetThink(&CFogController::SetLerpValues); SetNextThink(gpGlobals->curtime + 0.01); } void CFogController::SetLerpValuesTo(Color primary, Color secondary, float start, float end, float density, float farz) { int r, g, b, a; primary.GetColor(r, g, b, a); m_fog.colorPrimaryLerpTo.GetForModify().r = (float)r; m_fog.colorPrimaryLerpTo.GetForModify().g = (float)g; m_fog.colorPrimaryLerpTo.GetForModify().b = (float)b; secondary.GetColor(r, g, b, a); m_fog.colorSecondaryLerpTo.GetForModify().r = (float)r; m_fog.colorSecondaryLerpTo.GetForModify().g = (float)g; m_fog.colorSecondaryLerpTo.GetForModify().b = (float)b; m_fog.startLerpTo.GetForModify() = start; m_fog.endLerpTo.GetForModify() = end; m_fog.maxdensityLerpTo = density; m_fog.farzLerpTo = farz; StartTransition(); } #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CFogController::UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } //------------------------------------------------------------------------------ // Purpose: Input handler for setting the fog start distance. //------------------------------------------------------------------------------ void CFogController::InputSetStartDist(inputdata_t &inputdata) { // Get the world entity. m_fog.start = inputdata.value.Float(); } //------------------------------------------------------------------------------ // Purpose: Input handler for setting the fog end distance. //------------------------------------------------------------------------------ void CFogController::InputSetEndDist(inputdata_t &inputdata) { // Get the world entity. m_fog.end = inputdata.value.Float(); } //------------------------------------------------------------------------------ // Input handler for setting the maximum density of the fog. This lets us bring // the start distance in without the scene fogging too much. //------------------------------------------------------------------------------ void CFogController::InputSetMaxDensity( inputdata_t &inputdata ) { m_fog.maxdensity = inputdata.value.Float(); } //------------------------------------------------------------------------------ // Purpose: Input handler for turning on the fog. //------------------------------------------------------------------------------ void CFogController::InputTurnOn(inputdata_t &inputdata) { // Get the world entity. m_fog.enable = true; } //------------------------------------------------------------------------------ // Purpose: Input handler for turning off the fog. //------------------------------------------------------------------------------ void CFogController::InputTurnOff(inputdata_t &inputdata) { // Get the world entity. m_fog.enable = false; } //------------------------------------------------------------------------------ // Purpose: Input handler for setting the primary fog color. //------------------------------------------------------------------------------ void CFogController::InputSetColor(inputdata_t &inputdata) { // Get the world entity. m_fog.colorPrimary = inputdata.value.Color32(); } //------------------------------------------------------------------------------ // Purpose: Input handler for setting the secondary fog color. //------------------------------------------------------------------------------ void CFogController::InputSetColorSecondary(inputdata_t &inputdata) { // Get the world entity. m_fog.colorSecondary = inputdata.value.Color32(); } void CFogController::InputSetFarZ(inputdata_t &inputdata) { m_fog.farz = inputdata.value.Int(); } //------------------------------------------------------------------------------ // Purpose: Sets the angles to use for the secondary fog direction. //------------------------------------------------------------------------------ void CFogController::InputSetAngles( inputdata_t &inputdata ) { const char *pAngles = inputdata.value.String(); QAngle angles; UTIL_StringToVector( angles.Base(), pAngles ); Vector vTemp; AngleVectors( angles, &vTemp ); SetAbsAngles( angles ); AngleVectors( GetAbsAngles(), &m_fog.dirPrimary.GetForModify() ); m_fog.dirPrimary.GetForModify() *= -1.0f; } //----------------------------------------------------------------------------- // Purpose: Draw any debug text overlays // Output : Current text offset from the top //----------------------------------------------------------------------------- int CFogController::DrawDebugTextOverlays(void) { int text_offset = BaseClass::DrawDebugTextOverlays(); if (m_debugOverlays & OVERLAY_TEXT_BIT) { char tempstr[512]; Q_snprintf(tempstr,sizeof(tempstr),"State: %s",(m_fog.enable)?"On":"Off"); EntityText(text_offset,tempstr,0); text_offset++; Q_snprintf(tempstr,sizeof(tempstr),"Start: %3.0f",m_fog.start.Get()); EntityText(text_offset,tempstr,0); text_offset++; Q_snprintf(tempstr,sizeof(tempstr),"End : %3.0f",m_fog.end.Get()); EntityText(text_offset,tempstr,0); text_offset++; color32 color = m_fog.colorPrimary; Q_snprintf(tempstr,sizeof(tempstr),"1) Red : %i",color.r); EntityText(text_offset,tempstr,0); text_offset++; Q_snprintf(tempstr,sizeof(tempstr),"1) Green: %i",color.g); EntityText(text_offset,tempstr,0); text_offset++; Q_snprintf(tempstr,sizeof(tempstr),"1) Blue : %i",color.b); EntityText(text_offset,tempstr,0); text_offset++; color = m_fog.colorSecondary; Q_snprintf(tempstr,sizeof(tempstr),"2) Red : %i",color.r); EntityText(text_offset,tempstr,0); text_offset++; Q_snprintf(tempstr,sizeof(tempstr),"2) Green: %i",color.g); EntityText(text_offset,tempstr,0); text_offset++; Q_snprintf(tempstr,sizeof(tempstr),"2) Blue : %i",color.b); EntityText(text_offset,tempstr,0); text_offset++; } return text_offset; } #define FOG_CONTROLLER_COLORPRIMARY_LERP 1 #define FOG_CONTROLLER_COLORSECONDARY_LERP 2 #define FOG_CONTROLLER_START_LERP 4 #define FOG_CONTROLLER_END_LERP 8 void CFogController::InputSetColorLerpTo(inputdata_t &data) { m_iChangedVariables |= FOG_CONTROLLER_COLORPRIMARY_LERP; m_fog.colorPrimaryLerpTo = data.value.Color32(); } void CFogController::InputSetColorSecondaryLerpTo(inputdata_t &data) { m_iChangedVariables |= FOG_CONTROLLER_COLORSECONDARY_LERP; m_fog.colorSecondaryLerpTo = data.value.Color32(); } void CFogController::InputSetStartDistLerpTo(inputdata_t &data) { m_iChangedVariables |= FOG_CONTROLLER_START_LERP; m_fog.startLerpTo = data.value.Float(); } void CFogController::InputSetEndDistLerpTo(inputdata_t &data) { m_iChangedVariables |= FOG_CONTROLLER_END_LERP; m_fog.endLerpTo = data.value.Float(); } #ifdef C17 void CFogController::InputSetMaxDensLerpTo(inputdata_t &data) { m_fog.maxdensityLerpTo = data.value.Float(); } void CFogController::InputSetFarZLerpTo(inputdata_t &data) { m_fog.farzLerpTo = data.value.Float(); } /*void CFogController::InputStartFogTransition(inputdata_t &data) { DevMsg( "Fog Lerp starting.\n" ); StartTransition(); }*/ void CFogController::InputSetUseBlending(inputdata_t &data) { m_fog.blend = data.value.Bool(); } /*void CFogController::LerpFog( color32 *changefog, color32 *lerpfog ) { float flLerpColor[3] = { lerpfog->r, lerpfog->g, lerpfog->b }; changefog->r = Lerp( 0.01, (float)changefog->r, flLerpColor[1] ); changefog->g = Lerp( 0.01, (float)changefog->g, flLerpColor[2] ); changefog->b = Lerp( 0.01, (float)changefog->b, flLerpColor[3] ); }*/ void CFogController::SetLerpValues(void) { color32 colorPrimary = m_fog.colorPrimary; color32 colorSecondary = m_fog.colorSecondary; color32 colorPrimaryLerpTo = m_fog.colorPrimaryLerpTo; color32 colorSecondaryLerpTo = m_fog.colorSecondaryLerpTo; if (!(colorPrimary.r == colorPrimaryLerpTo.r)) { colorPrimary.r = Lerp(m_flLerpSpeed, colorPrimary.r, colorPrimaryLerpTo.r); m_fog.colorPrimary.GetForModify().r = colorPrimary.r; } if (!(colorPrimary.g == colorPrimaryLerpTo.g)) { colorPrimary.g = Lerp(m_flLerpSpeed, colorPrimary.g, colorPrimaryLerpTo.g); m_fog.colorPrimary.GetForModify().g = colorPrimary.g; } if (!(colorPrimary.b == colorPrimaryLerpTo.b)) { colorPrimary.b = Lerp(m_flLerpSpeed, colorPrimary.b, colorPrimaryLerpTo.b); m_fog.colorPrimary.GetForModify().b = colorPrimary.b; } if (!(colorSecondary.r == colorSecondaryLerpTo.r)) { colorSecondary.r = Lerp(m_flLerpSpeed, colorSecondary.r, colorSecondaryLerpTo.r); m_fog.colorSecondary.GetForModify().r = colorSecondary.r; } if (!(colorSecondary.g == colorSecondaryLerpTo.g)) { colorSecondary.g = Lerp(m_flLerpSpeed, colorSecondary.g, colorSecondaryLerpTo.g); m_fog.colorSecondary.GetForModify().g = colorSecondary.g; } if (!(colorSecondary.b == colorSecondaryLerpTo.b)) { colorSecondary.b = Lerp(m_flLerpSpeed, colorSecondary.b, colorSecondaryLerpTo.b); m_fog.colorSecondary.GetForModify().b = colorSecondary.b; } if (!(m_fog.start.Get() == m_fog.startLerpTo.Get())) { m_fog.start.GetForModify() = Lerp(m_flLerpSpeed, m_fog.start.Get(), m_fog.startLerpTo.Get()); } if (!(m_fog.end.Get() == m_fog.endLerpTo.Get())) { m_fog.end.GetForModify() = Lerp(m_flLerpSpeed, m_fog.end.Get(), m_fog.endLerpTo.Get()); } if (!(m_fog.maxdensity.Get() == m_fog.maxdensityLerpTo)) { m_fog.maxdensity.GetForModify() = Lerp(m_flLerpSpeed, m_fog.maxdensity.Get(), m_fog.maxdensityLerpTo); } if (!(m_fog.farz.Get() == m_fog.farzLerpTo)) { m_fog.farz.GetForModify() = Lerp(m_flLerpSpeed, m_fog.farz.Get(), m_fog.farzLerpTo); } if (debug_fog_lerping.GetBool()) { DevMsg("Color Primary R:%.2f G:%.2f B:%.2f\n", (float)m_fog.colorPrimary.Get().r, (float)m_fog.colorPrimary.Get().g, (float)m_fog.colorPrimary.Get().b); DevMsg("Color Secondary R:%.2f G:%.2f B:%.2f\n", (float)m_fog.colorSecondary.Get().r, (float)m_fog.colorSecondary.Get().g, (float)m_fog.colorSecondary.Get().b); DevMsg("Start: %.2f\n", m_fog.start.Get()); DevMsg("End: %.2f\n", m_fog.end.Get()); DevMsg("Density: %.2f\n", m_fog.maxdensity.Get()); DevMsg("FarZ: %.2f\n", m_fog.farz.Get()); } SetNextThink(gpGlobals->curtime + 0.01); } #else void CFogController::InputStartFogTransition(inputdata_t &data) { SetThink( &CFogController::SetLerpValues ); m_fog.lerptime = gpGlobals->curtime + m_fog.duration + 0.1; SetNextThink( gpGlobals->curtime + m_fog.duration ); } void CFogController::SetLerpValues( void ) { if ( m_iChangedVariables & FOG_CONTROLLER_COLORPRIMARY_LERP ) { m_fog.colorPrimary = m_fog.colorPrimaryLerpTo; } if ( m_iChangedVariables & FOG_CONTROLLER_COLORSECONDARY_LERP ) { m_fog.colorSecondary = m_fog.colorSecondaryLerpTo; } if ( m_iChangedVariables & FOG_CONTROLLER_START_LERP ) { m_fog.start = m_fog.startLerpTo; } if ( m_iChangedVariables & FOG_CONTROLLER_END_LERP ) { m_fog.end = m_fog.endLerpTo; } m_iChangedVariables = 0; m_fog.lerptime = gpGlobals->curtime; } #endif //----------------------------------------------------------------------------- // Purpose: Clear out the fog controller. //----------------------------------------------------------------------------- void CFogSystem::LevelInitPreEntity( void ) { m_pMasterController = NULL; } //----------------------------------------------------------------------------- // Purpose: On level load find the master fog controller. If no controller is // set as Master, use the first fog controller found. //----------------------------------------------------------------------------- void CFogSystem::LevelInitPostEntity( void ) { CFogController *pFogController = NULL; do { pFogController = static_cast<CFogController*>( gEntList.FindEntityByClassname( pFogController, "env_fog_controller" ) ); if ( pFogController ) { if ( m_pMasterController == NULL ) { m_pMasterController = pFogController; } else { if ( pFogController->IsMaster() ) { m_pMasterController = pFogController; } } } } while ( pFogController ); // HACK: Singleplayer games don't get a call to CBasePlayer::Spawn on level transitions. // CBasePlayer::Activate is called before this is called so that's too soon to set up the fog controller. // We don't have a hook similar to Activate that happens after LevelInitPostEntity // is called, or we could just do this in the player itself. if ( gpGlobals->maxClients == 1 ) { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer && ( pPlayer->m_Local.m_PlayerFog.m_hCtrl.Get() == NULL ) ) { pPlayer->InitFogController(); } } }
32.795918
162
0.66488
hitmen047
edf7839f32cd56ea2a00b3e68bfad710c7212fe4
12,289
cpp
C++
src/foo_scrobble/PlaybackScrobbler.cpp
gix/foo_scrobble
df9d3321ac29ed6f676bb540b97190118cbdf604
[ "MIT" ]
294
2017-11-20T17:42:08.000Z
2022-03-31T04:15:13.000Z
src/foo_scrobble/PlaybackScrobbler.cpp
gix/foo_scrobble
df9d3321ac29ed6f676bb540b97190118cbdf604
[ "MIT" ]
36
2017-12-03T04:24:46.000Z
2022-02-24T21:22:17.000Z
src/foo_scrobble/PlaybackScrobbler.cpp
gix/foo_scrobble
df9d3321ac29ed6f676bb540b97190118cbdf604
[ "MIT" ]
14
2018-03-10T12:47:03.000Z
2021-11-11T09:00:08.000Z
#include "ScrobbleConfig.h" #include "WebService.h" #include "fb2ksdk.h" #include "ScrobbleService.h" #include "ServiceHelper.h" #include "Track.h" namespace foo_scrobble { namespace { using SecondsD = std::chrono::duration<double>; #ifdef _DEBUG static constexpr bool IsDebug = true; #else static constexpr bool IsDebug = false; #endif constexpr SecondsD MinRequiredTrackLength{30.0}; constexpr SecondsD MaxElapsedPlaytime{240.0}; constexpr SecondsD NowPlayingMinimumPlaybackTime{3.0}; class TitleformatContext { public: titleformat_object::ptr const& GetArtistFormat() const { return artistFormat_; } titleformat_object::ptr const& GetTitleFormat() const { return titleFormat_; } titleformat_object::ptr const& GetAlbumArtistFormat() const { return albumArtistFormat_; } titleformat_object::ptr const& GetAlbumFormat() const { return albumFormat_; } titleformat_object::ptr const& GetTrackNumberFormat() const { return trackNumberFormat_; } titleformat_object::ptr const& GetMusicBrainzTrackIdFormat() const { return mbidFormat_; } titleformat_object::ptr const& GetSkipSubmissionFormat() const { return skipSubmissionFormat_; } void Recompile(ScrobbleConfig const& config) { auto compiler = titleformat_compiler::get(); Compile(compiler, artistFormat_, config.ArtistMapping, DefaultArtistMapping); Compile(compiler, titleFormat_, config.TitleMapping, DefaultTitleMapping); Compile(compiler, albumArtistFormat_, config.AlbumArtistMapping, DefaultAlbumArtistMapping); Compile(compiler, albumFormat_, config.AlbumMapping, DefaultAlbumMapping); Compile(compiler, trackNumberFormat_, config.TrackNumberMapping, DefaultTrackNumberMapping); Compile(compiler, mbidFormat_, config.MBTrackIdMapping, DefaultMBTrackIdMapping); if (!config.SkipSubmissionFormat.is_empty()) compiler->compile(skipSubmissionFormat_, config.SkipSubmissionFormat); else skipSubmissionFormat_ = nullptr; } private: static bool Compile(titleformat_compiler::ptr& compiler, titleformat_object::ptr& format, char const* spec, char const* fallbackSpec) { return compiler->compile(format, spec) || compiler->compile(format, fallbackSpec); } titleformat_object::ptr artistFormat_; titleformat_object::ptr titleFormat_; titleformat_object::ptr albumArtistFormat_; titleformat_object::ptr albumFormat_; titleformat_object::ptr trackNumberFormat_; titleformat_object::ptr mbidFormat_; titleformat_object::ptr skipSubmissionFormat_; }; class PendingTrack : public Track { public: SecondsD RequiredScrobbleTime() const { if (Duration <= SecondsD::zero()) return MinRequiredTrackLength; if constexpr (IsDebug) { return std::min(Duration, SecondsD{2.0}); } else { return std::min(Duration * 0.5, MaxElapsedPlaytime); } } bool HasRequiredFields() const { return Artist.get_length() > 0 && Title.get_length() > 0; } bool IsSkipped() const { return skip_; } bool CanScrobble(SecondsD const& playbackTime, bool logFailure = false) const { if (playbackTime < RequiredScrobbleTime()) return false; if (IsSkipped()) { if (logFailure) FB2K_console_formatter() << "foo_scrobble: Skipping track based on skip conditions"; return false; } if (!HasRequiredFields()) { if (logFailure) FB2K_console_formatter() << "foo_scrobble: Skipping track due to missing artist or title"; return false; } return true; } bool ShouldSendNowPlaying(SecondsD elapsedPlayback) const { return !notifiedNowPlaying_ && !IsSkipped() && HasRequiredFields() && elapsedPlayback >= NowPlayingMinimumPlaybackTime; } void NowPlayingSent() { notifiedNowPlaying_ = true; } void Format(metadb_handle& track, TitleformatContext& formatContext) { Timestamp = unix_clock::now(); Reformat(track, formatContext); } void Reformat(metadb_handle& track, TitleformatContext& formatContext) { track.format_title(nullptr, Artist, formatContext.GetArtistFormat(), nullptr); track.format_title(nullptr, Title, formatContext.GetTitleFormat(), nullptr); track.format_title(nullptr, AlbumArtist, formatContext.GetAlbumArtistFormat(), nullptr); track.format_title(nullptr, Album, formatContext.GetAlbumFormat(), nullptr); track.format_title(nullptr, MusicBrainzId, formatContext.GetMusicBrainzTrackIdFormat(), nullptr); track.format_title(nullptr, TrackNumber, formatContext.GetTrackNumberFormat(), nullptr); auto const skipFormat = formatContext.GetSkipSubmissionFormat(); if (!skipFormat.is_empty()) { pfc::string8_fast skip; track.format_title(nullptr, skip, formatContext.GetSkipSubmissionFormat(), nullptr); skip_ = !skip.is_empty(); } Duration = SecondsD{track.get_length()}; IsDynamic = false; lastUpdateTime_ = unix_clock::now(); } void Format(file_info const& dynamicTrack, TitleformatContext& formatContext) { auto pc = static_api_ptr_t<playback_control>(); pc->playback_format_title(nullptr, Artist, formatContext.GetArtistFormat(), nullptr, playback_control::display_level_titles); pc->playback_format_title(nullptr, Title, formatContext.GetTitleFormat(), nullptr, playback_control::display_level_titles); pc->playback_format_title(nullptr, Album, formatContext.GetAlbumFormat(), nullptr, playback_control::display_level_titles); AlbumArtist.force_reset(); TrackNumber.force_reset(); MusicBrainzId.force_reset(); auto const skipFormat = formatContext.GetSkipSubmissionFormat(); if (!skipFormat.is_empty()) { pfc::string8_fast skip; pc->playback_format_title(nullptr, skip, formatContext.GetSkipSubmissionFormat(), nullptr, playback_control::display_level_titles); skip_ = !skip.is_empty(); } Timestamp = unix_clock::now(); Duration = SecondsD{dynamicTrack.get_length()}; IsDynamic = true; lastUpdateTime_ = unix_clock::now(); } private: unix_clock::time_point lastUpdateTime_; bool notifiedNowPlaying_ = false; bool skip_ = false; }; } // namespace class PlaybackScrobbler : public service_multi_inherit<play_callback_static, ScrobbleConfigNotify> { public: PlaybackScrobbler() = default; virtual ~PlaybackScrobbler() = default; // #pragma region play_callback void on_playback_starting(play_control::t_track_command p_command, bool p_paused) override; void on_playback_new_track(metadb_handle_ptr p_track) override; void on_playback_stop(play_control::t_stop_reason p_reason) override; void on_playback_seek(double p_time) override; void on_playback_pause(bool p_state) override; void on_playback_edited(metadb_handle_ptr p_track) override; void on_playback_dynamic_info(file_info const& p_info) override; void on_playback_dynamic_info_track(file_info const& p_info) override; void on_playback_time(double p_time) override; void on_volume_change(float p_new_val) override; // #pragma endregion play_callback // #pragma region play_callback_static unsigned get_flags() override; // #pragma endregion play_callback_static // #pragma region ScrobbleConfigNotify void OnConfigChanged() override { if (formatContext_) formatContext_->Recompile(Config); } // #pragma endregion ScrobbleConfigNotify private: bool IsActive() const { return isScrobbling_ || config_.EnableNowPlaying; } void FlushCurrentTrack(); ScrobbleService& GetScrobbleService() { if (scrobbler_ == nullptr) scrobbler_ = standard_api_create_t<ScrobbleService>().get_ptr(); return *scrobbler_; } TitleformatContext& GetFormatContext() { if (!formatContext_) { formatContext_ = std::make_unique<TitleformatContext>(); formatContext_->Recompile(Config); } return *formatContext_; } ScrobbleConfig const& config_{Config}; PendingTrack pendingTrack_; SecondsD accumulatedPlaybackTime_{}; SecondsD lastPlaybackTime_{}; bool isScrobbling_ = false; std::unique_ptr<TitleformatContext> formatContext_; ScrobbleService* scrobbler_ = nullptr; }; #pragma region play_callback_static void PlaybackScrobbler::on_playback_starting(play_control::t_track_command /*p_command*/, bool /*p_paused*/) { // nothing } void PlaybackScrobbler::on_playback_new_track(metadb_handle_ptr p_track) { FlushCurrentTrack(); isScrobbling_ = config_.EnableScrobbling; if (!IsActive()) return; if (p_track->get_length() <= 0) return; bool const skipTrack = config_.SubmitOnlyInLibrary && !library_manager::get()->is_item_in_library(p_track); if (!skipTrack) { pendingTrack_.Format(*p_track, GetFormatContext()); } else { isScrobbling_ = false; FB2K_console_formatter() << "foo_scrobble: Skipping track not in media library."; } } void PlaybackScrobbler::on_playback_stop(play_control::t_stop_reason p_reason) { if (p_reason == playback_control::stop_reason_shutting_down) GetScrobbleService().Shutdown(); FlushCurrentTrack(); } void PlaybackScrobbler::on_playback_seek(double p_time) { if (!IsActive()) return; lastPlaybackTime_ = SecondsD(p_time); } void PlaybackScrobbler::on_playback_pause(bool /*p_state*/) {} void PlaybackScrobbler::on_playback_edited(metadb_handle_ptr p_track) { if (!IsActive()) return; if (!pendingTrack_.IsDynamic) pendingTrack_.Reformat(*p_track, GetFormatContext()); } void PlaybackScrobbler::on_playback_dynamic_info(file_info const& /*p_info*/) {} void PlaybackScrobbler::on_playback_dynamic_info_track(file_info const& p_info) { FlushCurrentTrack(); isScrobbling_ = config_.EnableScrobbling && config_.SubmitDynamicSources; if (!IsActive()) return; pendingTrack_.Format(p_info, GetFormatContext()); } void PlaybackScrobbler::on_playback_time(double p_time) { if (!IsActive()) return; accumulatedPlaybackTime_ += SecondsD(p_time) - lastPlaybackTime_; lastPlaybackTime_ = SecondsD(p_time); if (config_.EnableNowPlaying && pendingTrack_.ShouldSendNowPlaying(accumulatedPlaybackTime_)) { GetScrobbleService().SendNowPlayingAsync(pendingTrack_); pendingTrack_.NowPlayingSent(); } } void PlaybackScrobbler::on_volume_change(float /*p_new_val*/) {} unsigned int PlaybackScrobbler::get_flags() { return flag_on_playback_time | flag_on_playback_dynamic_info_track | flag_on_playback_edited | flag_on_playback_seek | flag_on_playback_stop | flag_on_playback_new_track; } #pragma endregion play_callback_static void PlaybackScrobbler::FlushCurrentTrack() { if (isScrobbling_ && pendingTrack_.CanScrobble(accumulatedPlaybackTime_, true)) GetScrobbleService().ScrobbleAsync(std::move(static_cast<Track&>(pendingTrack_))); accumulatedPlaybackTime_ = SecondsD::zero(); lastPlaybackTime_ = SecondsD::zero(); isScrobbling_ = false; pendingTrack_ = PendingTrack(); } static service_factory_single_v_t<PlaybackScrobbler, play_callback_static, ScrobbleConfigNotify> g_PlaybackScrobblerFactory; } // namespace foo_scrobble
31.510256
90
0.678574
gix
edf8157ecb7985f216c01428ba25326602c2d7bf
436
hpp
C++
knapsacksolver/algorithms/surrelax.hpp
fontanf/knapsack
619f8a65a9c23eaab9825dcce589408945e7ef65
[ "MIT" ]
null
null
null
knapsacksolver/algorithms/surrelax.hpp
fontanf/knapsack
619f8a65a9c23eaab9825dcce589408945e7ef65
[ "MIT" ]
null
null
null
knapsacksolver/algorithms/surrelax.hpp
fontanf/knapsack
619f8a65a9c23eaab9825dcce589408945e7ef65
[ "MIT" ]
null
null
null
#pragma once #include "knapsacksolver/solution.hpp" namespace knapsacksolver { void solvesurrelax( Instance instance, Output& output, std::function<Output (Instance&, Info, bool*)> func, bool* end, Info info = Info()); Output surrelax( const Instance& instance, Info info = Info()); Output surrelax_minknap( const Instance& instance, Info info = Info()); }
17.44
60
0.614679
fontanf
edf9a39ccb7c7bde9a2c35e00c778bc9bd04f704
35,466
cpp
C++
src/game/shared/econ/econ_item_system.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
src/game/shared/econ/econ_item_system.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
src/game/shared/econ/econ_item_system.cpp
TF2V/Tf2Vintage
983d652c338dc017dca51f5bc4eee1a3d4b7ac2e
[ "Unlicense" ]
null
null
null
#include "cbase.h" #include "filesystem.h" #include "econ_item_system.h" #include "script_parser.h" #include "activitylist.h" #include "tier0/icommandline.h" #if defined(CLIENT_DLL) #define UTIL_VarArgs VarArgs #endif const char *g_TeamVisualSections[TF_TEAM_VISUALS_COUNT] = { "visuals", // TEAM_UNASSIGNED "", // TEAM_SPECTATOR "visuals_red", // TEAM_RED "visuals_blu", // TEAM_BLUE "visuals_grn", // TEAM_GREEN "visuals_ylw", // TEAM_YELLOW "visuals_mvm_boss" // ??? }; const char *g_WearableAnimTypeStrings[NUM_WEARABLEANIM_TYPES] = { "on_spawn", "start_building", "stop_building", "start_taunting", "stop_taunting", }; const char *g_AttributeDescriptionFormats[] = { "value_is_percentage", "value_is_inverted_percentage", "value_is_additive", "value_is_additive_percentage", "value_is_or", "value_is_date", "value_is_account_id", "value_is_particle_index", "value_is_killstreakeffect_index", "value_is_killstreak_idleeffect_index", "value_is_item_def", "value_is_from_lookup_table" }; const char *g_EffectTypes[] = { "unusual", "strange", "neutral", "positive", "negative" }; const char *g_szQualityStrings[] = { "normal", "rarity1", "rarity2", "vintage", "rarity3", "rarity4", "unique", "community", "developer", "selfmade", "customized", "strange", "completed", "haunted", "collectors", "paintkitWeapon", }; const char *g_szQualityColorStrings[] = { "QualityColorNormal", "QualityColorrarity1", "QualityColorrarity2", "QualityColorVintage", "QualityColorrarity3", "QualityColorrarity4", "QualityColorUnique", "QualityColorCommunity", "QualityColorDeveloper", "QualityColorSelfMade", "QualityColorSelfMadeCustomized", "QualityColorStrange", "QualityColorCompleted", "QualityColorHaunted", "QualityColorCollectors", "QualityColorPaintkitWeapon", }; const char *g_szQualityLocalizationStrings[] = { "#Normal", "#rarity1", "#rarity2", "#vintage", "#rarity3", "#rarity4", "#unique", "#community", "#developer", "#selfmade", "#customized", "#strange", "#completed", "#haunted", "#collectors", "#paintkitWeapon", }; const char *g_szDropTypeStrings[] = { "", "none", "drop", "break", }; int GetTeamVisualsFromString( const char *pszString ) { for ( int i = 0; i < ARRAYSIZE( g_TeamVisualSections ); i++ ) { // There's a NULL hidden in g_TeamVisualSections if ( g_TeamVisualSections[i] && !V_stricmp( pszString, g_TeamVisualSections[i] ) ) return i; } return -1; } #define ITEMS_GAME "scripts/items/items_game.txt" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static CEconItemSchema g_EconItemSchema; CEconItemSchema *GetItemSchema() { return &g_EconItemSchema; } #define GET_STRING(copyto, from, name) \ if (from->GetString(#name, NULL)) \ (copyto)->name = from->GetString(#name) #define GET_STRING_DEFAULT(copyto, from, name, defaultstring) \ (copyto)->name = from->GetString(#name, defaultstring) #define GET_BOOL(copyto, from, name) \ (copyto)->name = from->GetBool(#name, (copyto)->name) #define GET_FLOAT(copyto, from, name) \ (copyto)->name = from->GetFloat(#name, (copyto)->name) #define GET_INT(copyto, from, name) \ (copyto)->name = from->GetInt(#name, (copyto)->name) #define FIND_ELEMENT(map, key, val) \ unsigned int index = map.Find(key); \ if (index != map.InvalidIndex()) \ val = map.Element(index) #define FIND_ELEMENT_STRING(map, key, val) \ unsigned int index = map.Find(key); \ if (index != map.InvalidIndex()) \ Q_snprintf(val, sizeof(val), map.Element(index)) #define IF_ELEMENT_FOUND(map, key) \ unsigned int index = map.Find(key); \ if (index != map.InvalidIndex()) #define GET_VALUES_FAST_BOOL(dict, keys)\ for (KeyValues *pKeyData = keys->GetFirstSubKey(); pKeyData != NULL; pKeyData = pKeyData->GetNextKey())\ { \ IF_ELEMENT_FOUND(dict, pKeyData->GetName()) \ { \ dict.Element(index) = pKeyData->GetBool(); \ } \ else \ { \ dict.Insert(pKeyData->GetName(), pKeyData->GetBool());\ } \ } #define GET_VALUES_FAST_STRING(dict, keys)\ for (KeyValues *pKeyData = keys->GetFirstSubKey(); pKeyData != NULL; pKeyData = pKeyData->GetNextKey()) \ { \ IF_ELEMENT_FOUND(dict, pKeyData->GetName()) \ { \ Q_strncpy((char*)dict.Element(index), pKeyData->GetString(), 196);\ } \ else \ { \ dict.Insert(pKeyData->GetName(), strdup(pKeyData->GetString()));\ } \ } // Recursively inherit keys from parent KeyValues void InheritKVRec( KeyValues *pFrom, KeyValues *pTo ) { for ( KeyValues *pSubData = pFrom->GetFirstSubKey(); pSubData != NULL; pSubData = pSubData->GetNextKey() ) { switch ( pSubData->GetDataType() ) { // Identifies the start of a subsection case KeyValues::TYPE_NONE: { KeyValues *pKey = pTo->FindKey( pSubData->GetName() ); if ( pKey == NULL ) { pKey = pTo->CreateNewKey(); pKey->SetName( pSubData->GetName() ); } InheritKVRec( pSubData, pKey ); break; } // Actual types case KeyValues::TYPE_STRING: { pTo->SetString( pSubData->GetName(), pSubData->GetString() ); break; } case KeyValues::TYPE_INT: { pTo->SetInt( pSubData->GetName(), pSubData->GetInt() ); break; } case KeyValues::TYPE_FLOAT: { pTo->SetFloat( pSubData->GetName(), pSubData->GetFloat() ); break; } case KeyValues::TYPE_WSTRING: { pTo->SetWString( pSubData->GetName(), pSubData->GetWString() ); break; } case KeyValues::TYPE_COLOR: { pTo->SetColor( pSubData->GetName(), pSubData->GetColor() ); break; } case KeyValues::TYPE_UINT64: { pTo->SetUint64( pSubData->GetName(), pSubData->GetUint64() ); break; } default: break; } } } bool CEconItemDefinition::LoadFromKV( KeyValues *pDefinition ) { definition = pDefinition; GET_STRING( this, pDefinition, name ); GET_BOOL( this, pDefinition, show_in_armory ); GET_STRING( this, pDefinition, item_class ); GET_STRING( this, pDefinition, item_name ); GET_STRING( this, pDefinition, item_description ); GET_STRING( this, pDefinition, item_type_name ); const char *pszQuality = pDefinition->GetString( "item_quality" ); if ( pszQuality[0] ) { int iQuality = UTIL_StringFieldToInt( pszQuality, g_szQualityStrings, ARRAYSIZE( g_szQualityStrings ) ); if ( iQuality != -1 ) { item_quality = iQuality; } } GET_STRING( this, pDefinition, item_logname ); GET_STRING( this, pDefinition, item_iconname ); const char *pszLoadoutSlot = pDefinition->GetString( "item_slot" ); if ( pszLoadoutSlot[0] ) { item_slot = UTIL_StringFieldToInt( pszLoadoutSlot, g_LoadoutSlots, TF_LOADOUT_SLOT_COUNT ); } const char *pszAnimSlot = pDefinition->GetString( "anim_slot" ); if ( pszAnimSlot[0] ) { if ( V_strcmp( pszAnimSlot, "FORCE_NOT_USED" ) != 0 ) { anim_slot = UTIL_StringFieldToInt( pszAnimSlot, g_AnimSlots, TF_WPN_TYPE_COUNT ); } else { anim_slot = -2; } } GET_BOOL( this, pDefinition, baseitem ); GET_INT( this, pDefinition, min_ilevel ); GET_INT( this, pDefinition, max_ilevel ); GET_BOOL( this, pDefinition, loadondemand ); GET_STRING( this, pDefinition, image_inventory ); GET_INT( this, pDefinition, image_inventory_size_w ); GET_INT( this, pDefinition, image_inventory_size_h ); GET_STRING( this, pDefinition, model_player ); GET_STRING( this, pDefinition, model_vision_filtered ); GET_STRING( this, pDefinition, model_world ); GET_STRING( this, pDefinition, extra_wearable ); GET_STRING( this, pDefinition, extra_wearable_vm ); GET_INT( this, pDefinition, attach_to_hands ); GET_INT( this, pDefinition, attach_to_hands_vm_only ); GET_BOOL( this, pDefinition, act_as_wearable ); GET_BOOL( this, pDefinition, act_as_weapon ); GET_INT( this, pDefinition, hide_bodygroups_deployed_only ); GET_BOOL( this, pDefinition, is_reskin ); GET_BOOL( this, pDefinition, specialitem ); GET_BOOL( this, pDefinition, demoknight ); GET_STRING( this, pDefinition, holiday_restriction ); GET_INT( this, pDefinition, year ); GET_BOOL( this, pDefinition, is_custom_content ); GET_BOOL( this, pDefinition, is_cut_content ); GET_BOOL( this, pDefinition, is_multiclass_item ); GET_STRING( this, pDefinition, item_script ); const char *pszDropType = pDefinition->GetString("drop_type"); if ( pszDropType[0] ) { int iDropType = UTIL_StringFieldToInt( pszDropType, g_szDropTypeStrings, ARRAYSIZE( g_szDropTypeStrings ) ); if (iDropType != -1) { drop_type = iDropType; } } // Initialize all visuals for next section. for (int i = 0; i < TF_TEAM_VISUALS_COUNT; i++) { visual[i] = NULL; } FOR_EACH_SUBKEY( pDefinition, pSubData ) { if ( !V_stricmp( pSubData->GetName(), "capabilities" ) ) { GET_VALUES_FAST_BOOL( capabilities, pSubData ); } else if ( !V_stricmp( pSubData->GetName(), "tags" ) ) { GET_VALUES_FAST_BOOL( tags, pSubData ); } else if ( !V_stricmp( pSubData->GetName(), "model_player_per_class" ) ) { FOR_EACH_SUBKEY( pSubData, pClassData ) { const char *pszClass = pClassData->GetName(); if ( !V_stricmp( pszClass, "basename" ) ) { // Generic item, assign a model for every class. for ( int i = TF_FIRST_NORMAL_CLASS; i <= TF_LAST_NORMAL_CLASS; i++ ) { // Add to the player model per class. model_player_per_class[i] = UTIL_VarArgs( pClassData->GetString(), g_aRawPlayerClassNamesShort[i], g_aRawPlayerClassNamesShort[i], g_aRawPlayerClassNamesShort[i] ); } } else { // Check the class this item is for and assign it to them. int iClass = UTIL_StringFieldToInt( pszClass, g_aPlayerClassNames_NonLocalized, TF_CLASS_COUNT_ALL ); if ( iClass != -1 ) { // Valid class, assign to it. model_player_per_class[iClass] = pClassData->GetString(); } } } } else if ( !V_stricmp( pSubData->GetName(), "used_by_classes" ) ) { FOR_EACH_SUBKEY( pSubData, pClassData ) { const char *pszClass = pClassData->GetName(); int iClass = UTIL_StringFieldToInt( pszClass, g_aPlayerClassNames_NonLocalized, TF_CLASS_COUNT_ALL ); if ( iClass != -1 ) { used_by_classes |= ( 1 << iClass ); const char *pszSlotname = pClassData->GetString(); if ( pszSlotname[0] != '1' ) { int iSlot = UTIL_StringFieldToInt( pszSlotname, g_LoadoutSlots, TF_LOADOUT_SLOT_COUNT ); if ( iSlot != -1 ) item_slot_per_class[iClass] = iSlot; } } } } else if ( !V_stricmp( pSubData->GetName(), "attributes" ) ) { FOR_EACH_TRUE_SUBKEY( pSubData, pAttribData ) { static_attrib_t attribute; if ( !attribute.BInitFromKV_MultiLine( pAttribData ) ) continue; attributes.AddToTail( attribute ); } } else if ( !V_stricmp( pSubData->GetName(), "static_attrs" ) ) { FOR_EACH_SUBKEY( pSubData, pAttribData ) { static_attrib_t attribute; if ( !attribute.BInitFromKV_SingleLine( pAttribData ) ) continue; attributes.AddToTail( attribute ); } } else if (!V_strnicmp(pSubData->GetName(), "visuals", 7)) { // Figure out what team is this meant for. int iVisuals = UTIL_StringFieldToInt(pSubData->GetName(), g_TeamVisualSections, TF_TEAM_VISUALS_COUNT); if (iVisuals == TEAM_UNASSIGNED) { // Hacky: for standard visuals block, assign it to all teams at once. for (int team = 0; team < TF_TEAM_VISUALS_COUNT; team++) { if (team == TEAM_SPECTATOR) continue; ParseVisuals(pSubData, team); } } else if (iVisuals != -1 && iVisuals != TEAM_SPECTATOR) { ParseVisuals(pSubData, iVisuals); } } } return true; } void CEconItemDefinition::ParseVisuals( KeyValues *pKVData, int iIndex ) { PerTeamVisuals_t* pVisuals; if (visual[iIndex]) // If we have data already in here, load the previous data before adding new stuff. pVisuals = visual[iIndex]; else pVisuals = new PerTeamVisuals_t; // Build ourselves a fresh visual file. FOR_EACH_SUBKEY( pKVData, pVisualData ) { if ( !V_stricmp( pVisualData->GetName(), "use_visualsblock_as_base" ) ) { const char *pszBlockTeamName = pVisualData->GetString(); int iTeam = GetTeamVisualsFromString( pszBlockTeamName ); if ( iTeam != -1 ) { *pVisuals = *GetVisuals( iTeam ); } else { Warning( "Unknown visuals block: %s", pszBlockTeamName ); } } else if ( !V_stricmp( pVisualData->GetName(), "player_bodygroups" ) ) { GET_VALUES_FAST_BOOL( pVisuals->player_bodygroups, pVisualData ); } else if ( !V_stricmp( pVisualData->GetName(), "attached_models" ) ) { FOR_EACH_SUBKEY( pVisualData, pAttachData ) { AttachedModel_t attached_model; attached_model.model_display_flags = pAttachData->GetInt( "model_display_flags", AM_VIEWMODEL|AM_WORLDMODEL ); V_strcpy_safe( attached_model.model, pAttachData->GetString( "model" ) ); pVisuals->attached_models.AddToTail( attached_model ); } } else if ( !V_stricmp( pVisualData->GetName(), "custom_particlesystem" ) ) { pVisuals->custom_particlesystem = pVisualData->GetString( "system" ); } else if ( !V_stricmp( pVisualData->GetName(), "muzzle_flash" ) ) { // Fetching this similar to weapon script file parsing. pVisuals->muzzle_flash = pVisualData->GetString(); } else if ( !V_stricmp( pVisualData->GetName(), "tracer_effect" ) ) { // Fetching this similar to weapon script file parsing. pVisuals->tracer_effect = pVisualData->GetString(); } else if ( !V_stricmp( pVisualData->GetName(), "animation_replacement" ) ) { FOR_EACH_SUBKEY( pVisualData, pAnimData ) { int key = ActivityList_IndexForName( pAnimData->GetName() ); int value = ActivityList_IndexForName( pAnimData->GetString() ); if ( key != kActivityLookup_Missing && value != kActivityLookup_Missing ) { pVisuals->animation_replacement.Insert( key, value ); } } } else if ( !V_stricmp( pVisualData->GetName(), "playback_activity" ) ) { FOR_EACH_SUBKEY( pVisualData, pActivityData ) { int iPlaybackType = UTIL_StringFieldToInt( pActivityData->GetName(), g_WearableAnimTypeStrings, NUM_WEARABLEANIM_TYPES ); if ( iPlaybackType != -1 ) { activity_on_wearable_t activity; activity.playback = (wearableanimplayback_t)iPlaybackType; activity.activity = kActivityLookup_Unknown; activity.activity_name = pActivityData->GetString(); pVisuals->playback_activity.AddToTail( activity ); } } } else if ( !V_strnicmp( pVisualData->GetName(), "custom_sound", 12 ) ) { int iSound = 0; if ( pVisualData->GetName()[12] ) { iSound = Clamp( V_atoi( pVisualData->GetName() + 12 ), 0, MAX_CUSTOM_WEAPON_SOUNDS - 1 ); } pVisuals->aCustomWeaponSounds[ iSound ] = pVisualData->GetString(); } else if ( !V_strnicmp( pVisualData->GetName(), "sound_", 6 ) ) { // Advancing pointer past sound_ prefix... why couldn't they just make a subsection for sounds? int iSound = GetWeaponSoundFromString( pVisualData->GetName() + 6 ); if ( iSound != -1 ) { pVisuals->aWeaponSounds[ iSound ] = pVisualData->GetString(); } } else if ( !V_stricmp( pVisualData->GetName(), "styles" ) ) { FOR_EACH_SUBKEY( pVisualData, pStyleData ) { ItemStyle_t *style = new ItemStyle_t; GET_STRING( style, pStyleData, name ); GET_STRING( style, pStyleData, model_player ); GET_STRING( style, pStyleData, image_inventory ); GET_BOOL( style, pStyleData, selectable ); GET_INT( style, pStyleData, skin_red ); GET_INT( style, pStyleData, skin_blu ); for ( KeyValues *pStyleModelData = pStyleData->GetFirstSubKey(); pStyleModelData != NULL; pStyleModelData = pStyleModelData->GetNextKey() ) { if ( !V_stricmp( pStyleModelData->GetName(), "model_player_per_class" ) ) { GET_VALUES_FAST_STRING( style->model_player_per_class, pStyleModelData ); } } pVisuals->styles.AddToTail( style ); } } else if ( !V_stricmp( pVisualData->GetName(), "skin" ) ) { pVisuals->skin = pVisualData->GetInt(); } else if ( !V_stricmp( pVisualData->GetName(), "use_per_class_bodygroups" ) ) { pVisuals->use_per_class_bodygroups = pVisualData->GetInt(); } else if ( !V_stricmp( pVisualData->GetName(), "material_override" ) ) { pVisuals->material_override = pVisualData->GetString(); } else if ( !V_stricmp( pVisualData->GetName(), "vm_bodygroup_override" ) ) { pVisuals->vm_bodygroup_override = pVisualData->GetInt(); } else if ( !V_stricmp( pVisualData->GetName(), "vm_bodygroup_state_override" ) ) { pVisuals->vm_bodygroup_state_override = pVisualData->GetInt(); } else if ( !V_stricmp( pVisualData->GetName(), "wm_bodygroup_override" ) ) { pVisuals->wm_bodygroup_override = pVisualData->GetInt(); } else if ( !V_stricmp( pVisualData->GetName(), "wm_bodygroup_state_override" ) ) { pVisuals->wm_bodygroup_state_override = pVisualData->GetInt(); } } visual[ iIndex ] = pVisuals; } bool CEconAttributeDefinition::LoadFromKV( KeyValues *pDefinition ) { definition = pDefinition; GET_STRING_DEFAULT( this, pDefinition, name, "( unnamed )" ); GET_STRING( this, pDefinition, attribute_class ); GET_STRING( this, pDefinition, description_string ); string_attribute = ( V_stricmp( pDefinition->GetString( "attribute_type" ), "string" ) == 0 ); const char *szFormat = pDefinition->GetString( "description_format" ); description_format = UTIL_StringFieldToInt( szFormat, g_AttributeDescriptionFormats, ARRAYSIZE( g_AttributeDescriptionFormats ) ); const char *szEffect = pDefinition->GetString( "effect_type" ); effect_type = UTIL_StringFieldToInt( szEffect, g_EffectTypes, ARRAYSIZE( g_EffectTypes ) ); const char *szType = pDefinition->GetString( "attribute_type" ); type = GetItemSchema()->GetAttributeType( szType ); GET_BOOL( this, pDefinition, hidden ); GET_BOOL( this, pDefinition, stored_as_integer ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- template<typename T> class ISchemaAttributeTypeBase : public ISchemaAttributeType { public: virtual void InitializeNewEconAttributeValue( attrib_data_union_t *pValue ) const { if ( sizeof( T ) <= sizeof( uint32 ) ) new( &pValue->iVal ) T; else if ( sizeof( T ) <= sizeof( void * ) ) new( &pValue->bVal ) T; else pValue->bVal = (byte *)new T; } virtual void UnloadEconAttributeValue( attrib_data_union_t *pValue ) const { if ( sizeof( T ) <= sizeof( uint32 ) ) reinterpret_cast<T *>( &pValue->iVal )->~T(); else if ( sizeof( T ) <= sizeof( void * ) ) reinterpret_cast<T *>( &pValue->bVal )->~T(); else delete pValue->bVal; } virtual bool OnIterateAttributeValue( IEconAttributeIterator *pIterator, const CEconAttributeDefinition *pAttrDef, const attrib_data_union_t &value ) const { return pIterator->OnIterateAttributeValue( pAttrDef, GetTypedDataFromValue( value ) ); } private: T const &GetTypedDataFromValue( const attrib_data_union_t &value ) const { if ( sizeof( T ) <= sizeof( uint32 ) ) return *reinterpret_cast<const T *>( &value.iVal ); if ( sizeof( T ) <= sizeof( void* ) ) return *reinterpret_cast<const T *>( &value.bVal ); Assert( value.bVal ); return *reinterpret_cast<const T *>( value.bVal ); } }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CSchemaAttributeType_Default : public ISchemaAttributeTypeBase<unsigned int> { public: virtual bool BConvertStringToEconAttributeValue( const CEconAttributeDefinition *pAttrDef, const char *pString, attrib_data_union_t *pValue, bool bUnk = true ) const { if ( bUnk ) { double val = 0.0; if ( pString && pString[0] ) val = strtod( pString, NULL ); pValue->flVal = val; } else if ( pAttrDef->stored_as_integer ) { pValue->iVal = V_atoi64( pString ); } else { pValue->flVal = V_atof( pString ); } return true; } virtual void ConvertEconAttributeValueToString( const CEconAttributeDefinition *pAttrDef, const attrib_data_union_t &value, char *pString ) const { if ( pAttrDef->stored_as_integer ) { V_strcpy( pString, UTIL_VarArgs( "%u", value.iVal ) ); } else { V_strcpy( pString, UTIL_VarArgs( "%f", value.flVal ) ); } } }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CSchemaAttributeType_UInt64 : public ISchemaAttributeTypeBase<unsigned long long> { public: virtual bool BConvertStringToEconAttributeValue( const CEconAttributeDefinition *pAttrDef, const char *pString, attrib_data_union_t *pValue, bool bUnk = true ) const { *(pValue->lVal) = V_atoui64( pString ); return true; } virtual void ConvertEconAttributeValueToString( const CEconAttributeDefinition *pAttrDef, const attrib_data_union_t &value, char *pString ) const { V_strcpy( pString, UTIL_VarArgs( "%llu", *(value.lVal) ) ); } }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CSchemaAttributeType_Float : public ISchemaAttributeTypeBase<float> { public: virtual bool BConvertStringToEconAttributeValue( const CEconAttributeDefinition *pAttrDef, const char *pString, attrib_data_union_t *pValue, bool bUnk = true ) const { pValue->flVal = V_atof( pString ); return true; } virtual void ConvertEconAttributeValueToString( const CEconAttributeDefinition *pAttrDef, const attrib_data_union_t &value, char *pString ) const { V_strcpy( pString, UTIL_VarArgs( "%f", value.flVal ) ); } }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CSchemaAttributeType_String : public ISchemaAttributeTypeBase<CAttribute_String> { public: virtual bool BConvertStringToEconAttributeValue( const CEconAttributeDefinition *pAttrDef, const char *pString, attrib_data_union_t *pValue, bool bUnk = true ) const { *(pValue->sVal) = pString; return true; } virtual void ConvertEconAttributeValueToString( const CEconAttributeDefinition *pAttrDef, const attrib_data_union_t &value, char *pString ) const { if ( pAttrDef->string_attribute ) { V_strcpy( pString, *(value.sVal) ); } } }; //----------------------------------------------------------------------------- // Purpose: constructor //----------------------------------------------------------------------------- CEconItemSchema::CEconItemSchema() : m_Items( DefLessFunc(item_def_index_t) ), m_Attributes( DefLessFunc(attrib_def_index_t) ), m_PrefabsValues( StringLessThan ), m_bInited( false ) { } CEconItemSchema::~CEconItemSchema() { m_pSchema->deleteThis(); m_Items.PurgeAndDeleteElements(); m_Attributes.PurgeAndDeleteElements(); FOR_EACH_DICT_FAST( m_PrefabsValues, i ) { m_PrefabsValues[i]->deleteThis(); } FOR_EACH_VEC( m_AttributeTypes, i ) { delete m_AttributeTypes[i].pType; } } //----------------------------------------------------------------------------- // Purpose: Initializer //----------------------------------------------------------------------------- bool CEconItemSchema::Init( void ) { Reset(); KeyValuesAD schema("KVDataFile"); if ( !schema->LoadFromFile( filesystem, ITEMS_GAME ) ) return false; InitAttributeTypes(); float flStartTime = engine->Time(); ParseSchema( schema ); float flEndTime = engine->Time(); Msg( "Processing item schema took %.02fms. Parsed %d items and %d attributes.\n", ( flEndTime - flStartTime ) * 1000.0f, m_Items.Count(), m_Attributes.Count() ); return true; } void CEconItemSchema::InitAttributeTypes( void ) { FOR_EACH_VEC( m_AttributeTypes, i ) { delete m_AttributeTypes[i].pType; } m_AttributeTypes.Purge(); attr_type_t defaultType; defaultType.szName = NULL; defaultType.pType = new CSchemaAttributeType_Default; m_AttributeTypes.AddToTail( defaultType ); attr_type_t longType; longType.szName = "uint64"; longType.pType = new CSchemaAttributeType_UInt64; m_AttributeTypes.AddToTail( longType ); attr_type_t floatType; floatType.szName = "float"; floatType.pType = new CSchemaAttributeType_Float; m_AttributeTypes.AddToTail( floatType ); attr_type_t stringType; stringType.szName = "string"; stringType.pType = new CSchemaAttributeType_String; m_AttributeTypes.AddToTail( stringType ); } void CEconItemSchema::MergeDefinitionPrefabs( KeyValues *pDefinition, KeyValues *pSchemeData ) { char prefab[64]{0}; V_strcpy_safe( prefab, pSchemeData->GetString( "prefab" ) ); if ( prefab[0] != '\0' ) { //check if there's prefab for prefab.. PREFABSEPTION CUtlStringList strings; V_SplitString( prefab, " ", strings ); // traverse backwards in a adjective > noun style FOR_EACH_VEC_BACK( strings, i ) { KeyValues *pPrefabValues = NULL; FIND_ELEMENT( m_PrefabsValues, strings[i], pPrefabValues ); AssertMsg( pPrefabValues, "Unable to find prefab \"%s\".", strings[i] ); if ( pPrefabValues ) MergeDefinitionPrefabs( pDefinition, pPrefabValues ); } } InheritKVRec( pSchemeData, pDefinition ); } bool CEconItemSchema::LoadFromFile( void ) { KeyValuesAD schema("KVDataFile"); if ( !schema->LoadFromFile( g_pFullFileSystem, ITEMS_GAME ) ) return false; Reset(); ParseSchema( schema ); return true; } bool CEconItemSchema::LoadFromBuffer( CUtlBuffer &buf ) { KeyValuesAD schema("KVDataFile"); if ( !schema->ReadAsBinary( buf ) ) return false; Reset(); ParseSchema( schema ); return true; } bool CEconItemSchema::SaveToBuffer( CUtlBuffer &buf ) { m_pSchema->RecursiveSaveToFile( buf, 0 ); return true; } void CEconItemSchema::Reset( void ) { m_pSchema->deleteThis(); m_GameInfo.Purge(); m_Colors.Purge(); m_Qualities.Purge(); m_Items.PurgeAndDeleteElements(); m_Attributes.PurgeAndDeleteElements(); FOR_EACH_MAP_FAST( m_PrefabsValues, i ) { m_PrefabsValues[i]->deleteThis(); } m_PrefabsValues.Purge(); m_unSchemaResetCount++; } void CEconItemSchema::Precache( void ) { static CSchemaAttributeHandle pAttribDef_CustomProjectile( "custom projectile model" ); // Precache everything from schema. FOR_EACH_MAP_FAST( m_Items, i ) { CEconItemDefinition *pItem = m_Items[i]; // Precache models. if ( pItem->GetWorldModel() ) CBaseEntity::PrecacheModel( pItem->GetWorldModel() ); if ( pItem->GetPlayerModel() ) CBaseEntity::PrecacheModel( pItem->GetPlayerModel() ); for ( int iClass = 0; iClass < TF_CLASS_COUNT_ALL; iClass++ ) { if ( pItem->GetPerClassModel( iClass ) ) CBaseEntity::PrecacheModel( pItem->GetPerClassModel( iClass ) ); } if ( pItem->GetExtraWearableModel() ) CBaseEntity::PrecacheModel( pItem->GetExtraWearableModel() ); // Precache visuals. for ( int i = TEAM_UNASSIGNED; i < TF_TEAM_VISUALS_COUNT; i++ ) { if ( i == TEAM_SPECTATOR ) continue; PerTeamVisuals_t *pVisuals = pItem->GetVisuals( i ); if ( pVisuals == NULL ) continue; // Precache sounds. for ( int i = 0; i < NUM_SHOOT_SOUND_TYPES; i++ ) { if ( pVisuals->GetWeaponShootSound( i ) ) CBaseEntity::PrecacheScriptSound( pVisuals->GetWeaponShootSound( i ) ); } for ( int i = 0; i < MAX_CUSTOM_WEAPON_SOUNDS; i++ ) { if ( pVisuals->GetCustomWeaponSound( i ) ) CBaseEntity::PrecacheScriptSound( pVisuals->GetCustomWeaponSound( i ) ); } // Precache attachments. for ( int i = 0; i < pVisuals->attached_models.Count(); i++ ) { const char *pszModel = pVisuals->attached_models[i].model; if ( pszModel && pszModel[0] != '\0' ) CBaseEntity::PrecacheModel( pszModel ); } // Precache particles // Custom Particles if ( pVisuals->GetCustomParticleSystem() ) { PrecacheParticleSystem( pVisuals->GetCustomParticleSystem() ); } // Muzzle Flash if ( pVisuals->GetMuzzleFlash() ) { PrecacheParticleSystem( pVisuals->GetMuzzleFlash() ); } // Tracer Effect if ( pVisuals->GetTracerFX() ) { PrecacheParticleSystem( pVisuals->GetTracerFX() ); //Since these get adjusted we need to do each one manually as a char. char pTracerEffect[128]; char pTracerEffectCrit[128]; Q_snprintf( pTracerEffect, sizeof(pTracerEffect), "%s_red", pVisuals->GetTracerFX() ); Q_snprintf( pTracerEffectCrit, sizeof(pTracerEffectCrit), "%s_red_crit", pVisuals->GetTracerFX() ); PrecacheParticleSystem( pTracerEffect ); PrecacheParticleSystem( pTracerEffectCrit ); Q_snprintf( pTracerEffect, sizeof(pTracerEffect), "%s_blue", pVisuals->GetTracerFX() ); Q_snprintf( pTracerEffectCrit, sizeof(pTracerEffectCrit), "%s_blue_crit", pVisuals->GetTracerFX() ); PrecacheParticleSystem( pTracerEffect ); PrecacheParticleSystem( pTracerEffectCrit ); } } // Cache all attrbute names. FOR_EACH_VEC( pItem->attributes, i ) { static_attrib_t const &attrib = pItem->attributes[i]; const CEconAttributeDefinition *pAttribute = attrib.GetStaticData(); // Special case for custom_projectile_model attribute. if ( pAttribute == pAttribDef_CustomProjectile ) { CBaseEntity::PrecacheModel( attrib.value ); } } } } void CEconItemSchema::ParseSchema( KeyValues *pKVData ) { m_pSchema = pKVData->MakeCopy(); KeyValues *pPrefabs = pKVData->FindKey( "prefabs" ); if ( pPrefabs ) { ParsePrefabs( pPrefabs ); } KeyValues *pGameInfo = pKVData->FindKey( "game_info" ); if ( pGameInfo ) { ParseGameInfo( pGameInfo ); } KeyValues *pQualities = pKVData->FindKey( "qualities" ); if ( pQualities ) { ParseQualities( pQualities ); } KeyValues *pColors = pKVData->FindKey( "colors" ); if ( pColors ) { ParseColors( pColors ); } KeyValues *pAttributes = pKVData->FindKey( "attributes" ); if ( pAttributes ) { ParseAttributes( pAttributes ); } KeyValues *pItems = pKVData->FindKey( "items" ); if ( pItems ) { ParseItems( pItems ); } #if defined( TF_VINTAGE ) || defined( TF_VINTAGE_CLIENT ) // TF2V exclusive lists start here. // None of these are necessary but they help in organizing the item schema. // Stockweapons is just for cataloging stock content. KeyValues *pStockItems = pKVData->FindKey( "stockitems" ); if ( pStockItems ) { ParseItems( pStockItems ); } // Base Unlocks catalogs the standard unlock weapons. KeyValues *pUnlockItems = pKVData->FindKey( "unlockitems" ); if ( pUnlockItems ) { ParseItems( pUnlockItems ); } #if defined(CLIENT_DLL) if ( !CommandLine()->CheckParm( "-hidecosmetics" ) ) #endif { // Stock Cosmetics are for the typical cosmetics. KeyValues *pCosmeticItems = pKVData->FindKey( "cosmeticitems" ); if ( pCosmeticItems ) { ParseItems( pCosmeticItems ); } } #if defined(CLIENT_DLL) if ( !CommandLine()->CheckParm( "-hidereskins" ) ) #endif { // Reskins is for reskin weapons. KeyValues *pReskinItems = pKVData->FindKey( "reskinitems" ); if ( pReskinItems ) { ParseItems( pReskinItems ); } } // Everything below should be largely static and not change much. // Special is for special top secret items. KeyValues *pSpecialItems = pKVData->FindKey( "specialitems" ); if ( pSpecialItems ) { ParseItems( pSpecialItems ); } // Medals is well, player medals. KeyValues *pMedals = pKVData->FindKey( "medals" ); if ( pMedals ) { ParseItems( pMedals ); } // Holiday is for content relating to events, like Halloween or Christmas. KeyValues *pHoliday = pKVData->FindKey( "holiday" ); if ( pHoliday ) { ParseItems( pHoliday ); } #endif } void CEconItemSchema::ParseGameInfo( KeyValues *pKVData ) { FOR_EACH_SUBKEY( pKVData, pSubData ) { m_GameInfo.Insert( pSubData->GetName(), pSubData->GetFloat() ); } } void CEconItemSchema::ParseQualities( KeyValues *pKVData ) { FOR_EACH_SUBKEY( pKVData, pSubData ) { EconQuality Quality; GET_INT( &Quality , pSubData, value ); m_Qualities.Insert( pSubData->GetName(), Quality ); } } void CEconItemSchema::ParseColors( KeyValues *pKVData ) { FOR_EACH_SUBKEY( pKVData, pSubData ) { EconColor ColorDesc; GET_STRING( &ColorDesc, pSubData, color_name ); m_Colors.Insert( pSubData->GetName(), ColorDesc ); } } void CEconItemSchema::ParsePrefabs( KeyValues *pKVData ) { FOR_EACH_TRUE_SUBKEY( pKVData, pSubData ) { if ( GetItemSchema()->m_PrefabsValues.IsValidIndex( GetItemSchema()->m_PrefabsValues.Find( pSubData->GetName() ) ) ) { Warning( "Duplicate prefab name (%s)\n", pSubData->GetName() ); continue; } KeyValues *Values = pSubData->MakeCopy(); m_PrefabsValues.Insert( pSubData->GetName(), Values ); } } void CEconItemSchema::ParseItems( KeyValues *pKVData ) { FOR_EACH_TRUE_SUBKEY( pKVData, pSubData ) { // Skip over default item, not sure why it's there. if ( V_stricmp( pSubData->GetName(), "default" ) == 0 ) continue; CEconItemDefinition *pItem = new CEconItemDefinition; int index = V_atoi( pSubData->GetName() ); pItem->index = index; KeyValues *pDefinition = new KeyValues( pSubData->GetName() ); MergeDefinitionPrefabs( pDefinition, pSubData ); pItem->LoadFromKV( pDefinition ); m_Items.Insert( index, pItem ); } } void CEconItemSchema::ParseAttributes( KeyValues *pKVData ) { FOR_EACH_TRUE_SUBKEY( pKVData, pSubData ) { CEconAttributeDefinition *pAttribute = new CEconAttributeDefinition; pAttribute->index = V_atoi( pSubData->GetName() ); pAttribute->LoadFromKV( pSubData->MakeCopy() ); m_Attributes.Insert( pAttribute->index, pAttribute ); } } void CEconItemSchema::ClientConnected( edict_t *pClient ) { } void CEconItemSchema::ClientDisconnected( edict_t *pClient ) { } CEconItemDefinition *CEconItemSchema::GetItemDefinition( int id ) { CEconItemDefinition *itemdef = NULL; FIND_ELEMENT( m_Items, id, itemdef ); return itemdef; } CEconItemDefinition *CEconItemSchema::GetItemDefinitionByName( const char *name ) { FOR_EACH_MAP_FAST( m_Items, i ) { if ( !V_stricmp( m_Items[i]->GetName(), name ) ) { return m_Items[i]; } } return NULL; } CEconAttributeDefinition *CEconItemSchema::GetAttributeDefinition( int id ) { CEconAttributeDefinition *itemdef = NULL; FIND_ELEMENT( m_Attributes, id, itemdef ); return itemdef; } CEconAttributeDefinition *CEconItemSchema::GetAttributeDefinitionByName( const char *name ) { FOR_EACH_MAP_FAST( m_Attributes, i ) { if ( !V_stricmp( m_Attributes[i]->GetName(), name ) ) { return m_Attributes[i]; } } return NULL; } CEconAttributeDefinition *CEconItemSchema::GetAttributeDefinitionByClass( const char *classname ) { FOR_EACH_MAP_FAST( m_Attributes, i ) { if ( !V_stricmp( m_Attributes[i]->GetClassName(), classname ) ) { return m_Attributes[i]; } } return NULL; } ISchemaAttributeType *CEconItemSchema::GetAttributeType( const char *name ) const { FOR_EACH_VEC( m_AttributeTypes, i ) { if ( m_AttributeTypes[i].szName == name ) return m_AttributeTypes[i].pType; } return NULL; }
27.156202
170
0.670924
TF2V
edf9aa2ac8977d639dd63540255307c2d55bc5c0
679
hpp
C++
src/Operators/HashJoin.hpp
elordin/dbimpl
4aa1ef8f9921bf3dc77752a139772a54a7e65663
[ "MIT" ]
null
null
null
src/Operators/HashJoin.hpp
elordin/dbimpl
4aa1ef8f9921bf3dc77752a139772a54a7e65663
[ "MIT" ]
4
2016-05-03T11:54:07.000Z
2016-05-03T13:49:46.000Z
src/Operators/HashJoin.hpp
elordin/dbimpl
4aa1ef8f9921bf3dc77752a139772a54a7e65663
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <vector> #include <unordered_map> #include "Register.hpp" #include "Operator.cpp" class HashJoin : public Operator{ private: Operator* leftOp; Operator* rightOp; unsigned regIdLeft; unsigned regIdRight; vector<Register*> result; std::unordered_map<uint64_t, vector<Register*>> hashTable; public: //initialized with two input operators, and two register IDs. One ID is from the left side and one is from the right side. HashJoin(Operator* leftOp, Operator* rightOp, unsigned regIdLeft, unsigned regIdRight); void open(); bool next(); std::vector<Register*> getOutput(); void close(); ~HashJoin(); };
20.575758
124
0.721649
elordin
edfb2eacd1a1f34fd64cb2ecba611bf9aceb1102
526
cpp
C++
test/test_main_storage.cpp
karimdavoodi/iptv_rest
93fdc83ce9ace2c733179caf26394d8aaa010de0
[ "MIT" ]
1
2020-09-16T01:45:24.000Z
2020-09-16T01:45:24.000Z
test/test_main_storage.cpp
karimdavoodi/iptv_rest
93fdc83ce9ace2c733179caf26394d8aaa010de0
[ "MIT" ]
null
null
null
test/test_main_storage.cpp
karimdavoodi/iptv_rest
93fdc83ce9ace2c733179caf26394d8aaa010de0
[ "MIT" ]
null
null
null
#include <iostream> #include <catch.hpp> #include "../src/main_storage.hpp" TEST_CASE("test of MainStorage","") { return; MainStorage st; nlohmann::json j = st.getJson("configs",""); REQUIRE(j.size() > 0); REQUIRE(j["login"].size() > 0 ); REQUIRE(j["login"]["admin"].size() == 1); j["login"]["new_user"] = "mac"; st.setJson("configs", "login", j["login"]); nlohmann::json j2 = st.getJson("configs","login"); REQUIRE(j2["admin"].size() == 1); }
27.684211
58
0.534221
karimdavoodi
edfcb02eb3220da7d366edea719bead076aa049e
1,141
hpp
C++
PP/tuple/find.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
3
2019-07-12T23:12:24.000Z
2019-09-05T07:57:45.000Z
PP/tuple/find.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
PP/tuple/find.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
#pragma once #include <PP/size_t.hpp> #include <PP/tuple/find_index_state.hpp> #include <PP/tuple/fold.hpp> #include <PP/utility/move.hpp> namespace PP::tuple { PP_CIA find = [](auto&& predicate, concepts::tuple auto&& tuple) { return PP_CV_MEMBER( foldl( [PP_FWL(predicate)](concepts::value auto&& s, auto&& element) { constexpr auto state = PP_GV(s); static_assert( concepts::value<decltype(predicate(PP_F(element)))>, "tuple::find: the predicate must return a " "concepts::value"); if constexpr (state.found || PP_GV(predicate(PP_F(element)))) return value<detail::tuple_find_index_state(state.index, true)>; else return value<detail::tuple_find_index_state(state.index + 1, false)>; }, value<detail::tuple_find_index_state(0, false)>, PP_F(tuple)), index); }; }
33.558824
80
0.496933
Petkr
61016ee7ef89395223351d703fa1d3e7bef0b069
4,260
cpp
C++
src/components/input/mipyuv420fileinput.cpp
xchbx/fox
12787683ba10db8f5eedf21e2d0e7a63bebc1664
[ "Apache-2.0" ]
2
2019-04-12T10:26:43.000Z
2019-06-21T15:20:11.000Z
src/components/input/mipyuv420fileinput.cpp
xchbx/fox
12787683ba10db8f5eedf21e2d0e7a63bebc1664
[ "Apache-2.0" ]
1
2018-08-25T14:55:07.000Z
2018-08-25T14:55:07.000Z
src/components/input/mipyuv420fileinput.cpp
xchbx/NetCamera
12787683ba10db8f5eedf21e2d0e7a63bebc1664
[ "Apache-2.0" ]
1
2020-12-31T08:52:03.000Z
2020-12-31T08:52:03.000Z
/* This file is a part of EMIPLIB, the EDM Media over IP Library. Copyright (C) 2006-2016 Hasselt University - Expertise Centre for Digital Media (EDM) (http://www.edm.uhasselt.be) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mipconfig.h" #include "mipyuv420fileinput.h" #include "miprawvideomessage.h" #include "mipsystemmessage.h" #define MIPYUV420FILEINPUT_ERRSTR_ALREADYOPEN "A file has already been opened" #define MIPYUV420FILEINPUT_ERRSTR_NOTOPEN "No file has been opened yet" #define MIPYUV420FILEINPUT_ERRSTR_BADMESSAGE "Only a MIPSYSTEMMESSAGE_TYPE_ISTIME system message is allowed as input" #define MIPYUV420FILEINPUT_ERRSTR_CANTOPEN "Unable to open the specified file" #define MIPYUV420FILEINPUT_ERRSTR_INVALIDDIMENSION "An invalid width or height was specified" #define MIPYUV420FILEINPUT_ERRSTR_DIMENSIONNOTEVEN "Both width and height should be even numbers" MIPYUV420FileInput::MIPYUV420FileInput() : MIPComponent("MIPYUV420FileInput") { m_pFile = 0; m_width = 0; m_height = 0; m_frameSize = 0; m_pData = 0; m_pVideoMessage = 0; m_gotMessage = false; } MIPYUV420FileInput::~MIPYUV420FileInput() { close(); } bool MIPYUV420FileInput::open(const std::string &fileName, int width, int height) { if (m_pFile != 0) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_ALREADYOPEN); return false; } if (width < 1 || height < 1) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_INVALIDDIMENSION); return false; } if ((width%2 != 0) || (height%2 != 0)) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_DIMENSIONNOTEVEN); return false; } FILE *pFile = fopen(fileName.c_str(), "rb"); if (pFile == 0) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_CANTOPEN); return false; } m_pFile = pFile; m_width = width; m_height = height; m_frameSize = (width*height*3)/2; m_pData = new uint8_t[m_frameSize]; m_pVideoMessage = new MIPRawYUV420PVideoMessage(width, height, m_pData, false); m_gotMessage = false; return true; } bool MIPYUV420FileInput::close() { if (m_pFile == 0) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_NOTOPEN); return false; } fclose(m_pFile); delete m_pVideoMessage; delete [] m_pData; m_width = 0; m_height = 0; m_frameSize = 0; m_pFile = 0; m_pData = 0; m_pVideoMessage = 0; return true; } bool MIPYUV420FileInput::push(const MIPComponentChain &chain, int64_t iteration, MIPMessage *pMsg) { if ( !(pMsg->getMessageType() == MIPMESSAGE_TYPE_SYSTEM && pMsg->getMessageSubtype() == MIPSYSTEMMESSAGE_TYPE_ISTIME) ) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_BADMESSAGE); return false; } if (m_pFile == 0) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_NOTOPEN); return false; } bool done = false; bool rewound = false; while (!done) { int num = fread(m_pData, 1, m_frameSize, m_pFile); if (num <= 0) { if (!rewound) { rewound = true; fseek(m_pFile, 0, SEEK_SET); } else { memset(m_pData, 0, m_frameSize); done = true; } } else if (num < m_frameSize) { memset(m_pData+num, 0, (m_frameSize-num)); fseek(m_pFile, 0, SEEK_SET); done = true; } else // read the correct amount { done = true; } } m_gotMessage = false; return true; } bool MIPYUV420FileInput::pull(const MIPComponentChain &chain, int64_t iteration, MIPMessage **pMsg) { if (m_pFile == 0) { setErrorString(MIPYUV420FILEINPUT_ERRSTR_NOTOPEN); return false; } if (!m_gotMessage) { m_gotMessage = true; *pMsg = m_pVideoMessage; } else { m_gotMessage = false; *pMsg = 0; } return true; }
23.027027
120
0.721127
xchbx
6103aad785badd38907e5e8b243235f96b1c7cee
640
cpp
C++
example/IconWindow.cpp
laferenorg/FGame
488386054ef375e838d00afc5e771dd088050cb2
[ "MIT" ]
2
2021-06-22T02:38:51.000Z
2021-06-22T11:46:24.000Z
example/IconWindow.cpp
laferenorg/FGame
488386054ef375e838d00afc5e771dd088050cb2
[ "MIT" ]
1
2021-07-16T03:49:15.000Z
2021-07-16T03:49:15.000Z
example/IconWindow.cpp
laferenorg/FGame
488386054ef375e838d00afc5e771dd088050cb2
[ "MIT" ]
2
2021-06-22T11:46:36.000Z
2021-06-23T06:10:35.000Z
/* Script example: Icon Window */ /* Include header C++ */ #include <iostream> #include <string> /* Include header FGame */ #include <FGame.hpp> void handleEventsAndExtendUpdate(SDL_Event& event, FGameV2* fgame) { /* Set Background */ fgame->SetBackground({ 0, 255, 0 }); } void update(FGameV2* fgame) { /* Code here */ } int main(int argc, const char* argv[]) { /* Create manger */ FGameV2 Manager = FGameV2({ FG_INIT }, "Simple Window"); /* Set icon */ Manager.SetIcon("assets/Img/icon.png"); /* Start looping */ Manager.StartLooping(handleEventsAndExtendUpdate, update, 60); { (void)argc; (void)argv; } return 0; }
19.393939
68
0.665625
laferenorg